-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathjspsych-uil-utils.js
431 lines (370 loc) · 13.3 KB
/
jspsych-uil-utils.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
/*
* one line to give the program's name and an idea of what it does.
* Copyright (C) 2020 Maarten Duijndam
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
import * as error from "./jspsych-uil-error.js"
import * as browser from "./jspsych-uil-browser.js"
import * as randomization from "./jspsych-uil-randomization.js"
import * as session from "./jspsych-uil-session.js"
import * as focus from "./jspsych-uil-focus.js"
import {isOnline, getWindow} from './libs/env.js';
export {
error,
browser,
randomization,
session,
focus,
}
export {
isOnline,
setAccessKey,
useAcceptationServer,
stopIfExperimentClosed,
saveData,
saveJson,
resolveServer
}
/* ********* constants *********** */
const DATA_STORE_PRODUCTION_SERVER =
'https://experiment-datastore.lab.hum.uu.nl/api/';
const DATA_STORE_ACCEPTATION_SERVER =
'https://experiment-datastore.acc.lab.hum.uu.nl/api/';
const CLOSED_EXPERIMENT_PAGE_LOCATION =
'https://web-experiments.lab.hum.uu.nl/index_files/closed/';
const CRITICAL_ERROR_PAGE_LOCATION =
'https://web-experiments.lab.hum.uu.nl/index_files/error/';
const DATA_UPLOAD_ENDPOINT = '/upload/';
const DATA_METADATA_ENDPOINT = '/metadata/';
const POST = 'POST';
const GET = 'GET';
const CONTENT_TYPE = 'Content-Type';
const CONTENT_TYPE_TEXT_PLAIN = 'text/plain';
const NIL_UUID = '00000000-0000-0000-0000-000000000000';
/* ************ private variables ************* */
let _access_key = undefined;
let _acc_server = false;
let _datastore_metadata = undefined;
/* ************ private functions ************* */
/**
* saves the data obtained from jsPsych on the webserver.
*
* @private
* @param {string} access_key The key obtain while registering the dataserver
* @param {string} server the server to which the data should be posted.
* @param {string} data the research data to send to the datastorage server.
*/
function saveOnDataServer(access_key, server, data) {
var xhr = new XMLHttpRequest();
xhr.open(POST, server + access_key + DATA_UPLOAD_ENDPOINT);
// Don't change, server only accepts plain text
xhr.setRequestHeader(CONTENT_TYPE, CONTENT_TYPE_TEXT_PLAIN);
xhr.onload = function() {
if(xhr.status === 200){
console.log("Upload status = 200 " + xhr.response);
}
else {
console.error("Error while uploading status = " + xhr.status);
console.error("Response = " + xhr.response);
}
};
xhr.send(data);
}
/**
* Loads experiment metadata from the Datastore status API
*
* @private
* @param {string} access_key The key obtain while registering the dataserver
* @param {string} server the server to which the data should be posted.
* @return {Promise}
*/
function getDatastoreMetadata(access_key, server) {
if (typeof(_datastore_metadata) !== "undefined")
// If we already have the data, return a auto-fulfilling promise
return new Promise((resolve, _) => {resolve(_datastore_metadata);});
let xhr = new XMLHttpRequest();
// As this is an async call, we return a promise. That way we can
// actually easily do stuff with the result.
return new Promise((resolve, reject) => {
let url = server + access_key + DATA_METADATA_ENDPOINT;
xhr.open(GET, url);
xhr.responseType = "json";
xhr.onload = function() {
if(xhr.status === 200){
_datastore_metadata = xhr.response;
resolve(xhr.response);
}
else {
console.error("Error while uploading status = " + xhr.status);
console.error("Response = " + xhr.response);
reject(new Error(String(xhr.status) + ": " + String(xhr.response)));
}
};
function onerror() {
reject(new Error("UiL-OTS datastore server is unavailable"));
}
xhr.onerror = onerror;
xhr.send();
})
}
/**
* Simple check of whether the uuid seems valid.
*
* This test just checks whether the form of the uuid is correct, it
* doesn't differntiate between version 1,2,3,4 or 5, nor does it
* check the variant.
*
* @param {string} id The id that should match a uuid
*
* @returns {boolean} True if the string is formatted as a UUID, false
* otherwise.
*/
function isUUIDFormat(id) {
return id.match(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/)
}
function validateAccessKey(access_key) {
if (typeof(access_key) === "undefined") {
// Check if we have a pre-saved access key
if (typeof(_access_key) === "undefined") {
// If not, error and return
console.error("Function argument access_key is undefined.");
return;
}
// If we do, use that key
access_key = _access_key;
}
let is_online = isOnline();
if (!isUUIDFormat(access_key)) {
let message =
`The access_key ${access_key} is not in a valid format. Please `+
"make sure you have copied it correctly in your experiment. " +
"It should be 5 groups of characters (0-9 or a-f) with " +
"8, 4, 4, 4 and 12 characters per group respectively.";
if (is_online) {
error.scriptError(
message
);
}
else {
console.log(message);
}
}
if (access_key === NIL_UUID) {
let message =
`The access_key is "${NIL_UUID}", you should update it.` +
"You can find the access_key in globals.js";
if (is_online) { // Treat as error when online
error.scriptError(message);
throw new TypeError("Bad access_key");
}
else { // and issue a warning when testing locally
console.log(message);
}
}
return access_key;
}
/* ************ public functions ************** */
/**
* Saves an access key to be used with all API related functions as an default.
*
* Saves an access key to be used with all API related functions as an default.
* If a default has been saved, one does not need to supply the access key anymore
* to any function with it as a parameter.
* This acces key will be used for all subsequent communications with the
* dataserver. If you would like to change it, you would have to call this function
* again, otherwise the cached variable is used instead of the ones passed to the
* server.
*
* @param {string} access_key, the key obtain from the datastore server.
*/
function setAccessKey (access_key) {
if (typeof(access_key) === "undefined") {
console.error("Function argument access_key is undefined.");
return;
}
_access_key = validateAccessKey(access_key.trim());
return _access_key;
}
/**
* Instructs all API methods to use the acceptation datastore server.
*
* Instructs all API methods to use the acceptation datastore server. This can
* be overriden on a per-call method using the ``acc_server`` parameter;
*/
function useAcceptationServer () {
_acc_server = true;
}
/**
* This function will redirect the user away if the experiment is closed.
*
* This function will redirect the user to a 'experiment closed' page
* if the experiment is closed according to the datastore.
*
* @param {string} access_key, the key obtain from the datastore server.
* Optional if key is set using setAccessKey
* @param {bool} acc_server, true if the data should be stored at the
* "acceptation server" for testing purposes. This parameter
* is only usefull when running the experiment online
* @param {string} A page to land when the experiment is closed
* @param {string} A page to land when the communication with the datastore
* fails.
* @memberof uil
*/
function stopIfExperimentClosed (
access_key = undefined,
acc_server = undefined,
stop_page = CLOSED_EXPERIMENT_PAGE_LOCATION,
error_page = CRITICAL_ERROR_PAGE_LOCATION
)
{
if (_access_key) {
access_key = _access_key;
}
else {
access_key = setAccessKey(access_key);
}
if (typeof(acc_server) === "undefined") {
acc_server = _acc_server;
}
let is_online = isOnline();
let key = access_key;
if (is_online) {
let server = "";
if (!acc_server)
server = DATA_STORE_PRODUCTION_SERVER;
else
server = DATA_STORE_ACCEPTATION_SERVER;
let getDatastoreMetadataResolve = function(data) {
let state = data['state'];
if (state !== "Open" && state !== "Piloting") {
getWindow().location = stop_page;
}
}
let getDatastoreMetadataReject = function (error) {
getWindow().location = error_page;
}
getDatastoreMetadata(key, server).then(
getDatastoreMetadataResolve,
getDatastoreMetadataReject
);
}
}
/**
* Saves data to the uilots data server or displays the data.
*
* Saves data to the uilots data server or displays the data
* in the browser window. When the experiment is hosted via an http(s)://
* server the data will be send to the data server, otherwise this function
* assumes that you are testing your experiment on your own pc via
* the file protocol.
*
* @param {string} access_key, the key obtain from the datastore server.
* Optional if key is set using setAccessKey
* @param {bool} acc_server, true if the data should be stored at the
* "acceptation server" for testing purposes. This parameter
* is only usefull when running the experiment online
* @memberof uil
* @deprecated use saveJson() instead.
*/
function saveData (access_key, acc_server = undefined) {
if (_access_key) {
access_key = _access_key;
}
else {
access_key = setAccessKey(access_key);
}
if (typeof(access_key) === "undefined") {
console.error("Unable to save without a valid access_key");
return;
}
let data = jsPsych.data.get().json();
let key = access_key;
let is_online = isOnline();
let server = resolveServer(acc_server);
if (is_online) {
if (session.isActive()) {
session.upload(key, data);
}
else {
saveOnDataServer(key, server, data);
}
}
else {
jsPsych.data.displayData();
}
}
/**
* Saves a json formatted string the uilots data server or displays the data.
*
* Saves data to the uilots data server or displays the data
* in the browser window. When the experiment is hosted via an http(s)://
* server the data will be send to the data server, otherwise this function
* assumes that you are testing your experiment on your own pc via
* the file protocol and will just display the json.
*
* @param {string} json a json formatted string.
* @param {string} access_key, the key obtain from the datastore server.
* Optional if key is set using setAccessKey
* @param {bool} acc_server, true if the data should be stored at the
* "acceptation server" for testing purposes. This parameter
* is only usefull when running the experiment online
* @memberof uil
*/
function saveJson (json, access_key, acc_server = undefined) {
if (_access_key) {
access_key = _access_key;
}
else {
access_key = setAccessKey(access_key);
}
if (typeof(access_key) === "undefined") {
console.error("Unable to save without a valid access_key");
return;
}
let key = access_key;
let is_online = isOnline();
let server = resolveServer(acc_server);
if (is_online) {
if (session.isActive()) {
session.upload(key, json);
}
else {
saveOnDataServer(key, server, json);
}
}
else {
// show the data in prettyfied format
json = JSON.stringify(JSON.parse(json), null, 4);
// Add preformatted json content.
let pre_element = document.createElement("pre");
pre_element.innerText = json;
let content = `<!doctype html><html><body><h1>Experiment Data (debug version)</h1>${pre_element.outerHTML}</body></html>`;
let url = URL.createObjectURL(new Blob([content], {type: 'text/html;charset=utf-8'}));
window.open(url);
}
}
/**
* Figures out which server we should be talking to
*/
function resolveServer (acc_server = undefined) {
if (typeof(acc_server) === "undefined") {
acc_server = _acc_server;
}
if (!acc_server)
return DATA_STORE_PRODUCTION_SERVER;
else
return DATA_STORE_ACCEPTATION_SERVER;
}