forked from theodi/nodejs-oauth-template
-
Notifications
You must be signed in to change notification settings - Fork 1
/
adaptHandler.js
794 lines (686 loc) · 28.1 KB
/
adaptHandler.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
var ObjectId = require('mongodb').ObjectID;
const cheerio = require('cheerio');
const { ObjectID } = require('bson');
const { Parser } = require('@json2csv/plainjs'); // Library to create CSV for output
async function getObjectById(dbConnect, collection, id) {
collection = collection + "s";
return new Promise(async (resolve, reject) => {
try {
const items = await dbConnect.collection(collection).find({ "_id": new ObjectId(id) }).toArray();
if (items.length === 0) {
resolve(null); // Object not found, return null
} else {
const objectData = items[0];
// Check if the object has a tags array
if (objectData.tags && Array.isArray(objectData.tags) && objectData.tags.length > 0) {
const tagIds = objectData.tags.map(tag => new ObjectId(tag));
// Query the tags collection to get tag titles
const tagItems = await dbConnect.collection("tags").find({ "_id": { $in: tagIds } }).toArray();
// Convert the tags array to objects with _tagId and title
const tagsWithTitles = tagItems.map(tagItem => ({ _tagId: tagItem._id, title: tagItem.title }));
// Update the objectData with the tags with titles
objectData.tags = tagsWithTitles;
}
resolve(objectData);
}
} catch (err) {
reject(err);
}
});
}
exports.getObjectById = async function(req, res, dbo, collection, id) {
const dbConnect = dbo.getDb();
try {
const objectData = await getObjectById(dbConnect, collection, id);
if (!objectData) {
console.log("Object not found");
return res.status(404).json({ error: "Object not found" });
}
res.set('Content-Type', 'application/json');
res.send(JSON.stringify(objectData, null, 4));
} catch (err) {
console.error("Error:", err);
res.status(500).json({ error: "An error occurred" });
}
};
exports.findObjectsWithParentId = function(req,res,dbo,collection,parent_id) {
var dbConnect = dbo.getDb();
dbConnect
.collection(collection)
.find({"_parentId":new ObjectId(parent_id)})
.toArray(function(err,items) {
// TODO error handling
res.set('Content-Type', 'application/json');
res.send(JSON.stringify(items, null, 4));
});
}
async function getItemsFromCollection(dbConnect, collection) {
return await dbConnect.collection(collection).find({}).toArray();
}
exports.getObjectsFromCollection = async function(req, res, dbo, collection) {
const dbConnect = dbo.getDb();
try {
const items = await getItemsFromCollection(dbConnect, collection);
res.set('Content-Type', 'application/json');
res.send(JSON.stringify(items, null, 4));
} catch (err) {
console.error("Error:", err);
res.status(500).json({ error: "An error occurred" });
}
};
function stripHtmlTags(input) {
if (!input) {
return input;
}
return input.replace(/<[^>]*>/g, " ");
}
function htmlToPlainText(html) {
// Load the HTML string into a Cheerio instance
const $ = cheerio.load(html);
// Find all <li> elements
const listItems = $('li');
// Iterate over each <li> element
listItems.each((index, listItem) => {
// Get the text content of the <li> element
const listItemText = $(listItem).text().trim();
// Determine whether to add a newline at the beginning or end
const newline = index === 0 ? '\n' : '';
// Replace the <li> element with a plain text equivalent with a dash and newline
$(listItem).replaceWith(`${newline}- ${listItemText}${index === listItems.length - 1 ? '' : '\n'}`);
});
// Get the text content of the modified HTML
const plainText = $('body').text().trim();
return plainText;
}
async function getWordCount(object) {
var count = 0;
// Calculate word count for displayTitle and body
if (object.displayTitle && typeof object.displayTitle === 'string') {
count += object.displayTitle.split(/\s+/).length;
}
if (object.body && typeof object.body === 'string') {
// Strip HTML tags from the body before calculating word count
const bodyWithoutHtml = stripHtmlTags(object.body);
count += bodyWithoutHtml.split(/\s+/).length;
}
if (
object._extensions &&
object._extensions._extra &&
object._extensions._extra._items &&
Array.isArray(object._extensions._extra._items)
) {
object._extensions._extra._items.forEach(item => {
if (item.title && typeof item.title === 'string') {
count += item.title.split(/\s+/).length;
}
if (item.body && typeof item.body === 'string') {
// Strip HTML tags from the item's body before calculating word count
const itemBodyWithoutHtml = stripHtmlTags(item.body);
count += itemBodyWithoutHtml.split(/\s+/).length;
}
});
}
if (object.properties && object.properties._items && Array.isArray(object.properties._items)) {
object.properties._items.forEach(propertyItem => {
if (propertyItem.displayTitle && typeof propertyItem.displayTitle === 'string') {
count += propertyItem.displayTitle.split(/\s+/).length;
}
if (propertyItem.body && typeof propertyItem.body === 'string') {
// Strip HTML tags from the property item's body before calculating word count
const propertyBodyWithoutHtml = stripHtmlTags(propertyItem.body);
count += propertyBodyWithoutHtml.split(/\s+/).length;
}
if (propertyItem.text && typeof propertyItem.text === 'string') {
count += propertyItem.text.split(/\s+/).length;
}
});
}
// Calculate word count for properties._feedback.correct and strip HTML tags
if (
object.properties &&
object.properties._feedback &&
object.properties._feedback.correct &&
typeof object.properties._feedback.correct === 'string'
) {
const feedbackCorrectWithoutHtml = stripHtmlTags(object.properties._feedback.correct);
count += feedbackCorrectWithoutHtml.split(/\s+/).length;
}
return count;
}
async function buildContentData(dbConnect, id) {
const contentCollection = "contentobjects";
const articlesCollection = "articles";
const blocksCollection = "blocks";
const componentsCollection = "components";
const contentData = await dbConnect.collection(contentCollection).findOne({ "_id": new ObjectId(id) });
if (!contentData) {
throw new Error("Content object not found");
}
const articlesData = await dbConnect.collection(articlesCollection).find({ "_parentId": new ObjectId(id) }).toArray();
contentData.totalArticleCount = articlesData.length;
contentData.totalBlockCount = 0;
contentData.totalComponentCount = 0;
contentData.assessmentCount = 0;
contentData.questionCount = 0;
contentData.wordCount = 0;
for (const article of articlesData) {
try {
if (article._extensions._assessment._isEnabled === true) {
contentData.assessmentCount += 1;
}
} catch (err) {}
article.wordCount = await getWordCount(article);
contentData.wordCount += article.wordCount;
const blocksData = await dbConnect.collection(blocksCollection).find({ "_parentId": new ObjectId(article._id) }).toArray();
article.totalComponentCount = 0;
for (const block of blocksData) {
block.wordCount = await getWordCount(block);
contentData.wordCount += block.wordCount;
const componentsData = await dbConnect.collection(componentsCollection).find({ "_parentId": new ObjectId(block._id) }).toArray();
for (const component of componentsData) {
component.wordCount = await getWordCount(component);
block.wordCount += component.wordCount;
contentData.wordCount += component.wordCount;
component.isQuestion = false;
try {
if (component.properties._feedback) {
component.isQuestion = true;
contentData.questionCount += 1;
}
} catch (err) {}
}
article.wordCount += block.wordCount;
block.components = componentsData;
block.componentCount = componentsData.length;
article.totalComponentCount += block.componentCount;
contentData.totalComponentCount += block.componentCount;
}
blocksData.sort((a, b) => a._sortOrder - b._sortOrder);
article.blocks = blocksData;
contentData.totalBlockCount += blocksData.length;
}
articlesData.sort((a, b) => a._sortOrder - b._sortOrder);
contentData.articles = articlesData;
return contentData;
}
async function buildCache(dbConnect) {
const contentCollection = "contentobjects";
try {
// Step 1: Get all contentobjects
const contentObjects = await getItemsFromCollection(dbConnect, contentCollection);
const contentObjectsData = await Promise.all(contentObjects.map(async (contentObject) => {
// Step 2: Get courseData
const courseData = await getObjectById(dbConnect, "course", contentObject._courseId);
// Step 3: Build contentData
const contentData = await buildContentData(dbConnect, contentObject._id);
// Step 4: Collate data
const tagTitles = (courseData.tags || []).map(tag => tag.title).join(', ');
const collatedContentObject = {
_id: contentObject._id,
_courseId: contentObject._courseId,
courseTitle: courseData.displayTitle,
title: contentObject.displayTitle,
tags: tagTitles,
totalArticleCount: contentData.totalArticleCount,
totalBlockCount: contentData.totalBlockCount,
totalComponentCount: contentData.totalComponentCount,
assessmentCount: contentData.assessmentCount,
questionCount: contentData.questionCount,
wordCount: contentData.wordCount,
};
return collatedContentObject;
}));
return contentObjectsData;
} catch (err) {
throw err;
}
}
async function updateCache(sourcedb, destinationdb) {
try {
const sourceDbConnect = sourcedb.getDb();
const destinationDbConnect = destinationdb.getDb();
// Step 1: Get cache data from sourceDb
console.log("Updating cache");
const cacheData = await buildCache(sourceDbConnect);
// Step 2: Delete existing data in the courseCache collection of destinationDb
await destinationDbConnect.collection("courseCache").deleteMany({});
// Step 3: Insert the new cache data into the courseCache collection
await destinationDbConnect.collection("courseCache").insertMany(cacheData);
console.log("Cache updated successfully.");
} catch (err) {
console.error("Error:", err);
}
}
exports.updateCourseCache = async function (sourcedb, destinationdb) {
updateCache(sourcedb,destinationdb);
};
exports.getCacheData = async function (req, res, sourceDb, cacheDb) {
try {
const dbConnect = cacheDb.getDb(); // Use cacheDb as the default source
// Check if forceUpdate is set to true in the request
const forceUpdate = req.query.forceUpdate === 'true';
if (forceUpdate) {
// If forceUpdate is true, update the cache and then read it
await updateCache(sourceDb, cacheDb); // Assuming you have an updateCache function
}
// Read all objects from the courseCache collection in cacheDb
const cachedContentObjects = await dbConnect.collection("courseCache").find({}).toArray();
// Content negotiation based on Accept header
const acceptHeader = req.headers['accept'];
if (acceptHeader.includes('text/csv')) {
// Respond with CSV
const parser = new Parser({ header: true });
const csv = parser.parse(cachedContentObjects);
res.set('Content-Type', 'text/csv');
res.send(csv);
} else {
// Default to JSON
res.set('Content-Type', 'application/json');
res.json(cachedContentObjects);
}
} catch (err) {
console.error("Error:", err);
res.status(500).json({ error: "An error occurred" });
}
};
function isQuestion(components){
let primaryComponent;
if (components.length === 1) {
// If there's only one component, it's the primary component
primaryComponent = components[0];
} else {
// Check for a component with .properties._feedback
const feedbackComponent = components.find(component => component.properties && component.properties._feedback);
if (feedbackComponent) {
return true;
} else {
return false;
}
}
};
function getElementAsJson(data, question) {
let json = {};
if (data.displayTitle.trim() !== "") {
json.title = data.displayTitle.trim();
json.type = question ? "Question" : "Title";
}
if (data.body.trim() !== "") {
json.body = data.body.trim(); // Retain HTML content as is
}
if (data._extensions && data._extensions._extra && data._extensions._extra._isEnabled === true) {
json.extraItems = (data._extensions._extra._items || []).map(item => {
let extraItem = {};
if (item.title.trim() !== "") {
extraItem.title = item.title.trim();
}
if (item.body.trim() !== "") {
extraItem.body = item.body.trim(); // Retain HTML content as is
}
return extraItem;
});
}
if (data.properties) {
json.properties = {};
if (data.properties._feedback) {
json.properties.instruction = data.properties.instruction;
json.properties.items = (data.properties._items || []).map(item => {
let itemDetails = {};
if (item._options) {
itemDetails.text = item.text.trim(); // Retain HTML content as is
itemDetails.options = (item._options || []).map(option => ({
text: option.text.trim(),
isCorrect: option._isCorrect
}));
} else {
itemDetails.text = item.text.trim(); // Retain HTML content as is
itemDetails.shouldBeSelected = item._shouldBeSelected;
}
return itemDetails;
});
json.properties.feedback = {
correct: data.properties._feedback.correct ? data.properties._feedback.correct.trim() : undefined,
incorrect: data.properties._feedback._incorrect.final ? data.properties._feedback._incorrect.final.trim() : undefined
};
} else {
json.properties.instruction = data.properties.instruction;
if (data.properties._completionBody) {
json.properties.completionBody = data.properties._completionBody.trim();
}
json.properties.items = (data.properties._items || []).map(item => {
let itemDetails = {};
if (item.title !== "") {
itemDetails.title = item.title;
}
if (item.body !== "") {
itemDetails.body = item.body; // Retain HTML content as is
}
if (item.text !== "") {
itemDetails.text = item.text; // Retain HTML content as is
}
return itemDetails;
});
}
}
return json;
}
function getElementAsText(data,question) {
var ret = "";
if (data.displayTitle.trim() != "") {
if (question) {
ret += "Question:";
} else {
ret += "Title:"
}
ret += data.displayTitle.trim() + "\n";
}
if (data.body.trim() != "") {
ret += stripHtmlTags(htmlToPlainText(data.body)).replace(/ /g, ' ').trim() + "\n\n";
}
if (data._extensions && data._extensions._extra && data._extensions._extra._isEnabled === true) {
(data._extensions._extra._items).forEach(item => {
if (item.title.trim() != "") {
ret += item.title.trim() + "\n";
}
if (item.body.trim() != "") {
ret += stripHtmlTags(htmlToPlainText(item.body)).replace(/ /g, ' ').trim() + "\n\n";
}
});
}
if (data.properties) {
if (data.properties._feedback) {
//Question instruction
ret += data.properties.instruction + "\n";
try {
(data.properties._items).forEach(item => {
if(item._options) {
if (item.text) {
ret += "- " + stripHtmlTags(item.text).replace(/ /g, ' ').trim();
}
(item._options).forEach(option => {
if (option._isCorrect) {
ret += " (Correct answer: " + option.text + ")";
}
});
ret += "\n";
} else {
if (item._shouldBeSelected) {
ret += "- Correct answer: " + stripHtmlTags(item.text).replace(/ /g, ' ').trim() + "\n";
} else {
ret += "- Incorrect answer: " + stripHtmlTags(item.text).replace(/ /g, ' ').trim() + "\n";
}
}
});
} catch(err) {}
ret += "\n";
if ( data.properties._feedback.correct ) {
ret += "Feedback for correct answer: " + stripHtmlTags(data.properties._feedback.correct).replace(/ /g, ' ').trim() + "\n\n";
}
if (data.properties._feedback._incorrect.final ) {
ret += "Feedback for incorrect answer: " + stripHtmlTags(data.properties._feedback._incorrect.final).replace(/ /g, ' ').trim() + "\n\n";
}
} else {
//Question instruction
ret += data.properties.instruction + "\n";
if (data.properties._completionBody) {
ret += data.properties._completionBody.trim() + "\n";
}
//Question items
try {
(data.properties._items).forEach(item => {
if (item.title.trim() != "") {
ret += item.title.trim() + "\n";
if (item.body.trim() != "") {
ret += stripHtmlTags(item.body).replace(/ /g, ' ').trim() + "\n\n";
}
} else {
if (item.body.trim() != "") {
ret += stripHtmlTags(item.body).replace(/ /g, ' ').trim() + "\n";
}
if (item.text.trim() != "") {
ret += stripHtmlTags(item.text).replace(/ /g, ' ').trim() + "\n";
}
}
});
} catch (err) {
//console.log(err);
}
}
}
//Feeedback
return ret;
}
function countWords(text) {
// Use regular expression to count words
const wordArray = text.trim().split(/\s+/);
return wordArray.length;
}
exports.getContentObjectTranscript = async function(req, res, dbo, id) {
const dbConnect = dbo.getDb();
try {
let chunks = [];
const chunkSize = parseInt(req.query.maxWords) || 10000;
let currentPage = parseInt(req.query.page) || 1;
let currentChunk = 0;
// Fetch the content data from the database
const data = await buildContentData(dbConnect, id);
let articles = data.articles;
// Create text chunks
chunks[0] = "Module title: " + data.displayTitle.trim() + "\n\n";
const module = {};
module.title = data.displayTitle;
try { module.aim = data._extensions._skillsFramework.aim; } catch (err) {}
try { module.learningOutcomes = data._extensions._skillsFramework.learningOutcomes; } catch (err) {}
try { module.reflectiveQuestions = data._extensions._skillsFramework.reflectiveQuestions; } catch (err) {}
for (let i = 0; i < articles.length; i++) {
let blocks = articles[i].blocks;
for (let b = 0; b < blocks.length; b++) {
let block = blocks[b];
let components = block.components;
let question = isQuestion(components);
let blockText = getElementAsText(block, question);
for (let c = 0; c < components.length; c++) {
let component = components[c];
blockText += getElementAsText(component, question);
}
if (countWords(chunks[currentChunk] + blockText) <= chunkSize) {
chunks[currentChunk] = chunks[currentChunk] + blockText;
} else {
currentChunk += 1;
chunks[currentChunk] = "";
chunks[currentChunk] = chunks[currentChunk] + blockText;
}
}
}
const updatedAt = new Date(data.updatedAt);
const lastModified = updatedAt.toUTCString();
// Handle the response based on the Accept header
const acceptHeader = req.headers.accept || 'text/plain';
if (acceptHeader.includes('application/json')) {
// Build JSON response containing only the elements included in the text response
const jsonResponse = [];
let currentChunkIndex = currentPage - 1;
for (let i = 0; i < articles.length; i++) {
let article = articles[i];
let articleBlocks = [];
for (let b = 0; b < article.blocks.length; b++) {
let block = article.blocks[b];
let components = block.components;
let blockJson = getElementAsJson(block, isQuestion(components));
let blockContent = {
block: blockJson,
components: components.map(component => getElementAsJson(component, isQuestion([component])))
};
articleBlocks.push(blockContent);
// Add block to the JSON response if it's part of the current chunk
if (chunks[currentChunkIndex].includes(getElementAsText(block, isQuestion(components)))) {
jsonResponse.push({
module: module,
content: articleBlocks
});
}
}
}
if (chunks.length > 1) {
const baseUrl = req.protocol + '://' + req.get('host') + req.baseUrl;
let nextChunkUrl = `${baseUrl}${req.path}?maxWords=${chunkSize}&page=${currentPage + 1}`;
res.set('Link', `<${nextChunkUrl}>; rel="next"`);
}
res.set('Last-Modified', lastModified);
res.set('Content-Type', 'application/json');
res.json(jsonResponse);
} else {
// Default to text/plain response
if (chunks.length > 1) {
const baseUrl = req.protocol + '://' + req.get('host') + req.baseUrl;
let nextChunkUrl = `${baseUrl}${req.path}?maxWords=${chunkSize}&page=${currentPage + 1}`;
res.set('Link', `<${nextChunkUrl}>; rel="next"`);
}
res.set('Last-Modified', lastModified);
res.set('Content-Type', 'text/plain');
res.send(chunks[currentPage - 1]);
}
} catch (err) {
console.error("Error:", err);
if (err.message === "Content object not found") {
res.status(404).json({ error: "Content object not found" });
} else {
res.status(500).json({ error: "An error occurred" });
}
}
}
exports.getContentObjectOutcomesMetadata = async function(req,res,dbo,id) {
const dbConnect = dbo.getDb();
const context = req.query.programme || null;
try {
let chunks = [];
const chunkSize = parseInt(req.query.maxWords) || 10000;
let currentPage = parseInt(req.query.page) || 1;
let currentChunk = 0;
//HERE to get the last updated date (this is all from create 2 so it live to changes! Ideally needs to be from)
const data = await buildContentData(dbConnect, id);
const courseData = await getObjectById(dbConnect, "course", data._courseId);
chunks[0] = "Module title: " + data.displayTitle.trim() + "\n\n";
const updatedAt = new Date(data.updatedAt);
const lastModified = updatedAt.toUTCString();
let aim = "Aim: " + stripHtmlTags(data._extensions._skillsFramework.aim).trim() + "\n\n";
chunks[0] += aim;
let learningOutcomesText = "Learning outcomes:\n";
const learningOutcomes = data._extensions._skillsFramework.learningOutcomes;
for (var i=0;i<learningOutcomes.length;i++) {
learningOutcomesText += " - " + learningOutcomes[i].outcome + "\n";
}
chunks[0] += learningOutcomesText + "\n";
let reflectiveQuestionsText = "Reflective questions/exercises:\n";
const reflectiveQuestions = data._extensions._skillsFramework.reflectiveQuestions;
for (var i=0;i<reflectiveQuestions.length;i++) {
reflectiveQuestionsText += " - " + reflectiveQuestions[i].question + "\n";
}
chunks[0] += reflectiveQuestionsText;
const programmes = courseData._extensions._skillsFramework._items;
for (var i=0;i<programmes.length;i++) {
let programmesText = "\n\nPart of programme: " + programmes[i].title + "\n\n";
programmesText += "Programme aim: " + stripHtmlTags(programmes[i].aim).trim() + "\n\n";
programmesText += "Position of module in programme: " + stripHtmlTags(programmes[i].positionDescription).trim() + "\n\n";
programmesText += "Related programme learning outcomes: \n";
const programmeLOs = programmes[i].learningOutcomes;
for (var j=0;j<programmeLOs.length;j++) {
programmesText += " - " + programmeLOs[j].outcome + "\n";
}
programmesText += "\n";
programmesText += "Programme specific reflective questions for module: \n";
const programmeReflectiveQuestions = programmes[i].reflectiveQuestions;
for (var j=0;j<programmeReflectiveQuestions.length;j++) {
programmesText += " - " + programmeReflectiveQuestions[j].question + "\n";
}
if (context) {
if (programmes[i].uri === context) {
chunks[0] += programmesText;
}
} else {
chunks[0] += programmesText;
}
}
if (chunks.length > 1) {
const baseUrl = req.protocol + '://' + req.get('host') + req.baseUrl;
nextChunkUrl = baseUrl + req.path + "?maxWords=" + chunkSize + "&page=" + (currentPage + 1);
res.set('Link', `<${nextChunkUrl}>; rel="next"`);
}
res.set('Last-Modified', lastModified);
res.set('Content-Type', 'text/plain');
res.send(chunks[currentPage-1])
} catch (err) {
console.error("Error:", err);
if (err.message === "Content object not found") {
res.status(404).json({ error: "Content object not found" });
} else {
res.status(500).json({ error: "An error occurred" });
}
}
}
exports.getContentObjectHead = async function(req, res, dbo, id) {
const dbConnect = dbo.getDb();
try {
// Fetch the data from the database
const data = await buildContentData(dbConnect, id);
// Get the last modified date and format it
const updatedAt = new Date(data.updatedAt);
const lastModified = updatedAt.toUTCString();
// Determine the desired content type from the Accept header
const acceptHeader = req.headers.accept || 'application/json';
if (acceptHeader.includes('application/json')) {
// Set content-type to application/json (if needed for other purposes)
res.setHeader('Content-Type', 'application/json');
} else {
// Set content-type to text/plain (if needed for other purposes)
res.setHeader('Content-Type', 'text/plain');
}
// Set the Last-Modified header
res.setHeader('Last-Modified', lastModified);
// Send an empty response body with a 200 status
return res.status(200).send();
} catch (err) {
console.error("Error:", err);
if (err.message === "Content object not found") {
return res.status(404).json({ error: "Content object not found" });
} else {
return res.status(500).json({ error: "An error occurred" });
}
}
}
exports.getContentObject = async function(req, res, dbo, id) {
const dbConnect = dbo.getDb();
try {
const contentData = await buildContentData(dbConnect, id);
const updatedAt = new Date(contentData.updatedAt);
const lastModified = updatedAt.toUTCString();
res.set('Last-Modified', lastModified);
res.json(contentData);
} catch (err) {
console.error("Error:", err);
if (err.message === "Content object not found") {
res.status(404).json({ error: "Content object not found" });
} else {
res.status(500).json({ error: "An error occurred" });
}
}
}
exports.getCourseConfig = function(req, res, dbo, id) {
var collection = "configs";
var dbConnect = dbo.getDb();
var query = {"_courseId": new ObjectId(id)};
dbConnect
.collection(collection)
.findOne(query, function(err, data) {
if (err) {
console.error("Error while retrieving object:", err);
res.status(500).json({ error: "An error occurred while retrieving content object" });
return;
}
if (!data) {
console.log("Object not found");
res.status(404).json({ error: "Object not found" });
return;
}
res.json(data);
});
}