-
Notifications
You must be signed in to change notification settings - Fork 42
/
Copy pathadapt-stateful-session.js
274 lines (254 loc) · 11.1 KB
/
adapt-stateful-session.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
define([
'core/js/adapt',
'./scorm/wrapper',
'core/js/enums/completionStateEnum',
'./serializers/ComponentSerializer',
'./serializers/SCORMSuspendData'
], function(Adapt, ScormWrapper, COMPLETION_STATE, ComponentSerializer, SCORMSuspendData) {
class StatefulSession extends Backbone.Controller {
initialize() {
_.bindAll(this, 'beginSession', 'onVisibilityChange', 'endSession');
this.scorm = ScormWrapper.getInstance();
this._trackingIdType = 'block';
this._componentSerializer = null;
this._shouldStoreResponses = true;
this._shouldStoreAttempts = false;
this._shouldRecordInteractions = true;
this.beginSession();
}
beginSession() {
this.listenTo(Adapt, 'app:dataReady', this.restoreSession);
this._trackingIdType = Adapt.build.get('trackingIdType') || 'block';
this._componentSerializer = new ComponentSerializer(this._trackingIdType);
// suppress SCORM errors if 'nolmserrors' is found in the querystring
if (window.location.search.indexOf('nolmserrors') !== -1) {
this.scorm.suppressErrors = true;
}
const config = Adapt.spoor.config;
if (!config) return;
const tracking = config._tracking;
this._shouldStoreResponses = (tracking && tracking._shouldStoreResponses) || false;
this._shouldStoreAttempts = (tracking && tracking._shouldStoreAttempts) || false;
// Default should be to record interactions, so only avoid doing that if
// _shouldRecordInteractions is set to false
if (tracking && tracking._shouldRecordInteractions === false) {
this._shouldRecordInteractions = false;
}
const settings = config._advancedSettings;
if (!settings) {
// force use of SCORM 1.2 by default - some LMSes (SABA/Kallidus for instance)
// present both APIs to the SCO and, if given the choice, the pipwerks
// code will automatically select the SCORM 2004 API - which can lead to
// unexpected behaviour.
this.scorm.setVersion('1.2');
this.scorm.initialize();
return;
}
if (settings._showDebugWindow) {
this.scorm.showDebugWindow();
}
this.scorm.setVersion(settings._scormVersion || '1.2');
if (_.isBoolean(settings._suppressErrors)) {
this.scorm.suppressErrors = settings._suppressErrors;
}
if (_.isBoolean(settings._commitOnStatusChange)) {
this.scorm.commitOnStatusChange = settings._commitOnStatusChange;
}
if (_.isBoolean(settings._commitOnAnyChange)) {
this.scorm.commitOnAnyChange = settings._commitOnAnyChange;
}
if (_.isFinite(settings._timedCommitFrequency)) {
this.scorm.timedCommitFrequency = settings._timedCommitFrequency;
}
if (_.isFinite(settings._maxCommitRetries)) {
this.scorm.maxCommitRetries = settings._maxCommitRetries;
}
if (_.isFinite(settings._commitRetryDelay)) {
this.scorm.commitRetryDelay = settings._commitRetryDelay;
}
if ('_exitStateIfIncomplete' in settings) {
this.scorm.exitStateIfIncomplete = settings._exitStateIfIncomplete;
}
if ('_exitStateIfComplete' in settings) {
this.scorm.exitStateIfComplete = settings._exitStateIfComplete;
}
this.scorm.initialize();
}
restoreSession() {
this.setupLearnerInfo();
this.restoreSessionState();
// defer call because AdaptModel.check*Status functions are asynchronous
_.defer(this.setupEventListeners.bind(this));
}
setupLearnerInfo() {
// Replace the hard-coded _learnerInfo data in _globals with the actual data
// from the LMS
// If the course has been published from the AT, the _learnerInfo object
// won't exist so we'll need to create it
const globals = Adapt.course.get('_globals');
if (!globals._learnerInfo) {
globals._learnerInfo = {};
}
Object.assign(globals._learnerInfo, Adapt.offlineStorage.get('learnerinfo'));
}
restoreSessionState() {
const sessionPairs = Adapt.offlineStorage.get();
const hasNoPairs = !Object.keys(sessionPairs).length;
if (hasNoPairs) return;
if (sessionPairs.c) {
const [ _isComplete, _isAssessmentPassed ] = SCORMSuspendData.deserialize(sessionPairs.c);
Adapt.course.set({
_isComplete,
_isAssessmentPassed
});
}
if (sessionPairs.q) {
this._componentSerializer.deserialize(sessionPairs.q);
}
}
setupEventListeners() {
const debouncedSaveSession = _.debounce(this.saveSessionState.bind(this), 1);
this.listenTo(Adapt.data, 'change:_isComplete', debouncedSaveSession);
if (this._shouldStoreResponses) {
this.listenTo(Adapt.data, 'change:_isSubmitted change:_userAnswer', debouncedSaveSession);
}
this.listenTo(Adapt, {
'app:languageChanged': this.onLanguageChanged,
'questionView:recordInteraction': this.onQuestionRecordInteraction,
'assessment:complete': this.onAssessmentComplete,
'tracking:complete': this.onTrackingComplete
});
const config = Adapt.spoor.config;
const advancedSettings = config._advancedSettings;
const shouldCommitOnVisibilityChange = (!advancedSettings ||
advancedSettings._commitOnVisibilityChangeHidden !== false);
if (shouldCommitOnVisibilityChange) {
document.addEventListener('visibilitychange', this.onVisibilityChange);
}
$(window).on('beforeunload unload', this.endSession);
}
saveSessionState() {
const courseState = SCORMSuspendData.serialize([
Boolean(Adapt.course.get('_isComplete')),
Boolean(Adapt.course.get('_isAssessmentPassed'))
]);
const componentStates = this._componentSerializer.serialize(this._shouldStoreResponses, this._shouldStoreAttempts);
const sessionPairs = {
'c': courseState,
'q': componentStates
};
Adapt.offlineStorage.set(sessionPairs);
this.printCompletionInformation(sessionPairs);
}
printCompletionInformation(suspendData) {
if (typeof suspendData === 'string') {
// In-case LMS data is passed as a string
suspendData = JSON.parse(suspendData);
}
const courseState = SCORMSuspendData.deserialize(suspendData.c);
const courseComplete = courseState[0];
const assessmentPassed = courseState[1];
const trackingIdModels = Adapt.data.filter(model => model.get('_type') === this._trackingIdType && model.has('_trackingId'));
const trackingIds = trackingIdModels.map(model => model.get('_trackingId'));
if (!trackingIds.length) {
Adapt.log.info(`course._isComplete: ${courseComplete}, course._isAssessmentPassed: ${assessmentPassed}, ${this._trackingIdType} completion: no tracking ids found`);
return;
}
const data = SCORMSuspendData.deserialize(suspendData.q);
const max = Math.max(...data.map(item => item[0][0]));
const shouldStoreResponses = (data[0].length === 3);
const completionString = data.reduce((markers, item) => {
const trackingId = item[0][0];
const isComplete = shouldStoreResponses ?
item[2][1][0] :
item[1][0];
const mark = isComplete ? '1' : '0';
markers[trackingId] = (markers[trackingId] === '-' || markers[trackingId] === '1') ?
mark :
'0';
return markers;
}, (new Array(max + 1).join('-').split(''))).join('');
Adapt.log.info(`course._isComplete: ${courseComplete}, course._isAssessmentPassed: ${assessmentPassed}, ${this._trackingIdType} completion: ${completionString}`);
}
onLanguageChanged() {
// when the user switches language, we need to:
// - reattach the event listeners as the language change triggers a reload of
// the json, which will create brand new collections
// - get and save a fresh copy of the session state. as the json has been reloaded,
// the blocks completion data will be reset (the user is warned that this will
// happen by the language picker extension)
// - check to see if the config requires that the lesson_status be reset to
// 'incomplete'
const config = Adapt.spoor.config;
this.removeEventListeners();
this.setupEventListeners();
this.saveSessionState();
if (config && config._reporting && config._reporting._resetStatusOnLanguageChange === true) {
Adapt.offlineStorage.set('status', 'incomplete');
}
}
onVisibilityChange() {
if (document.visibilityState === 'hidden') this.scorm.commit();
}
onQuestionRecordInteraction(questionView) {
if (!this._shouldRecordInteractions) return;
const responseType = questionView.getResponseType();
// If responseType doesn't contain any data, assume that the question
// component hasn't been set up for cmi.interaction tracking
if (_.isEmpty(responseType)) return;
const id = questionView.model.get('_id');
const response = questionView.getResponse();
const result = questionView.isCorrect();
const latency = questionView.getLatency();
Adapt.offlineStorage.set('interaction', id, response, result, latency, responseType);
}
onAssessmentComplete(stateModel) {
const config = Adapt.spoor.config;
Adapt.course.set('_isAssessmentPassed', stateModel.isPass);
this.saveSessionState();
const shouldSubmitScore = (config && config._tracking && config._tracking._shouldSubmitScore);
if (!shouldSubmitScore) return;
const scoreArgs = stateModel.isPercentageBased ?
[ stateModel.scoreAsPercent, 0, 100 ] :
[ stateModel.score, 0, stateModel.maxScore ];
Adapt.offlineStorage.set('score', ...scoreArgs);
}
onTrackingComplete(completionData) {
const config = Adapt.spoor.config;
this.saveSessionState();
let completionStatus = completionData.status.asLowerCase;
// The config allows the user to override the completion state.
switch (completionData.status) {
case COMPLETION_STATE.COMPLETED:
case COMPLETION_STATE.PASSED: {
if (!config || !config._reporting || !config._reporting._onTrackingCriteriaMet) {
Adapt.log.warn(`No value defined for '_onTrackingCriteriaMet', so defaulting to '${completionStatus}'`);
} else {
completionStatus = config._reporting._onTrackingCriteriaMet;
}
break;
}
case COMPLETION_STATE.FAILED: {
if (!config || !config._reporting || !config._reporting._onAssessmentFailure) {
Adapt.log.warn(`No value defined for '_onAssessmentFailure', so defaulting to '${completionStatus}'`);
} else {
completionStatus = config._reporting._onAssessmentFailure;
}
}
}
Adapt.offlineStorage.set('status', completionStatus);
}
endSession() {
if (!this.scorm.finishCalled) {
this.scorm.finish();
}
this.removeEventListeners();
}
removeEventListeners() {
$(window).off('beforeunload unload', this.endSession);
document.removeEventListener('visibilitychange', this.onVisibilityChange);
this.stopListening();
}
}
return StatefulSession;
});