forked from arenaxr/arena-web-core
-
Notifications
You must be signed in to change notification settings - Fork 4
/
persist-objects.js
executable file
·739 lines (658 loc) · 23 KB
/
persist-objects.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
/**
* @fileoverview Manage objects on persistence server
*
* Open source software under the terms in /LICENSE
* Copyright (c) 2020, The CONIX Research Center. All rights reserved.
* @date 2020
*/
/* global Alert, ARENAAUTH, ARENADefaults, Swal, THREE */
/* eslint-disable import/extensions */
import MqttClient from './mqtt-client.js';
import ARENAUserAccount from './arena-account.js';
let persist;
function type_order(type) {
switch (type) {
case 'scene-options':
return 0;
case 'landmarks':
return 1;
case 'program':
return 2;
case 'object':
return 3;
default:
return 4;
}
}
/**
*
*/
export async function init(settings) {
if (settings.objList === undefined) throw 'Must provide a list element';
// handle default settings
settings = settings || {};
persist = {
mqttUri: settings.mqttUri !== undefined ? settings.mqttUri : 'wss://arena.andrew.cmu.edu/mqtt/',
persistUri:
settings.persistUri !== undefined
? settings.persistUri
: `${window.location.hostname + (window.location.port ? `:${window.location.port}` : '')}/persist/`,
objList: settings.objList,
addEditSection: settings.addEditSection,
editObjHandler: settings.editObjHandler,
visObjHandler: settings.visObjHandler,
authState: settings.authState,
mqttUsername: settings.mqttUsername,
mqttToken: settings.mqttToken,
exportSceneButton: settings.exportSceneButton,
};
persist.currentSceneObjs = [];
// set select when clicking on a list item
persist.objList.addEventListener(
'click',
(ev) => {
if (ev.target.tagName === 'LI') {
ev.target.classList.toggle('checked');
}
},
false
);
// start mqtt client
persist.mc = new MqttClient({
uri: persist.mqttUri,
onMessageCallback: onMqttMessage,
mqtt_username: persist.mqttUsername,
mqtt_token: persist.mqttToken,
dbg: true,
});
console.info(`Starting connection to ${persist.mqttUri}...`);
// connect
try {
persist.mc.connect();
} catch (error) {
console.error(error); // Failure!
Alert.fire({
icon: 'error',
title: `Error connecting to MQTT: ${JSON.stringify(error)}`,
timer: 5000,
});
return;
}
persist.mqttConnected = true;
console.info('Connected.');
}
export async function populateSceneAndNsLists(nsInput, nsList, sceneInput, sceneList) {
try {
persist.authState = await ARENAUserAccount.userAuthState();
} catch (err) {
Swal.fire({
icon: 'Error',
title: `Error querying user authentication status: ${err.statusText}`,
allowEscapeKey: false,
allowOutsideClick: false,
showConfirmButton: false,
});
console.error(err);
return undefined;
}
if (!persist.authState.authenticated) {
Swal.fire({
icon: 'error',
title: 'Please do a non-anonymous login.',
allowEscapeKey: false,
allowOutsideClick: false,
}).then((result) => {
ARENAAUTH.signOut();
});
const option = document.createElement('option');
option.text = '';
nsList.add(option);
nsInput.disabled = true;
emptySceneInput(sceneInput);
return undefined;
}
const ns = await populateNamespaceList(nsInput, nsList);
if (ns) {
populateSceneList(ns, sceneInput, sceneList);
} else {
emptySceneInput(sceneInput);
}
return ns;
}
export function clearObjectList(noObjNotification = undefined) {
persist.currentSceneObjs = [];
while (persist.objList.firstChild) {
persist.objList.removeChild(persist.objList.firstChild);
}
if (noObjNotification === undefined) return;
const li = document.createElement('li');
const t = document.createTextNode(noObjNotification);
li.appendChild(t);
persist.objList.appendChild(li);
}
export async function fetchSceneObjects(scene) {
if (persist.persistUri === undefined) {
throw 'Persist DB URL not defined.'; // should be called after persist_url is set
}
let sceneObjs;
try {
const persistOpt = ARENADefaults.disallowJWT ? {} : { credentials: 'include' };
const data = await fetch(persist.persistUri + scene, persistOpt);
if (!data) {
throw 'Could not fetch data';
}
if (!data.ok) {
throw 'Fetch request result not ok';
}
sceneObjs = await data.json();
} catch (err) {
throw `${err}`;
}
return sceneObjs;
}
export function updateListItemVisibility(visible, li, iconVis) {
iconVis.className = visible ? 'icon-eye-open' : 'icon-eye-close';
li.style.color = visible ? 'black' : 'gray';
}
export async function populateObjectList(scene, filter, objTypeFilter, focusObjectId = undefined) {
clearObjectList();
let sceneObjs;
try {
sceneObjs = await fetchSceneObjects(scene);
} catch (err) {
Alert.fire({
icon: 'error',
title: `Error fetching scene from database. ${err}`,
timer: 5000,
});
return;
}
persist.currentSceneObjs = sceneObjs;
// sort object list by type, then object_id
sceneObjs.sort((a, b) => {
// order by type
if (type_order(a.type) < type_order(b.type)) {
return -1;
}
if (type_order(a.type) > type_order(b.type)) {
return 1;
}
// then by object_id
if (a.object_id < b.object_id) {
return -1;
}
if (a.object_id > b.object_id) {
return 1;
}
return 0;
});
// console.log(sceneobjs);
if (sceneObjs.length === 0) {
const li = document.createElement('li');
const t = document.createTextNode('No objects in the scene');
li.appendChild(t);
persist.objList.appendChild(li);
persist.addEditSection.style = 'display:block';
persist.exportSceneButton.setAttribute('href', '#'); // No download
persist.exportSceneButton.removeAttribute('download'); // No download
return;
}
// Update scene obj list to download as json
const exportJSON = sceneObjs.map((obj) => {
const filteredObj = { ...obj };
filteredObj.data = filteredObj.attributes;
delete filteredObj.createdAt;
delete filteredObj.updatedAt;
delete filteredObj.attributes;
return filteredObj;
});
persist.exportSceneButton.setAttribute(
'href',
`data:text/json;charset=utf-8,${encodeURIComponent(JSON.stringify(exportJSON, null, 2))}`
);
persist.exportSceneButton.setAttribute('download', `${scene.replace('/', '__')}.json`);
// create regex
let re;
try {
re = new RegExp(filter);
} catch (err) {
Alert.fire({
icon: 'error',
title: `Invalid filter ${JSON.stringify(err)} (NOTE: '.*' matches all object ids)`,
timer: 5000,
});
return;
}
for (let i = 0; i < sceneObjs.length; i++) {
const li = document.createElement('li');
const span = document.createElement('span');
const img = document.createElement('img');
// save obj json so we can use later in selected object actions (delete/copy)
li.setAttribute('data-obj', JSON.stringify(sceneObjs[i]));
let inputValue = '';
if (sceneObjs[i].attributes === undefined) continue;
if (objTypeFilter[sceneObjs[i].type] === false) continue;
if (re.test(sceneObjs[i].object_id) === false) continue;
if (sceneObjs[i].type === 'object') {
inputValue = `${sceneObjs[i].object_id} ( ${sceneObjs[i].attributes.object_type} )`;
img.src = 'assets/3dobj-icon.png';
if (objTypeFilter[sceneObjs[i].attributes.object_type] === false) continue;
} else if (sceneObjs[i].type === 'program') {
const ptype = sceneObjs[i].attributes.filetype === 'WA' ? 'WASM program' : 'python program';
inputValue = `${sceneObjs[i].object_id} ( ${ptype}: ${sceneObjs[i].attributes.filename} )`;
img.src = 'assets/program-icon.png';
} else if (sceneObjs[i].type === 'scene-options') {
inputValue = `${sceneObjs[i].object_id} ( scene options )`;
img.src = 'assets/options-icon.png';
} else if (sceneObjs[i].type === 'landmarks') {
inputValue = `${sceneObjs[i].object_id} ( landmarks )`;
img.src = 'assets/map-icon.png';
}
const r = sceneObjs[i].attributes.rotation;
if (r) {
// convert deprecated euler-style rotation to quaternions if needed
if (!r.hasOwnProperty('w')) {
const q = new THREE.Quaternion().setFromEuler(
new THREE.Euler(
THREE.MathUtils.degToRad(r.x),
THREE.MathUtils.degToRad(r.y),
THREE.MathUtils.degToRad(r.z)
)
);
sceneObjs[i].attributes.rotation = {
x: parseFloat(q.x.toFixed(5)),
y: parseFloat(q.y.toFixed(5)),
z: parseFloat(q.z.toFixed(5)),
w: parseFloat(q.w.toFixed(5)),
};
}
}
const t = document.createTextNode(inputValue);
li.appendChild(t);
// add image
img.width = 16;
span.className = 'objtype';
span.appendChild(img);
li.appendChild(span);
// add edit "button"
const editspan = document.createElement('span');
const ielem = document.createElement('i');
ielem.className = 'icon-edit';
editspan.className = 'edit';
editspan.title = 'Edit JSON';
editspan.appendChild(ielem);
li.appendChild(editspan);
editspan.onclick = (function () {
const obj = sceneObjs[i];
return function () {
persist.editObjHandler(obj);
};
})();
if (sceneObjs[i].object_id === focusObjectId) {
persist.editObjHandler(sceneObjs[i]);
}
// add 3d edit "button"
if (sceneObjs[i].type !== 'program') {
const editspan3d = document.createElement('span');
const ielem3d = document.createElement('i');
ielem3d.className = 'icon-globe';
editspan3d.className = 'edit3d';
editspan3d.title = 'Edit 3D';
editspan3d.appendChild(ielem3d);
li.appendChild(editspan3d);
editspan3d.onclick = function () {
if (sceneObjs[i].type === 'scene-options') {
window.open(`/${scene}?build3d=1&objectId=env`, 'Arena3dEditor');
} else {
window.open(`/${scene}?build3d=1&objectId=${sceneObjs[i].object_id}`, 'Arena3dEditor');
}
};
}
// add visibility convenience "button"
let visible = Object.hasOwn(sceneObjs[i].attributes, 'visible') ? sceneObjs[i].attributes.visible : true;
const visspan = document.createElement('span');
const iconVis = document.createElement('i');
updateListItemVisibility(visible, li, iconVis);
visspan.className = 'visible';
visspan.title = 'Toggle Visible';
visspan.appendChild(iconVis);
li.appendChild(visspan);
visspan.onclick = function () {
visible = !visible;
updateListItemVisibility(visible, li, iconVis);
persist.visObjHandler(sceneObjs[i], visible);
};
persist.objList.appendChild(li);
}
persist.addEditSection.style = 'display:block';
}
export async function populateNamespaceList(nsInput, nsList) {
if (!persist.authState.authenticated) return; // should not be called when we are not logged in
let scenes = [];
// get editable scenes...
try {
const uScenes = await ARENAUserAccount.userScenes();
uScenes.forEach((uScene) => {
scenes.push(uScene.name);
});
} catch (err) {
Alert.fire({
icon: 'error',
title: `Error fetching scene list from account: ${err.statusText}`,
timer: 5000,
});
console.error(err);
return undefined;
}
// get public scenes...
if (persist.persistUri === undefined) {
throw 'Persist DB URL not defined.'; // should be called after persist_url is set
}
let sceneObjs;
try {
const persistOpt = ARENADefaults.disallowJWT
? {}
: {
credentials: 'include',
};
const data = await fetch(`${persist.persistUri}public/!allscenes`, persistOpt);
if (!data) {
throw 'Could not fetch data';
}
if (!data.ok) {
throw 'Fetch request result not ok';
}
const pScenes = await data.json();
scenes.push(...pScenes);
} catch (err) {
console.error(err);
return undefined;
}
// make distinct
scenes = [...new Set(scenes)];
// clear list
while (nsList.firstChild) {
nsList.removeChild(nsList.firstChild);
}
persist.scenes = [];
persist.namespaces = [];
if (scenes.length > 0) {
nsList.disabled = false;
// split scenes into scene name and namespace
for (let i = 0; i < scenes.length; i++) {
const sn = scenes[i].split('/');
if (sn.length < 2) continue;
if (persist.namespaces.indexOf(sn[0]) < 0) persist.namespaces.push(sn[0]);
persist.scenes.push({ ns: sn[0], name: sn[1] });
}
// sort lists
persist.namespaces.sort();
persist.scenes.sort();
}
// add user namespace if needed
if (persist.namespaces.indexOf(persist.authState.username) < 0) {
persist.namespaces.push(persist.authState.username);
}
// add public namespace if needed
if (persist.namespaces.indexOf('public') < 0) {
const option = document.createElement('option');
option.text = 'public';
nsList.appendChild(option);
}
// populate list
for (let i = 0; i < persist.namespaces.length; i++) {
const option = document.createElement('option');
option.text = persist.namespaces[i];
nsList.appendChild(option);
}
nsInput.value = persist.authState.username;
return persist.authState.username;
}
export function emptySceneInput(sceneInput) {
sceneInput.value = 'No Scenes';
sceneInput.disabled = true;
clearObjectList('No Scene Selected');
persist.addEditSection.style = 'display:none';
}
export function populateSceneList(ns, sceneInput, sceneList, selected = undefined) {
if (!persist.authState.authenticated) return; // should not be called when we are not logged in
if (persist.scenes.length === 0) {
emptySceneInput(sceneInput);
return;
}
// clear list
while (sceneList.firstChild) {
sceneList.removeChild(sceneList.firstChild);
}
sceneInput.disabled = false;
let first;
let selectedExists = false;
for (let i = 0; i < persist.scenes.length; i++) {
if (ns && persist.scenes[i].ns !== ns) continue;
if (!first) first = persist.scenes[i].name;
if (selected) {
if (selected === persist.scenes[i].name) selectedExists = true;
}
const option = document.createElement('option');
option.text = ns === undefined ? `${persist.scenes[i].ns}/${persist.scenes[i].name}` : persist.scenes[i].name;
// sceneList.add(option);
sceneList.appendChild(option);
}
if (!first) {
emptySceneInput(sceneInput);
} else if (!selected || !selectedExists) sceneInput.value = first;
else sceneInput.value = selected;
}
export function populateNewSceneNamespaces(nsInput, nsList) {
if (!persist.authState.authenticated) {
throw 'User must be authenticated.';
}
const ns = persist.namespaces;
if (persist.namespaces.indexOf('public') > 0) {
ns.push('public');
}
// clear list
while (nsList.firstChild) {
nsList.removeChild(nsList.firstChild);
}
// populate list
for (let i = 0; i < ns.length; i++) {
const option = document.createElement('option');
option.text = ns[i];
nsList.appendChild(option);
}
nsInput.value = persist.authState.username;
return ns;
}
export async function addNewScene(ns, sceneName, newObjs) {
const exists = persist.scenes.find((scene) => scene.ns === ns && scene.name === sceneName);
if (!exists) {
try {
const result = await ARENAUserAccount.requestUserNewScene(`${ns}/${sceneName}`);
} catch (err) {
Alert.fire({
icon: 'error',
title: `Error adding scene: ${err.statusText}`,
timer: 5000,
});
}
Alert.fire({
icon: 'info',
title: 'Scene added',
timer: 5000,
});
persist.scenes.push({ ns, name: sceneName });
}
if (!newObjs) return exists;
// add objects to the new scene
newObjs.forEach((obj) => {
addObject(obj, `${ns}/${sceneName}`);
});
return exists;
}
export async function deleteScene(ns, sceneName) {
selectedObjsPerformAction('delete', `${ns}/${sceneName}`, true);
let result;
try {
result = await ARENAUserAccount.requestDeleteUserScene(`${ns}/${sceneName}`);
} catch (err) {
Alert.fire({
icon: 'error',
title: `Error deleting scene: ${err.statusText}`,
timer: 5000,
});
console.error(err);
}
}
export function selectedObjsPerformAction(action, scene, all = false) {
const items = persist.objList.getElementsByTagName('li');
const objList = [];
for (let i = 0; i < items.length; i++) {
if (!items[i].classList.contains('checked') && !all) continue;
const objJson = items[i].getAttribute('data-obj');
if (!objJson) continue;
objList.push(objJson);
}
performActionArgObjList(action, scene, objList);
}
export function performActionArgObjList(action, scene, objList, json = true) {
let theNewScene = scene;
if (!persist.mqttConnected) mqttReconnect();
for (let i = 0; i < objList.length; i++) {
const obj = json ? JSON.parse(objList[i]) : objList[i];
const actionObj = JSON.stringify({
object_id: obj.object_id,
action,
persist: true,
type: obj.type,
data: obj.attributes !== undefined ? obj.attributes : obj.data,
});
if (!scene) {
scene = `${obj.namespace}/${obj.sceneId}`;
theNewScene = obj.sceneId;
}
const topic = `realm/s/${scene}/${obj.object_id}`;
console.info(`Publish [ ${topic}]: ${actionObj}`);
try {
persist.mc.publish(topic, actionObj);
} catch (error) {
Alert.fire({
icon: 'error',
title: `Error: ${JSON.stringify(error)}`,
timer: 5000,
});
return;
}
}
return theNewScene;
}
export function selectAll() {
const items = persist.objList.getElementsByTagName('li');
for (let i = 0; i < items.length; i++) {
items[i].classList.add('checked');
}
}
export function clearSelected() {
const items = persist.objList.getElementsByTagName('li');
for (let i = 0; i < items.length; i++) {
items[i].classList.remove('checked');
}
}
export async function addObject(obj, scene) {
let found = false;
if (!persist.mqttConnected) mqttReconnect();
for (let i = 0; i < persist.currentSceneObjs.length; i++) {
if (persist.currentSceneObjs[i].object_id === obj.object_id) {
found = true;
break;
}
}
if (obj.action === 'update') {
if (found === false) {
const result = await Swal.fire({
title: 'Update non-existing object ?',
html: 'You probably want to <b>create</b> new objects (update usually will have no effect).',
showDenyButton: true,
showCancelButton: true,
confirmButtonText: `Create`,
denyButtonText: `Update (i'm sure)`,
});
console.log(result);
if (result.isConfirmed) {
obj.action = 'create';
} else if (result.isDismissed) {
Alert.fire({
icon: 'warning',
title: 'Canceled',
html: 'Add/Update Canceled',
timer: 10000,
});
return;
}
}
}
// set overwrite to true so previous attributes are removed
if (found) obj.overwrite = true;
const persistAlert = obj.persist === false ? '<br/><strong>Object not persisted.</strong>' : '';
const objJson = JSON.stringify(obj);
const topic = `realm/s/${scene}/${obj.object_id}`;
console.info(`Publish [ ${topic}]: ${objJson}`);
try {
persist.mc.publish(topic, objJson);
} catch (error) {
console.error(error);
Alert.fire({
icon: 'error',
title: `Error adding object. MQTT Error: ${error.message}. Try reloading.`,
timer: 5000,
});
return;
}
if (obj.action === 'update') {
if (found === true)
Alert.fire({
icon: 'warning',
title: 'Updated',
html: `Object update published (previous attributes overwritten/deleted). ${persistAlert}`,
timer: 5000,
});
} else {
Alert.fire({
icon: 'info',
title: 'Created',
html: `Object create published. ${persistAlert}`,
timer: 5000,
});
}
}
export function mqttReconnect(settings) {
settings = settings || {};
persist.mqttUri = settings.mqtt_uri !== undefined ? settings.mqtt_uri : 'wss://arena.andrew.cmu.edu/mqtt/';
if (persist.mc) persist.mc.disconnect();
console.info('Disconnected.');
// start mqtt client
persist.mc = new MqttClient({
uri: persist.mqttUri,
onMessageCallback: onMqttMessage,
onConnectionLost: onMqttConnectionLost,
mqtt_username: persist.mqttUsername,
mqtt_token: persist.mqttToken,
});
try {
persist.mc.connect();
} catch (error) {
Alert.fire({
icon: 'error',
title: `Error connecting to MQTT: ${JSON.stringify(error)}`,
timer: 5000,
});
return;
}
persist.mqttConnected = true;
console.info(`Connected to ${persist.mqttUri}`);
}
// callback from mqttclient; on reception of message
function onMqttMessage(message) {}
function onMqttConnectionLost() {
persist.mqttConnected = false;
}