-
Notifications
You must be signed in to change notification settings - Fork 28
/
XAPI.js
1504 lines (1252 loc) · 44.9 KB
/
XAPI.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
1000
import Adapt from 'core/js/adapt';
import data from 'core/js/data';
import COMPLETION_STATE from 'core/js/enums/completionStateEnum';
import logging from 'core/js/logging';
import notify from 'core/js/notify';
import offlineStorage from 'core/js/offlineStorage';
import wait from 'core/js/wait';
import XAPIWrapper from 'libraries/xapiwrapper.min';
class XAPI extends Backbone.Model {
preinitialize() {
// Declare defaults and model properties
this.defaults = {
lang: 'en-US',
displayLang: 'en-US',
generateIds: false,
activityId: null,
actor: null,
shouldTrackState: true,
shouldUseRegistration: false,
componentBlacklist: 'blank,graphic',
isInitialised: false,
state: {}
};
this.xapiWrapper = XAPIWrapper;
this.startAttemptDuration = 0;
this.startTimeStamp = null;
this.courseName = '';
this.courseDescription = '';
this.defaultLang = 'en-US';
this.isComplete = false;
// Default events to send statements for.
this.coreEvents = {
Adapt: {
'router:page': false,
'router:menu': false,
'assessments:complete': true,
'questionView:recordInteraction': true
},
contentObjects: {
'change:_isComplete': false
},
articles: {
'change:_isComplete': false
},
blocks: {
'change:_isComplete': false
},
components: {
'change:_isComplete': true
}
};
// An object describing the core Adapt framework collections.
this.coreObjects = {
course: 'course',
contentObjects: ['menu', 'page'],
articles: 'article',
blocks: 'block',
components: 'component',
offlineStorage: 'offlineStorage'
};
}
/** Implementation starts here */
async initialize() {
if (!this.getConfig('_isEnabled')) return this;
wait.begin();
// Initialize the xAPIWrapper.
try {
await this.initializeWrapper();
} catch (error) {
this.onInitialised(error);
return this;
}
this.set({
activityId: (this.getLRSAttribute('activity_id') || this.getConfig('_activityID') || this.getBaseUrl()),
displayLang: Adapt.config.get('_defaultLanguage'),
lang: this.getConfig('_lang'),
generateIds: this.getConfig('_generateIds'),
shouldTrackState: this.getConfig('_shouldTrackState'),
shouldUseRegistration: this.getConfig('_shouldUseRegistration') || false,
componentBlacklist: this.getConfig('_componentBlacklist') || []
});
let componentBlacklist = this.get('componentBlacklist');
if (!Array.isArray(componentBlacklist)) {
// Create the blacklist array and force the items to lowercase.
componentBlacklist = componentBlacklist.split(/,\s?/).map(component => {
return component.toLowerCase();
});
}
this.set('componentBlacklist', componentBlacklist);
if (!this.validateProps()) {
const error = new Error('Missing required properties');
logging.error('adapt-contrib-xapi: xAPI Wrapper initialisation failed', error);
this.onInitialised(error);
return this;
}
this.startTimeStamp = new Date();
this.courseName = Adapt.course.get('displayTitle') || Adapt.course.get('title');
this.courseDescription = Adapt.course.get('description') || '';
// Send the 'launched' and 'initialized' statements.
const statements = [
this.getCourseStatement(window.ADL.verbs.launched),
this.getCourseStatement(window.ADL.verbs.initialized)
];
try {
await this.sendStatements(statements);
} catch (error) {
this.onInitialised(error);
return this;
}
if (['ios', 'android'].indexOf(Adapt.device.OS) > -1) {
$(document).on('visibilitychange', this.onVisibilityChange.bind(this));
} else {
$(window).on('beforeunload unload', this.sendUnloadStatements.bind(this));
}
if (!this.get('shouldTrackState')) {
// xAPI is not managing the state.
this.onInitialised();
return this;
}
// Retrieve the course state.
try {
await this.getState();
} catch (error) {
this.onInitialised(error);
return this;
}
if (this.get('state').length === 0) {
// This is a new attempt, send 'attempted'.
await this.sendStatement(this.getCourseStatement(window.ADL.verbs.attempted));
} else {
// This is a continuation of an existing attempt, send 'resumed'.
await this.sendStatement(this.getCourseStatement(window.ADL.verbs.resumed));
}
this.restoreState();
this.onInitialised();
return this;
}
static getInstance() {
if (!this.instance) this.instance = new XAPI();
return this.instance;
}
/**
* Replace the hard-coded _learnerInfo data in _globals with the actual data from the LRS.
*/
getLearnerInfo() {
const globals = Adapt.course.get('_globals');
if (!globals._learnerInfo) {
globals._learnerInfo = {};
}
Object.assign(globals._learnerInfo, offlineStorage.get('learnerinfo'));
}
/**
* Intializes the ADL xapiWrapper code.
*/
async initializeWrapper() {
// If no endpoint has been configured, assume the ADL Launch method.
if (!this.getConfig('_endpoint')) {
// check to see if configuration has been passed in URL
this.xapiWrapper = window.xapiWrapper || window.ADL.XAPIWrapper;
if (this.checkWrapperConfig()) {
// URL had all necessary configuration so we continue using it.
// Set the LRS specific properties.
this.set({
registration: this.getLRSAttribute('registration'),
actor: this.getLRSAttribute('actor')
});
this.xapiWrapper.strictCallbacks = true;
return;
}
return new Promise((resolve, reject) => {
// If no endpoint is configured, assume this is using the ADL launch method.
window.ADL.launch((error, launchData, xapiWrapper) => {
if (error) {
return reject(error);
}
// Initialise the xAPI wrapper.
this.xapiWrapper = xapiWrapper;
this.set({
actor: launchData.actor,
registration: xapiWrapper.lrs.registration
});
this.xapiWrapper.strictCallbacks = true;
return resolve();
}, true, true);
});
}
// The endpoint has been defined in the config, so use the static values.
// Initialise the xAPI wrapper.
this.xapiWrapper = window.xapiWrapper || window.ADL.XAPIWrapper;
// Set any attributes on the xAPIWrapper.
this.setWrapperConfig();
// Set the LRS specific properties.
this.set({
registration: this.getLRSAttribute('registration'),
actor: this.getLRSAttribute('actor')
});
this.xapiWrapper.strictCallbacks = true;
}
/**
* Triggers 'plugin:endWait' event (if required).
*/
onInitialised(error) {
this.set({ isInitialised: !error });
wait.end();
_.defer(() => {
if (error) {
Adapt.trigger('xapi:lrs:initialize:error', error);
return;
}
Adapt.trigger('xapi:lrs:initialize:success');
});
}
async onLanguageChanged(newLanguage) {
// Update the language.
this.set({ displayLang: newLanguage });
// Since a language change counts as a new attempt, reset the state.
await this.deleteState();
// Send a statement to track the (new) course.
await this.sendStatement(this.getCourseStatement(window.ADL.verbs.launched));
}
/**
* Sends 'suspended' and 'terminated' statements to the LRS when the window
* is closed or the browser app is minimised on a device. Sends a 'resume'
* statement when switching back to a suspended session.
*/
async onVisibilityChange() {
if (document.visibilityState === 'visible') {
this.isTerminated = false;
return this.sendStatement(this.getCourseStatement(window.ADL.verbs.resumed));
}
await this.sendUnloadStatements();
}
// Sends (optional) 'suspended' and 'terminated' statements to the LRS.
async sendUnloadStatements() {
if (this.isTerminated) return;
const statements = [];
if (!this.isComplete) {
// If the course is still in progress, send the 'suspended' verb.
statements.push(this.getCourseStatement(window.ADL.verbs.suspended));
}
// Always send the 'terminated' verb.
statements.push(this.getCourseStatement(window.ADL.verbs.terminated));
// Note: it is not possible to intercept these synchronous statements.
await this.sendStatementsSync(statements);
this.isTerminated = true;
}
/**
* Check Wrapper to see if all parameters needed are set.
*/
checkWrapperConfig() {
const lrs = this.xapiWrapper.lrs;
if (lrs.endpoint && lrs.actor && lrs.auth && lrs.activity_id) return true;
return false;
}
/**
* Attempt to extract endpoint, user and password from the config.json.
*/
setWrapperConfig() {
const keys = ['endpoint', 'user', 'password'];
const newConfig = {};
keys.forEach(key => {
let val = this.getConfig('_' + key);
if (val) {
// Note: xAPI wrapper requires a trailing slash and protocol to be present
if (key === 'endpoint') {
val = val.replace(/\/?$/, '/');
if (!/^https?:\/\//i.test(val)) {
logging.warn('adapt-contrib-xapi: "_endpoint" value is missing protocol (defaulting to http://)');
val = 'http://' + val;
}
}
newConfig[key] = val;
}
});
if (Object.keys(newConfig).length > 0) {
this.xapiWrapper.changeConfig(newConfig);
if (!this.xapiWrapper.testConfig()) {
throw new Error('Incorrect xAPI configuration detected');
}
}
}
/**
* Gets the URL the course is currently running on.
* @return {string} The URL to the current course.
*/
getBaseUrl() {
const url = window.location.origin + window.location.pathname;
logging.info(`adapt-contrib-xapi: Using detected URL (${url}) as ActivityID`);
return url;
}
getAttemptDuration() {
return this.startAttemptDuration + this.getSessionDuration();
}
getSessionDuration() {
return Math.abs((new Date()) - this.startTimeStamp);
}
/**
* Converts milliseconds to an ISO8601 duration
* @param {int} inputMilliseconds - Duration in milliseconds
* @return {string} - Duration in ISO8601 format
*/
convertMillisecondsToISO8601Duration(inputMilliseconds) {
const iInputMilliseconds = parseInt(inputMilliseconds, 10);
let inputIsNegative = '';
let rtnStr = '';
// Round to nearest 0.01 seconds.
let iInputCentiseconds = Math.round(iInputMilliseconds / 10);
if (iInputCentiseconds < 0) {
inputIsNegative = '-';
iInputCentiseconds = iInputCentiseconds * -1;
}
const hours = parseInt(((iInputCentiseconds) / 360000), 10);
const minutes = parseInt((((iInputCentiseconds) % 360000) / 6000), 10);
const seconds = (((iInputCentiseconds) % 360000) % 6000) / 100;
rtnStr = inputIsNegative + 'PT';
if (hours > 0) {
rtnStr += hours + 'H';
}
if (minutes > 0) {
rtnStr += minutes + 'M';
}
rtnStr += seconds + 'S';
return rtnStr;
}
setupListeners() {
if (!this.get('isInitialised')) {
logging.warn('adapt-contrib-xapi: Unable to setup listeners for xAPI');
return;
}
// Allow surfacing the learner's info in _globals.
this.getLearnerInfo();
this.listenTo(Adapt, 'app:languageChanged', this.onLanguageChanged);
if (this.get('shouldTrackState')) {
this.listenTo(Adapt, 'state:change', this.sendState);
}
// Use the config to specify the core events.
this.coreEvents = Object.assign(this.coreEvents, this.getConfig('_coreEvents'));
// Always listen out for course completion.
this.listenTo(Adapt, 'tracking:complete', this.onTrackingComplete);
// Conditionally listen to the events.
// Visits to the menu.
if (this.coreEvents.Adapt['router:menu']) {
this.listenTo(Adapt, 'router:menu', this.onItemExperience);
}
// Visits to a page.
if (this.coreEvents.Adapt['router:page']) {
this.listenTo(Adapt, 'router:page', this.onItemExperience);
}
// When an interaction takes place on a question.
if (this.coreEvents.Adapt['questionView:recordInteraction']) {
this.listenTo(Adapt, 'questionView:recordInteraction', this.onQuestionInteraction);
}
// When an assessment is completed.
if (this.coreEvents.Adapt['assessments:complete']) {
this.listenTo(Adapt, 'assessments:complete', this.onAssessmentComplete);
}
// Standard completion events for the various collection types, i.e.
// course, contentobjects, articles, blocks and components.
Object.keys(this.coreEvents).forEach(key => {
if (key !== 'Adapt') {
const val = this.coreEvents[key];
if (typeof val === 'object' && val['change:_isComplete'] === true) {
this.listenTo(Adapt[key], 'change:_isComplete', this.onItemComplete);
}
}
});
}
/**
* Gets an xAPI Activity (with an 'id of the activityId) representing the course.
* @returns {window.ADL.XAPIStatement.Activity} Activity representing the course.
*/
getCourseActivity() {
const object = new window.ADL.XAPIStatement.Activity(this.get('activityId'));
const name = {};
const description = {};
name[this.get('displayLang')] = this.courseName;
description[this.get('displayLang')] = this.courseDescription;
object.definition = {
type: window.ADL.activityTypes.course,
name,
description
};
return object;
}
/**
* Creates an xAPI statement related to the Adapt.course object.
* @param {object | string} verb - A valid ADL.verbs object or key.
* @param {object} [result] - An optional result object.
* @return A valid ADL statement object.
*/
getCourseStatement(verb, result) {
if (typeof result === 'undefined') {
result = {};
}
const object = this.getCourseActivity();
// Append the duration.
switch (verb) {
case window.ADL.verbs.launched:
case window.ADL.verbs.initialized:
case window.ADL.verbs.attempted: {
result.duration = 'PT0S';
break;
}
case window.ADL.verbs.failed:
case window.ADL.verbs.passed:
case window.ADL.verbs.suspended: {
result.duration = this.convertMillisecondsToISO8601Duration(this.getAttemptDuration());
break;
}
case window.ADL.verbs.terminated: {
result.duration = this.convertMillisecondsToISO8601Duration(this.getSessionDuration());
break;
}
}
return this.getStatement(this.getVerb(verb), object, result);
}
/**
* Gets a name object from a given model.
* @param {Backbone.Model} model - An instance of Adapt.Model (or Backbone.Model).
* @return {object} An object containing a key-value pair with the language code and name.
*/
getNameObject(model) {
const name = {};
name[this.get('displayLang')] = model.get('displayTitle') || model.get('title');
return name;
}
/**
* Gets the activity type for a given model.
* @param {Backbone.Model} model - An instance of Adapt.Model (or Backbone.Model).
* @return {string} A URL to the current activity type.
*/
getActivityType(model) {
let type = '';
switch (model.get('_type')) {
case 'component': {
type = model.get('_isQuestionType') ? window.ADL.activityTypes.interaction : window.ADL.activityTypes.media;
break;
}
case 'block':
case 'article': {
type = window.ADL.activityTypes.interaction;
break;
}
case 'course': {
type = window.ADL.activityTypes.course;
break;
}
case 'menu': {
type = window.ADL.activityTypes.module;
break;
}
case 'page': {
type = window.ADL.activityTypes.lesson;
break;
}
}
return type;
}
/**
* Sends an 'answered' statement to the LRS.
* @param {ComponentView} view - An instance of Adapt.ComponentView.
*/
async onQuestionInteraction(view) {
if ((!view.model || view.model.get('_type') !== 'component') &&
!view.model.get('_isQuestionType')) return;
// This component is on the blacklist, so do not send a statement.
if (this.isComponentOnBlacklist(view.model.get('_component'))) return;
const object = new window.ADL.XAPIStatement.Activity(this.getUniqueIri(view.model));
const completion = view.model.get('_isComplete');
const lang = this.get('displayLang');
const description = {};
description[lang] = this.stripHtml(view.model.get('body'));
object.definition = {
name: this.getNameObject(view.model),
description,
type: window.ADL.activityTypes.question,
interactionType: view.getResponseType()
};
if (typeof view.getInteractionObject === 'function') {
// Get any extra interactions.
Object.assign(object.definition, view.getInteractionObject());
// Ensure any 'description' properties are objects with the language map.
Object.keys(object.definition).forEach(key => {
if (!object.definition[key]?.length) return;
for (let i = 0; i < object.definition[key].length; i++) {
if (!Object.prototype.hasOwnProperty.call(object.definition[key][i], 'description')) {
break;
}
if (typeof object.definition[key][i].description === 'string') {
const description = {};
description[lang] = object.definition[key][i].description;
object.definition[key][i].description = description;
}
}
});
}
const result = {
score: {
raw: view.model.get('_score') || 0
},
success: view.model.get('_isCorrect'),
completion,
response: this.processInteractionResponse(object.definition.interactionType, view.getResponse())
};
// Answered
const statement = this.getStatement(this.getVerb(window.ADL.verbs.answered), object, result);
this.addGroupingActivity(view.model, statement);
await this.sendStatement(statement);
}
/**
* Removes the HTML tags/attributes and returns a string.
* @param {string} html - A string containing HTML
* @returns {string} The same string minus HTML
*/
stripHtml(html) {
const tempDiv = document.createElement('div');
tempDiv.innerHTML = html;
return tempDiv.textContent || tempDiv.innerText || '';
}
/**
* In order to support SCORM 1.2 and SCORM 2004, some of the components return a non-standard
* response.
* @param {string} responseType - The type of the response.
* @param {string} response - The unprocessed response string.
* @returns {string} A response formatted for xAPI compatibility.
*/
processInteractionResponse(responseType, response) {
switch (responseType) {
case 'choice': {
response = response.replace(/,|#/g, '[,]');
break;
}
case 'matching': {
// Example: 1[.]1_1[,]2[.]2_5
response = response
.split('#')
.map((val, i) => {
return (i + 1) + '[.]' + val.replace('.', '_');
})
.join('[,]');
break;
}
}
return response;
}
/**
* Sends an xAPI statement when an item has been experienced.
* @param {AdaptModel} model - An instance of AdaptModel, i.e. ContentObjectModel, etc.
*/
async onItemExperience(model) {
if (model.get('_id') === 'course') {
// We don't really want to track actions on the home menu.
return;
}
const object = new window.ADL.XAPIStatement.Activity(this.getUniqueIri(model));
object.definition = {
name: this.getNameObject(model),
type: this.getActivityType(model)
};
// Experienced.
const statement = this.getStatement(this.getVerb(window.ADL.verbs.experienced), object);
this.addGroupingActivity(model, statement);
await this.sendStatement(statement);
}
/**
* Checks if a given component is blacklisted from sending statements.
* @param {string} component - The name of the component.
* @returns {boolean} true if the component exists on the blacklist.
*/
isComponentOnBlacklist(component) {
return this.get('componentBlacklist').indexOf(component) !== -1;
}
/**
* Sends an xAPI statement when an item has been completed.
* @param {AdaptModel} model - An instance of AdaptModel, i.e. ComponentModel, BlockModel, etc.
* @param {boolean} isComplete - Flag to indicate if the model has been completed
*/
async onItemComplete(model, isComplete) {
// The item is not actually completed, e.g. it may have been reset.
if (isComplete === false) return;
// If this is a question component (interaction), do not record multiple statements.
// Return because 'Answered' will already have been passed.
if (model.get('_type') === 'component' && model.get('_isQuestionType') === true &&
this.coreEvents.Adapt['questionView:recordInteraction'] === true &&
this.coreEvents.components['change:_isComplete'] === true) return;
// This component is on the blacklist, so do not send a statement.
if (model.get('_type') === 'component' && this.isComponentOnBlacklist(model.get('_component'))) return;
const result = { completion: true };
const object = new window.ADL.XAPIStatement.Activity(this.getUniqueIri(model));
object.definition = {
name: this.getNameObject(model),
type: this.getActivityType(model)
};
// Completed.
const statement = this.getStatement(this.getVerb(window.ADL.verbs.completed), object, result);
this.addGroupingActivity(model, statement);
await this.sendStatement(statement);
}
/**
* Gets a lesson activity for a given page.
* @param {string|Adapt.Model} page - Either an Adapt contentObject model of type 'page', or the _id of one.
* @returns {XAPIStatement.Activity} Activity corresponding to the lesson.
*/
getLessonActivity(page) {
const pageModel = (typeof page === 'string')
? data.findById(page)
: page;
const activity = new window.ADL.XAPIStatement.Activity(this.getUniqueIri(pageModel));
const name = this.getNameObject(pageModel);
activity.definition = {
name,
type: window.ADL.activityTypes.lesson
};
return activity;
}
/**
* Adds a 'grouping' and/or 'parent' value to a statement's contextActivities.
* Note: the 'parent' is only added in the case of a question component which is part of
* an assessment. All articles, blocks and components are grouped by page.
* @param {Adapt.Model} model - Any Adapt model.
* @param {ADL.XAPIStatement} statement - A valid xAPI statement object.
*/
addGroupingActivity(model, statement) {
const type = model.get('_type');
if (type !== 'course') {
// Add a grouping for the course.
statement.addGroupingActivity(this.getCourseActivity());
}
if (['article', 'block', 'component'].indexOf(type) !== -1) {
// Group these items by page/lesson.
const pageModel = model.findAncestor('pages');
statement.addGroupingActivity(this.getLessonActivity(pageModel));
}
if (type === 'component' && model.get('_isPartOfAssessment')) {
// Get the article containing this question component.
const articleModel = model.findAncestor('articles');
if (articleModel?.has('_assessment')?._isEnabled) {
// Set the assessment as the parent.
const assessment = {
id: articleModel.get('_assessment')._id,
articleId: articleModel.get('_id'),
type: 'article-assessment',
pageId: articleModel.get('_parentId')
};
statement.addParentActivity(this.getAssessmentObject(assessment));
}
}
}
/**
* Takes an assessment state and returns a results object based on it.
* @param {object} assessment - An instance of the assessment state.
* @return {object} - A result object containing score, success and completion properties.
*/
getAssessmentResultObject(assessment) {
return {
score: {
scaled: (assessment.scoreAsPercent / 100),
raw: assessment.score,
min: 0,
max: assessment.maxScore
},
success: assessment.isPass,
completion: assessment.isComplete
};
}
/**
* Gets an Activity for use in an xAPI statement.
* @param {object} assessment - Object representing the assessment.
* @returns {ADL.XAPIStatement.Activity} - Activity representing the assessment.
*/
getAssessmentObject(assessment) {
// Instantiate a Model so it can be used to obtain an IRI.
const fakeModel = new Backbone.Model({
_id: assessment.id || assessment.articleId,
_type: assessment.type,
pageId: assessment.pageId
});
const object = new window.ADL.XAPIStatement.Activity(this.getUniqueIri(fakeModel));
const name = {};
name[this.get('displayLang')] = assessment.id || 'Assessment';
object.definition = {
name: name,
type: window.ADL.activityTypes.assessment
};
return object;
}
/**
* Sends an xAPI statement when an assessment has been completed.
* @param {object} assessment - Object representing the state of the assessment.
*/
onAssessmentComplete(assessment) {
const object = this.getAssessmentObject(assessment);
const result = this.getAssessmentResultObject(assessment);
let statement;
if (assessment.isPass) {
// Passed.
statement = this.getStatement(this.getVerb(window.ADL.verbs.passed), object, result);
} else {
// Failed.
statement = this.getStatement(this.getVerb(window.ADL.verbs.failed), object, result);
}
statement.addGroupingActivity(this.getCourseActivity());
statement.addGroupingActivity(this.getLessonActivity(assessment.pageId));
// Delay so that component completion can be recorded before assessment completion.
_.delay(async () => {
await this.sendStatement(statement);
}, 500);
}
/**
* Gets a valid 'verb' object in the ADL.verbs and returns the correct language version.
* @param {object|stirng} verb - A valid ADL verb object or key, e.g. 'completed'.
* @return {object} An ADL verb object with 'id' and language specific 'display' properties.
*/
getVerb(verb) {
if (typeof verb === 'string') {
const key = verb.toLowerCase();
verb = window.ADL.verbs[key];
if (!verb) {
logging.error(`adapt-contrib-xapi: Verb " ${key} " does not exist in window.ADL.verbs object`);
}
}
if (typeof verb !== 'object') {
throw new Error('Unrecognised verb: ' + verb);
}
const lang = this.get('lang') || this.defaultLang;
const singleLanguageVerb = {
id: verb.id,
display: {}
};
const description = verb.display[lang];
if (description) {
singleLanguageVerb.display[lang] = description;
return singleLanguageVerb;
}
// Fallback in case the verb translation doesn't exist.
singleLanguageVerb.display[this.defaultLang] = verb.display[this.defaultLang];
return singleLanguageVerb;
}
/**
* Gets a unique IRI for a given model.
* @param {AdaptModel} model - An instance of an AdaptModel object.
* @return {string} An IRI formulated specific to the passed model.
*/
getUniqueIri(model) {
let iri = this.get('activityId');
const type = model.get('_type');
if (type !== 'course') {
if (type === 'article-assessment') {
iri = iri + ['#', 'assessment', model.get('_id')].join('/');
} else {
iri = iri + ['#/id', model.get('_id')].join('/');
}
}
return iri;
}
/**
* Handler for the Adapt Framework's 'tracking:complete' event.
* @param {object} completionData
*/
onTrackingComplete(completionData) {
let result = {};
let completionVerb;
// Check the completion status.
switch (completionData.status) {
case COMPLETION_STATE.PASSED: {
completionVerb = window.ADL.verbs.passed;
break;
}
case COMPLETION_STATE.FAILED: {
completionVerb = window.ADL.verbs.failed;
break;
}
default: {
completionVerb = window.ADL.verbs.completed;
}
}
if (completionVerb === window.ADL.verbs.completed) {
result = { completion: true };
} else {
// The assessment(s) play a part in completion, so use their result.
result = this.getAssessmentResultObject(completionData.assessment);
}
// Store a reference that the course has actually been completed.
this.isComplete = true;
_.defer(async () => {
// Send the completion status.
await this.sendStatement(this.getCourseStatement(completionVerb, result));
});
}
/**
* Refresh course progress from loaded state.
*/
restoreState() {
const state = this.get('state');
if (state && Object.keys(state).length === 0) return;
const Adapt = require('core/js/adapt');
if (state.components) {
state.components.forEach(stateObject => {
const restoreModel = Adapt.findById(stateObject._id);
if (restoreModel) {
restoreModel.setTrackableState(stateObject);
} else {
logging.warn('adapt-contrib-xapi: Unable to restore state for component: ' + stateObject._id);
}
});
}
if (state.blocks) {
state.blocks.forEach(stateObject => {
const restoreModel = Adapt.findById(stateObject._id);
if (restoreModel) {
restoreModel.setTrackableState(stateObject);
} else {
logging.warn('adapt-contrib-xapi: Unable to restore state for block: ' + stateObject._id);
}
});
}
}
/**
* Generate an XAPIstatement object for the xAPI wrapper sendStatement methods.
* @param {object} verb - A valid ADL.verbs object.
* @param {object} object -
* @param {object} [result] - optional
* @param {object} [context] - optional
* @return {ADL.XAPIStatement} A formatted xAPI statement object.