app.js 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291
  1. import { Lang } from '/lib/polyglot/language.js';
  2. import { Helpers } from '/helpers.js';
  3. import { IndexApp } from '/web/index-app.js';
  4. import { Widgets } from '/lib/widgets.js';
  5. class App {
  6. constructor() {
  7. console.log("app constructor");
  8. this.widgets = new Widgets;
  9. //globals
  10. window._app = this;
  11. window._cellWidgets = this.widgets;
  12. window._LangManager = new Lang;
  13. window._noty = new Noty;
  14. _LangManager.setLanguage().then(res => {
  15. return this.initDB()
  16. }).then(res => {
  17. this.helpers = new Helpers;
  18. this.initUser();
  19. //client routes
  20. page('/', this.HandleIndex);
  21. page('/setup', this.HandleSetupIndex);
  22. page('/profile', this.HandleUserIndex);
  23. page('/worlds', this.HandleIndex);
  24. page('/:user/worlds', this.HandleUserWorlds);
  25. page('/:user/worlds/:type', this.HandleUserWorldsWithType);
  26. page('/:user/:type/:name/edit/:file', this.HandleFileEdit);
  27. page('/:user/:space', this.HandleParsableRequestGenID);
  28. page('/:user/:space/:id', this.HandleParsableRequestWithID);
  29. page('/:user/:space/index.vwf/:id', this.HandleParsableRequestWithID);
  30. page('/:user/:space/load/:savename', this.HandleParsableLoadRequest);
  31. page('/:user/:space/:id/load/:savename', this.HandleParsableRequestWithID);
  32. page('/:user/:space/load/:savename/:rev', this.HandleParsableLoadRequestWithRev);
  33. page('/:user/:space/:id/load/:savename/:rev', this.HandleParsableRequestWithID);
  34. page('*', this.HandleNoPage);
  35. page();
  36. })
  37. }
  38. initDB() {
  39. var config = JSON.parse(localStorage.getItem('lcs_config'));
  40. if (!config) {
  41. config = {
  42. 'dbhost': 'https://' + window.location.hostname + ':8080/gun', //'http://localhost:8080/gun',
  43. 'reflector': 'https://' + window.location.hostname + ':3002',
  44. 'language': 'en'
  45. }
  46. localStorage.setItem('lcs_config', JSON.stringify(config));
  47. }
  48. const dbConnection = new Promise((resolve, reject) => {
  49. this.db = Gun(this.dbHost);
  50. this.user = this.db.user();
  51. window._LCSDB = this.db;
  52. window._LCSUSER = this.user;
  53. window._LCS_SYS_USER = undefined;
  54. window._LCS_WORLD_USER = undefined;
  55. _LCSDB.get('lcs/app').get('pub').once(res => {
  56. if (res) {
  57. window._LCS_SYS_USER = this.db.user(res);
  58. }
  59. });
  60. _LCSDB.on('hi', function (peer) {
  61. let msg = 'Connected to ' + peer.url;
  62. let noty = new Noty({
  63. text: msg,
  64. timeout: 2000,
  65. theme: 'mint',
  66. layout: 'bottomRight',
  67. type: 'success'
  68. });
  69. noty.show();
  70. console.log(msg)
  71. })
  72. _LCSDB.on('bye', function (peer) {
  73. let msg = 'No connection to ' + peer.url;
  74. let noty = new Noty({
  75. text: msg,
  76. timeout: 1000,
  77. theme: 'mint',
  78. layout: 'bottomRight',
  79. type: 'error'
  80. });
  81. noty.show();
  82. console.log(msg)
  83. })
  84. resolve('ok');
  85. });
  86. return dbConnection
  87. }
  88. initUser() {
  89. _LCSUSER.recall({ sessionStorage: 1 });
  90. }
  91. get reflectorHost() {
  92. var res = "";
  93. let config = localStorage.getItem('lcs_config');
  94. if (config) {
  95. res = JSON.parse(config).reflector;
  96. }
  97. return res;
  98. }
  99. get dbHost() {
  100. var res = "";
  101. let config = localStorage.getItem('lcs_config');
  102. if (config) {
  103. res = JSON.parse(config).dbhost;
  104. }
  105. return res;
  106. }
  107. async loadProxyDefaults() {
  108. //load to DB default proxy files (VWF & A-Frame components)
  109. let proxyResponse = await fetch('/proxy-files', { method: 'get' });
  110. let proxyFiles = await proxyResponse.json();
  111. let filterProxyFiles = proxyFiles.filter(el => (el !== null));
  112. console.log(filterProxyFiles);
  113. var origin = window.location.origin;
  114. //var userPub = _LCSUSER.is.pub;
  115. let proxyObj = {};
  116. for (var index in filterProxyFiles) {
  117. let el = filterProxyFiles[index];
  118. if (el) {
  119. var url = origin + el;
  120. var entryName = url.replace(origin + '/defaults/', "").split(".").join("_");
  121. let proxyFile = await fetch(url, { method: 'get' });
  122. let responseText = await proxyFile.text();
  123. if (responseText) {
  124. let obj = {
  125. //'owner': userPub,
  126. 'file': responseText
  127. }
  128. proxyObj[entryName] = obj;
  129. }
  130. }
  131. }
  132. console.log(proxyObj);
  133. Object.keys(proxyObj).forEach(el => {
  134. _LCSDB.user().get('proxy').get(el).put(proxyObj[el]);
  135. })
  136. }
  137. async loadWorldsDefaults() {
  138. //load to DB default worlds
  139. let worldsResponse = await fetch('/world-files', { method: 'get' });
  140. let worldFiles = await worldsResponse.json();
  141. let filterworldFiles = worldFiles.filter(el => (el !== null));
  142. console.log(filterworldFiles);
  143. let worldsObj = {};
  144. for (var index in filterworldFiles) {
  145. let el = filterworldFiles[index];
  146. if (el) {
  147. let url = window.location.origin + el;
  148. var entryName = url.replace(window.location.origin + '/defaults/worlds/', "").split(".").join("_");
  149. let worldName = entryName.split("/")[0];
  150. let userPub = _LCSUSER.is.pub;
  151. let worldFile = await fetch(url, { method: 'get' });
  152. let worldSource = await worldFile.text();
  153. if (worldSource) {
  154. let modified = new Date().valueOf();
  155. let obj = {
  156. 'file': worldSource,
  157. 'modified': modified
  158. }
  159. if (!worldsObj[worldName]) {
  160. worldsObj[worldName] = {
  161. 'parent': '-',
  162. 'owner': userPub,
  163. 'featured': true,
  164. 'published': true
  165. }
  166. }
  167. let entry = entryName.replace(worldName + '/', "");
  168. worldsObj[worldName][entry] = obj;
  169. }
  170. }
  171. }
  172. console.log(worldsObj);
  173. Object.entries(worldsObj).forEach(el => {
  174. let worldName = el[0];
  175. let files = el[1];
  176. Object.entries(files).forEach(file => {
  177. _LCSDB.user().get('worlds').get(worldName).get(file[0]).put(file[1]);
  178. })
  179. })
  180. }
  181. async loadEmptyDefaultProto() {
  182. //empty proto world
  183. let userPub = _LCSUSER.is.pub;
  184. let worldsObj = {};
  185. let emptyWorld = {
  186. "index_vwf_yaml": YAML.stringify(
  187. {
  188. "extends": "http://vwf.example.com/aframe/ascene.vwf"
  189. }, 4),
  190. "index_vwf_config_yaml": YAML.stringify(
  191. {
  192. "info": {
  193. "title": "Empty World"
  194. },
  195. "model": {
  196. "vwf/model/aframe": null
  197. },
  198. "view": {
  199. "vwf/view/aframe": null,
  200. "vwf/view/editor-new": null
  201. }
  202. }, 4),
  203. "index_vwf_html": "",
  204. "appui_js": "",
  205. "info_json": JSON.stringify ({
  206. "info": {
  207. "en": {
  208. "title": "Empty World",
  209. "imgUrl": "",
  210. "text": "Empty World"
  211. },
  212. "ru": {
  213. "title": "Новый Мир",
  214. "imgUrl": "",
  215. "text": "Новый Мир"
  216. }
  217. }
  218. })
  219. }
  220. worldsObj['empty'] = {
  221. 'parent': '-',
  222. 'owner': userPub,
  223. 'featured': true,
  224. 'published': true
  225. }
  226. Object.keys(emptyWorld).forEach(el=>{
  227. let modified = new Date().valueOf();
  228. let obj = {
  229. 'file': emptyWorld[el],
  230. 'modified': modified
  231. }
  232. worldsObj['empty'][el] = obj;
  233. })
  234. console.log(worldsObj);
  235. Object.entries(worldsObj).forEach(el => {
  236. let worldName = el[0];
  237. let files = el[1];
  238. Object.entries(files).forEach(file => {
  239. _LCSDB.user().get('worlds').get(worldName).get(file[0]).put(file[1]);
  240. })
  241. })
  242. }
  243. //load defaults for first registered user running ./setup
  244. HandleSetupIndex() {
  245. window._app.hideProgressBar();
  246. window._app.hideUIControl();
  247. let el = document.createElement("div");
  248. el.setAttribute("id", "admin");
  249. document.body.appendChild(el);
  250. _LCSDB.on('auth',
  251. async function (ack) {
  252. if (_LCSUSER.is) {
  253. let setPubKey = {
  254. $cell: true,
  255. $components: [
  256. {
  257. $type: "p",
  258. class: "mdc-typography--headline5",
  259. $text: "1. Set app system user PUB key"
  260. },
  261. {
  262. $type: "button",
  263. class: "mdc-button mdc-button--raised",
  264. $text: "Set app PUB key",
  265. onclick: function (e) {
  266. console.log("admin action");
  267. _LCSDB.get('lcs/app').get('pub').put(_LCSUSER.is.pub);
  268. }
  269. }
  270. ]
  271. }
  272. let adminComponents = [];
  273. let defaultPub = await _LCSDB.get('lcs/app').get('pub').once().then();
  274. if (!defaultPub) {
  275. adminComponents.push(setPubKey);
  276. }
  277. if (_LCSUSER.is.pub == defaultPub) {
  278. let loadEmpty = {
  279. $cell: true,
  280. $components: [
  281. {
  282. $type: "p",
  283. class: "mdc-typography--headline5",
  284. $text: "3. Initialize empty World proto"
  285. },
  286. {
  287. $type: "button",
  288. id: "loadDefaults",
  289. class: "mdc-button mdc-button--raised",
  290. $text: "Init empty world",
  291. onclick: function (e) {
  292. console.log("admin action");
  293. window._app.loadEmptyDefaultProto();
  294. }
  295. }
  296. ]
  297. }
  298. let loadDefaults = {
  299. $cell: true,
  300. $components: [
  301. {
  302. $type: "p",
  303. class: "mdc-typography--headline5",
  304. $text: "4. Load Sample Worlds protos from server (optional)"
  305. },
  306. {
  307. $type: "button",
  308. id: "loadDefaults",
  309. class: "mdc-button mdc-button--raised",
  310. $text: "Load default worlds (from server)",
  311. onclick: function (e) {
  312. console.log("admin action");
  313. window._app.loadWorldsDefaults();
  314. }
  315. }
  316. ]
  317. }
  318. let loadDefaultsProxy = {
  319. $cell: true,
  320. $components: [
  321. {
  322. $type: "p",
  323. class: "mdc-typography--headline5",
  324. $text: "3. Load VWF & A-Frame default components"
  325. },
  326. {
  327. $type: "button",
  328. class: "mdc-button mdc-button--raised",
  329. $text: "Load defaults Proxy",
  330. onclick: function (e) {
  331. console.log("admin action");
  332. window._app.loadProxyDefaults();
  333. }
  334. }
  335. ]
  336. }
  337. adminComponents.push(setPubKey, loadDefaultsProxy, loadEmpty, loadDefaults);
  338. }
  339. document.querySelector("#admin").$cell({
  340. $cell: true,
  341. id: 'adminComponents',
  342. $type: "div",
  343. $components: adminComponents
  344. });
  345. }
  346. })
  347. }
  348. //TODO: profile
  349. HandleUserIndex(ctx) {
  350. console.log("USER INDEX");
  351. window._app.hideProgressBar();
  352. window._app.hideUIControl();
  353. _LCSDB.on('auth',
  354. async function (ack) {
  355. if(ack.pub){
  356. document.querySelector("#profile")._status = "User: " + _LCSUSER.is.alias //+' pub: ' + _LCSUSER.is.pub;
  357. document.querySelector("#profile").$update();
  358. }
  359. })
  360. let el = document.createElement("div");
  361. el.setAttribute("id", "userProfile");
  362. document.body.appendChild(el);
  363. let userProfile = {
  364. $type: 'div',
  365. id: "profile",
  366. _status: "",
  367. $init: function(){
  368. this._status = "user is not signed in..."
  369. },
  370. $update: function(){
  371. this.$components = [
  372. {
  373. $type: "h1",
  374. class: "mdc-typography--headline4",
  375. $text: this._status //"Profile for: " + _LCSUSER.is.alias
  376. }
  377. ]
  378. }
  379. }
  380. document.querySelector("#userProfile").$cell({
  381. $cell: true,
  382. $type: "div",
  383. $components: [userProfile]
  384. })
  385. }
  386. async HandleUserWorlds(ctx) {
  387. console.log("USER WORLDS INDEX");
  388. console.log(ctx.params);
  389. let user = ctx.params.user;
  390. page.redirect('/' + user + '/worlds/protos');
  391. }
  392. async HandleFileEdit(ctx) {
  393. console.log("USER WORLD FILE EDIT");
  394. let user = ctx.params.user;
  395. let worldName = ctx.params.name;
  396. let fileOriginal = ctx.params.file;
  397. let type = ctx.params.type;
  398. window._app.hideProgressBar();
  399. window._app.hideUIControl();
  400. _LCSDB.on('auth',
  401. async function (ack) {
  402. if (_LCSUSER.is) {
  403. if (_LCSUSER.is.alias == user) {
  404. var worldType = 'worlds';
  405. var file = fileOriginal;
  406. if (type == 'state') {
  407. worldType = 'documents';
  408. file = _app.helpers.replaceSubStringALL(fileOriginal, "~", '/');
  409. }
  410. let worldFile = await _LCSUSER.get(worldType).get(worldName).get(file).once().then();
  411. if (worldFile) {
  412. console.log(worldFile.file);
  413. let el = document.createElement("div");
  414. el.setAttribute("id", "worldFILE");
  415. document.body.appendChild(el);
  416. let aceEditorCell = {
  417. $type: "div",
  418. $components: [
  419. {
  420. class: "aceEditor",
  421. id: "aceEditor",
  422. //style: "width:1200px; height: 800px",
  423. $type: "div",
  424. $text: worldFile.file,
  425. $init: function () {
  426. var mode = "ace/mode/json";
  427. if (file.includes('_yaml'))
  428. mode = "ace/mode/yaml"
  429. if (file.includes('_js'))
  430. mode = "ace/mode/javascript"
  431. var editor = ace.edit("aceEditor");
  432. editor.setTheme("ace/theme/monokai");
  433. editor.setFontSize(16);
  434. editor.getSession().setMode(mode);
  435. editor.setOptions({
  436. maxLines: Infinity
  437. });
  438. }
  439. },
  440. {
  441. $type: "button",
  442. class: "mdc-button mdc-button--raised",
  443. $text: "Save",
  444. onclick: async function (e) {
  445. console.log("save new info");
  446. let editor = document.querySelector("#aceEditor").env.editor;
  447. let newInfo = editor.getValue();
  448. _LCSUSER.get(worldType).get(worldName).get(file).get('file').put(newInfo, res => {
  449. if (res) {
  450. let modified = new Date().valueOf();
  451. _LCSUSER.get(worldType).get(worldName).get(file).get('modified').put(modified);
  452. }
  453. })
  454. }
  455. },
  456. {
  457. $type: "button",
  458. class: "mdc-button mdc-button--raised",
  459. $text: "Close",
  460. onclick: function (e) {
  461. console.log("close");
  462. if (type == "proto")
  463. window.location.pathname = "/" + user + '/worlds/protos'
  464. if (type == "state")
  465. window.location.pathname = "/" + user + '/worlds/states'
  466. }
  467. }
  468. ]
  469. }
  470. document.querySelector("#worldFILE").$cell({
  471. $cell: true,
  472. $type: "div",
  473. $components: [aceEditorCell
  474. ]
  475. })
  476. }
  477. }
  478. }
  479. })
  480. }
  481. async HandleUserWorldsWithType(ctx) {
  482. console.log("USER WORLDS INDEX");
  483. console.log(ctx.params);
  484. let user = ctx.params.user;
  485. let type = ctx.params.type;
  486. window._app.hideProgressBar();
  487. window._app.hideUIControl();
  488. if (!_app.indexApp) {
  489. _app.indexApp = new IndexApp;
  490. document.querySelector('head').innerHTML += '<link rel="stylesheet" href="/web/index-app.css">';
  491. }
  492. if (!document.querySelector('#app')) {
  493. await _app.indexApp.initApp();
  494. }
  495. if (type == 'protos') {
  496. await _app.indexApp.getWorldsProtosFromUserDB(user);
  497. } else if (type == 'states') {
  498. await _app.indexApp.getWorldsFromUserDB(user);
  499. }
  500. }
  501. async HandleIndex() {
  502. console.log("INDEX");
  503. window._app.hideProgressBar();
  504. window._app.hideUIControl();
  505. _app.indexApp = new IndexApp;
  506. document.querySelector('head').innerHTML += '<link rel="stylesheet" href="/web/index-app.css">';
  507. await _app.indexApp.generateFrontPage();
  508. await _app.indexApp.initApp();
  509. await _app.indexApp.getAppDetailsFromDB();
  510. }
  511. HandleNoPage() {
  512. console.log("no such page")
  513. }
  514. //handle parcable requests
  515. HandleParsableLoadRequest(ctx) {
  516. let app = window._app;
  517. console.log(ctx.params);
  518. //var pathname = ctx.pathname;
  519. var spaceName = ctx.params.space;
  520. var saveName = ctx.params.savename;
  521. let user = ctx.params.user;
  522. page.redirect('/' + user + '/' + spaceName + '/' + app.helpers.GenerateInstanceID() + '/load/' + saveName);
  523. }
  524. HandleParsableLoadRequestWithRev(ctx) {
  525. let app = window._app;
  526. console.log(ctx.params);
  527. //var pathname = ctx.pathname;
  528. var spaceName = ctx.params.space;
  529. var saveName = ctx.params.savename;
  530. var rev = ctx.params.rev;
  531. let user = ctx.params.user;
  532. page.redirect('/' + user + '/' + spaceName + '/' + app.helpers.GenerateInstanceID() + '/load/' + saveName + '/' + rev);
  533. }
  534. async setUserPaths(user) {
  535. await _LCSDB.get('users').get(user).get('pub').once(res => {
  536. if (res)
  537. window._LCS_WORLD_USER = _LCSDB.user(res);
  538. }).then();
  539. }
  540. async HandleParsableRequestGenID(ctx) {
  541. let app = window._app;
  542. console.log(ctx.params);
  543. let user = ctx.params.user;
  544. var pathname = ctx.pathname;
  545. await app.setUserPaths(user);
  546. if (pathname[pathname.length - 1] == '/') {
  547. pathname = pathname.slice(0, -1)
  548. }
  549. let pathToParse = pathname.replace('/' + user, "");
  550. app.helpers.Process(pathToParse).then(parsedRequest => {
  551. localStorage.setItem('lcs_app', JSON.stringify({ path: parsedRequest }));
  552. console.log(parsedRequest);
  553. if ((parsedRequest['instance'] == undefined) && (parsedRequest['private_path'] == undefined) && (parsedRequest['public_path'] !== "/") && (parsedRequest['application'] !== undefined)) {
  554. page.redirect(pathname + '/' + app.helpers.GenerateInstanceID());
  555. }
  556. });
  557. }
  558. async HandleParsableRequestWithID(ctx) {
  559. let app = window._app;
  560. console.log(ctx.params);
  561. var pathname = ctx.pathname;
  562. let user = ctx.params.user;
  563. if (pathname[pathname.length - 1] == '/') {
  564. pathname = pathname.slice(0, -1)
  565. }
  566. await app.setUserPaths(user);
  567. let pathToParse = pathname.replace('/' + user, "");
  568. app.helpers.Process(pathToParse).then(parsedRequest => {
  569. localStorage.setItem('lcs_app', JSON.stringify({ path: parsedRequest }));
  570. console.log(parsedRequest);
  571. var userLibraries = { model: {}, view: {} };
  572. var application;
  573. vwf.loadConfiguration(application, userLibraries, compatibilityCheck);
  574. });
  575. }
  576. async HandleParsableRequest(ctx) {
  577. let app = window._app;
  578. console.log(ctx.params);
  579. var pathname = ctx.pathname;
  580. if (pathname[pathname.length - 1] == '/') {
  581. pathname = pathname.slice(0, -1)
  582. }
  583. var parsedRequest = await app.helpers.Process(pathname);
  584. localStorage.setItem('lcs_app', JSON.stringify({ path: parsedRequest }));
  585. console.log(parsedRequest);
  586. if ((parsedRequest['instance'] == undefined) && (parsedRequest['private_path'] == undefined) && (parsedRequest['public_path'] !== "/") && (parsedRequest['application'] !== undefined)) {
  587. // Redirect if the url request does not include an application/file && a default 'index.vwf.yaml' exists
  588. // page.redirect(pathname + '/' + app.helpers.GenerateInstanceID());
  589. window.location.pathname = pathname + '/' + app.helpers.GenerateInstanceID()
  590. //return true;
  591. } else {
  592. //return false;
  593. }
  594. var userLibraries = { model: {}, view: {} };
  595. var application;
  596. vwf.loadConfiguration(application, userLibraries, compatibilityCheck);
  597. }
  598. //get DB application state information for reflector (called from VWF)
  599. async getApplicationState() {
  600. let dataJson = JSON.parse(localStorage.getItem('lcs_app'));
  601. if (dataJson) {
  602. if (!dataJson.path['instance']) return undefined;
  603. }
  604. let userAlias = await _LCS_WORLD_USER.get('alias').once().then();
  605. let userPub = await _LCSDB.get('users').get(userAlias).get('pub').once().then();
  606. let loadInfo = await this.getLoadInformation(dataJson);
  607. let saveInfo = await this.loadSaveObject(loadInfo);
  608. let loadObj = {
  609. loadInfo: loadInfo,
  610. path: dataJson.path,
  611. saveObject: saveInfo,
  612. user: userAlias
  613. }
  614. console.log(loadObj);
  615. //temporary solution for syncing DB replicas using Gun.load()
  616. await _LCS_SYS_USER.get('proxy').load(res=>{}, {wait: 200}).then();
  617. await _LCSDB.user(userPub).get('worlds').get(loadObj.path.public_path.slice(1)).load(res=>{}, {wait: 200}).then();
  618. return loadObj
  619. }
  620. // LookupSaveRevisions takes the public path and the name of a save, and provides
  621. // an array of all revisions for that save. (If the save does not exist, this will be
  622. // an empty array).
  623. async lookupSaveRevisions(public_path, save_name) {
  624. var result = [];
  625. var states = [];
  626. let docName = 'savestate_/' + public_path + '/' + save_name + '_vwf_json';
  627. let revs = await _LCS_WORLD_USER.get('documents').get(public_path).get(docName).get('revs').once().then();
  628. if (revs) {
  629. for (const res of Object.keys(revs)) {
  630. if (res !== '_') {
  631. let el = await _LCS_WORLD_USER.get('documents').get(public_path).get(docName).get('revs').get(res).once().then();
  632. if (el)
  633. result.push(parseInt(el.revision));
  634. }
  635. }
  636. return result
  637. }
  638. }
  639. // GetLoadInformation receives a parsed request {private_path, public_path, instance, application} and returns the
  640. // details of the save that is designated by the initial request. The details are returned in an object
  641. // composed of: save_name (name of the save) save_revision (revision of the save), explicit_revision (boolean, true if the request
  642. // explicitly specified the revision, false if it did not), and application_path (the public_path of the application this is a save for).
  643. async getLoadInformation(response) {
  644. let parsedRequest = response.path;
  645. var result = { 'save_name': undefined, 'save_revision': undefined, 'explicit_revision': undefined, 'application_path': undefined };
  646. if (parsedRequest['private_path']) {
  647. var segments = this.helpers.GenerateSegments(parsedRequest['private_path']);
  648. if ((segments.length > 1) && (segments[0] == "load")) {
  649. var potentialRevisions = await this.lookupSaveRevisions((parsedRequest['public_path']).slice(1), segments[1]);
  650. console.log('!!!!! - ', potentialRevisions);
  651. if (potentialRevisions.length > 0) {
  652. result['save_name'] = segments[1];
  653. if (segments.length > 2) {
  654. var requestedRevision = parseInt(segments[2]);
  655. if (requestedRevision) {
  656. if (potentialRevisions.indexOf(requestedRevision) > -1) {
  657. result['save_revision'] = requestedRevision;
  658. result['explicit_revision'] = true;
  659. result['application_path'] = parsedRequest['public_path'];
  660. }
  661. }
  662. }
  663. if (result['explicit_revision'] == undefined) {
  664. result['explicit_revision'] = false;
  665. potentialRevisions.sort();
  666. result['save_revision'] = potentialRevisions.pop();
  667. result['application_path'] = parsedRequest['public_path'];
  668. }
  669. }
  670. }
  671. }
  672. return result;
  673. }
  674. async loadSaveObject(loadInfo) {
  675. //let objName = loadInfo[ 'save_name' ] +'/'+ "savestate_" + loadInfo[ 'save_revision' ];
  676. let objName = "savestate_" + loadInfo['application_path'] + '/' + loadInfo['save_name'] + '_vwf_json';
  677. let objNameRev = "savestate_" + loadInfo['save_revision'] + loadInfo['application_path'] + '/' + loadInfo['save_name'] + '_vwf_json';
  678. // if(loadInfo[ 'save_revision' ]){
  679. // }
  680. let worldName = this.helpers.appPath //loadInfo[ 'application_path' ].slice(1);
  681. let saveObject = await _LCS_WORLD_USER.get('documents').get(worldName).get(objName).get('revs').get(objNameRev).once().then();
  682. let saveInfo = saveObject ? JSON.parse(saveObject.jsonState) : saveObject;
  683. return saveInfo;
  684. }
  685. // GetSaveInformation is a helper function that takes the application_path (/path/to/application).
  686. // It returns an array of all saves found for that
  687. // application (including separate entries for individual revisions of saves ).
  688. async getSaveInformation(application_path, userPUB) {
  689. var result = [];
  690. let user = _LCSDB.user(userPUB);
  691. var docName = application_path.slice(1);
  692. let potentialSaveNames = await user.get('documents').get(docName).once().then();
  693. if (potentialSaveNames) {
  694. for (const res of Object.keys(potentialSaveNames)) {
  695. if (res !== '_') {
  696. let el = await user.get('documents').path(docName).get(res).once().then();
  697. let revisionList = await this.lookupSaveRevisions(application_path.slice(1), el.filename);
  698. var latestsave = true;
  699. revisionList.sort();
  700. while (revisionList.length > 0) {
  701. var newEntry = {};
  702. newEntry['applicationpath'] = application_path;
  703. newEntry['savename'] = el.filename;
  704. newEntry['revision'] = revisionList.pop().toString();
  705. newEntry['latestsave'] = latestsave;
  706. if (latestsave) {
  707. newEntry['url'] = this.helpers.JoinPath(window.location.origin, application_path, "load", el.filename + "/");
  708. }
  709. else {
  710. newEntry['url'] = this.helpers.JoinPath(window.location.origin, application_path, "load", el.filename + "/", newEntry['revision'] + "/");
  711. }
  712. latestsave = false;
  713. result.push(newEntry);
  714. }
  715. }
  716. }
  717. }
  718. return result;
  719. }
  720. async getProtoWorldFiles(userPub, worldName, date) {
  721. let fileNamesAll = await _LCSDB.user(userPub).get('worlds').get(worldName).once().then();
  722. let worldFileNames = Object.keys(fileNamesAll).filter(el => (el !== '_') && (el !== 'owner') && (el !== 'parent')
  723. && (el !== 'info_json'));
  724. let worldObj = {};
  725. for (var el in worldFileNames) {
  726. let fn = worldFileNames[el];
  727. let res = await _LCSDB.user(userPub).get('worlds').get(worldName).get(fn).once().then();
  728. var data = {
  729. 'file': res.file,
  730. 'modified': res.modified
  731. }
  732. if (!date) {
  733. data = {
  734. 'file': res.file
  735. }
  736. }
  737. worldObj[fn] = data;
  738. }
  739. console.log(worldObj);
  740. return worldObj
  741. }
  742. async cloneWorldPrototype(worldName, userName, newWorldName) {
  743. let userPub = await _LCSDB.get('users').get(userName).get('pub').once().then();
  744. //let worldProto = await _LCSDB.user(userPub).get('worlds').get(worldName).once().then();
  745. var worldID = window._app.helpers.GenerateInstanceID().toString();
  746. if (newWorldName) {
  747. worldID = newWorldName
  748. }
  749. //let modified = new Date().valueOf();
  750. console.log('clone: ' + worldName + 'to: ' + worldID);
  751. let newOwner = _LCSUSER.is.pub;
  752. let worldObj = {
  753. 'owner': newOwner,
  754. 'parent': userName + '/' + worldName,
  755. 'featured': true,
  756. 'published': true
  757. };
  758. let fileNamesAll = await _LCSDB.user(userPub).get('worlds').get(worldName).once().then();
  759. let worldFileNames = Object.keys(fileNamesAll).filter(el => (el !== '_') && (el !== 'owner') && (el !== 'parent') && (el !== 'featured') && (el !== 'published'));
  760. for (var el in worldFileNames) {
  761. let fn = worldFileNames[el];
  762. let res = await _LCSDB.user(userPub).get('worlds').get(worldName).get(fn).once().then();
  763. let data = {
  764. 'file': res.file,
  765. 'modified': res.modified
  766. }
  767. worldObj[fn] = data;
  768. }
  769. console.log(worldObj);
  770. Object.keys(worldObj).forEach(el => {
  771. _LCSUSER.get('worlds').get(worldID).get(el).put(worldObj[el]);
  772. })
  773. }
  774. async cloneWorldState(filename) {
  775. let myWorldProtos = await _LCSUSER.get('worlds').once().then();
  776. let userName = this.helpers.worldUser;
  777. let userPub = await _LCSDB.get('users').get(userName).get('pub').once().then();
  778. let protoUserRoot = this.helpers.getRoot(true).root;
  779. //let myName = _LCSUSER.is.alias;
  780. //let proto = Object.keys(myWorldProtos).filter(el => el == protoUserRoot);
  781. var protosKeys = [];
  782. if (myWorldProtos)
  783. protosKeys = Object.keys(myWorldProtos);
  784. if (protosKeys.includes(protoUserRoot)) {
  785. let userProtoFiles = await this.getProtoWorldFiles(userPub, protoUserRoot);
  786. let myProtoFiles = await this.getProtoWorldFiles(_LCSUSER.is.pub, protoUserRoot);
  787. let hashUP = await this.helpers.sha256(JSON.stringify(userProtoFiles));
  788. let hashMP = await this.helpers.sha256(JSON.stringify(myProtoFiles));
  789. if (hashUP == hashMP) {
  790. this.saveStateAsFile(filename);
  791. } else {
  792. let noty = new Noty({
  793. text: 'world prototype is modified.. could not clone world state',
  794. timeout: 2000,
  795. theme: 'mint',
  796. layout: 'bottomRight',
  797. type: 'error'
  798. });
  799. noty.show();
  800. }
  801. } else {
  802. await this.cloneWorldPrototype(protoUserRoot, userName, protoUserRoot);
  803. this.saveStateAsFile(filename);
  804. }
  805. }
  806. //TODO: refactor and config save
  807. saveStateAsFile(filename, otherProto) // invoke with the view as "this"
  808. {
  809. console.log("Saving: " + filename);
  810. //var clients = this.nodes["http://vwf.example.com/clients.vwf"];
  811. // Save State Information
  812. var state = vwf.getState();
  813. state.nodes[0].children = {};
  814. var timestamp = state["queue"].time;
  815. timestamp = Math.round(timestamp * 1000);
  816. var objectIsTypedArray = function (candidate) {
  817. var typedArrayTypes = [
  818. Int8Array,
  819. Uint8Array,
  820. // Uint8ClampedArray,
  821. Int16Array,
  822. Uint16Array,
  823. Int32Array,
  824. Uint32Array,
  825. Float32Array,
  826. Float64Array
  827. ];
  828. var isTypedArray = false;
  829. if (typeof candidate == "object" && candidate != null) {
  830. typedArrayTypes.forEach(function (typedArrayType) {
  831. isTypedArray = isTypedArray || candidate instanceof typedArrayType;
  832. });
  833. }
  834. return isTypedArray;
  835. };
  836. var transitTransformation = function (object) {
  837. return objectIsTypedArray(object) ?
  838. Array.prototype.slice.call(object) : object;
  839. };
  840. let jsonValuePure = require("vwf/utility").transform(
  841. state, transitTransformation
  842. );
  843. //remove all Ohm generated grammarsfrom state
  844. let jsonValue = _app.helpers.removeGrammarObj(jsonValuePure);
  845. var jsonState = JSON.stringify(jsonValue);
  846. let rootPath = this.helpers.getRoot(true);
  847. var inst = rootPath.inst;
  848. if (filename == '') filename = inst;
  849. //if (root.indexOf('.vwf') != -1) root = root.substring(0, root.lastIndexOf('/'));
  850. var root = rootPath.root;
  851. var json = jsonState;
  852. if (otherProto) {
  853. console.log('need to modify state...');
  854. json = this.helpers.replaceSubStringALL(jsonState, '/' + root + '/', '/' + otherProto + '/');//jsonState.replace(('/' + root + '/'), ('/' + otherProto +'/') );
  855. root = otherProto;
  856. console.log(json);
  857. }
  858. //var documents = _LCSUSER.get('documents');
  859. var saveRevision = new Date().valueOf();
  860. var stateForStore = {
  861. "root": root,
  862. "filename": filename,
  863. "inst": inst,
  864. "timestamp": timestamp,
  865. "extension": ".vwf.json",
  866. "jsonState": json,
  867. "publish": true
  868. };
  869. //let objName = loadInfo[ 'save_name' ] +'/'+ "savestate_" + loadInfo[ 'save_revision' ];
  870. // "savestate_" + loadInfo[ 'save_revision' ] + '/' + loadInfo[ 'save_name' ] + '_vwf_json'
  871. var docName = 'savestate_/' + root + '/' + filename + '_vwf_json';
  872. _LCSUSER.get('documents').get(root).get(docName).put(stateForStore, res => {
  873. if (res) {
  874. let noty = new Noty({
  875. text: 'Saved to ' + docName,
  876. timeout: 2000,
  877. theme: 'mint',
  878. layout: 'bottomRight',
  879. type: 'success'
  880. });
  881. noty.show();
  882. }
  883. });
  884. _LCSUSER.get('worlds').get(root).get('info_json').once(res => {
  885. if (res) {
  886. let modified = new Date().valueOf();
  887. let newOwner = _LCSUSER.is.pub;
  888. let userName = _LCSUSER.is.alias;
  889. let obj = {
  890. 'parent': userName + '/' + root,
  891. 'owner': newOwner,
  892. 'file': res.file,
  893. 'modified': modified
  894. }
  895. let docInfoName = 'savestate_/' + root + '/' + filename + '_info_vwf_json';
  896. _LCSUSER.get('documents').get(root).get(docInfoName).not(res => {
  897. _LCSUSER.get('documents').get(root).get(docInfoName).put(obj);
  898. });
  899. }
  900. });
  901. var docNameRev = 'savestate_' + saveRevision.toString() + '/' + root + '/' + filename + '_vwf_json';
  902. _LCSUSER.get('documents').get(root).get(docName).get('revs').get(docNameRev).put(stateForStore)
  903. .path("revision").put(saveRevision);
  904. // Save Config Information
  905. var config = { "info": {}, "model": {}, "view": {} };
  906. // Save browser title
  907. config["info"]["title"] = document.title//$('title').html();
  908. // Save model drivers
  909. Object.keys(vwf_view.kernel.kernel.models).forEach(function (modelDriver) {
  910. if (modelDriver.indexOf('vwf/model/') != -1) config["model"][modelDriver] = "";
  911. });
  912. // If neither glge or threejs model drivers are defined, specify nodriver
  913. if (config["model"]["vwf/model/glge"] === undefined && config["model"]["vwf/model/threejs"] === undefined) config["model"]["nodriver"] = "";
  914. // Save view drivers and associated parameters, if any
  915. Object.keys(vwf_view.kernel.kernel.views).forEach(function (viewDriver) {
  916. if (viewDriver.indexOf('vwf/view/') != -1) {
  917. if (vwf_view.kernel.kernel.views[viewDriver].parameters) {
  918. config["view"][viewDriver] = vwf_view.kernel.kernel.views[viewDriver].parameters;
  919. }
  920. else config["view"][viewDriver] = "";
  921. }
  922. });
  923. //var jsonConfig = $.encoder.encodeForURL(JSON.stringify(config));
  924. var jsonConfig = JSON.stringify(config);
  925. let configStateForStore = {
  926. "root": root,
  927. "filename": filename,
  928. "inst": inst,
  929. "timestamp": timestamp,
  930. "extension": "config.vwf.json",
  931. "jsonState": jsonConfig
  932. };
  933. //let objName = loadInfo[ 'save_name' ] +'/'+ "savestate_" + loadInfo[ 'save_revision' ];
  934. // "savestate_" + loadInfo[ 'save_revision' ] + '/' + loadInfo[ 'save_name' ] + '_vwf_json'
  935. // let configName = 'savestate_/' + root + '/' + filename + '_config_vwf_json';
  936. // let documentSaveConfigState = _LCSUSER.get(configName).put(configStateForStore);
  937. // //documents.path(root).set(documentSaveConfigState);
  938. // let configNameRev = 'savestate_' + saveRevision.toString() + '/' + root + '/' + filename + '_config_vwf_json';
  939. // _LCSUSER.get(configNameRev).put(configStateForStore);
  940. // _LCSUSER.get(configNameRev).path("revision").put(saveRevision);
  941. //documentSaveConfigState.path('revs').set(documentSaveStateRevision);
  942. // Save config file to server
  943. // var xhrConfig = new XMLHttpRequest();
  944. // xhrConfig.open("POST", "/" + root + "/save/" + filename, true);
  945. // xhrConfig.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  946. // xhrConfig.send("root=" + root + "/" + filename + "&filename=saveState&inst=" + inst + "&timestamp=" + timestamp + "&extension=.vwf.config.json" + "&jsonState=" + jsonConfig);
  947. }
  948. // LoadSavedState
  949. async loadSavedState(filename, applicationpath, revision) {
  950. console.log("Loading: " + filename);
  951. let userName = await _LCS_WORLD_USER.get('alias').once().then();
  952. if (revision) {
  953. window.location.pathname = '/' + userName + applicationpath + '/load/' + filename + '/' + revision + '/';
  954. }
  955. else { // applicationpath + "/" + inst + '/load/' + filename + '/';
  956. window.location.pathname = '/' + userName + applicationpath + '/load/' + filename + '/';
  957. }
  958. }
  959. hideUIControl() {
  960. var el = document.getElementById("ui-controls");
  961. if (el) {
  962. el.classList.remove("visible");
  963. el.classList.add("not-visible");
  964. }
  965. }
  966. showUIControl() {
  967. var el = document.getElementById("ui-controls");
  968. if (el) {
  969. el.classList.remove("not-visible");
  970. el.classList.add("visible");
  971. }
  972. }
  973. hideProgressBar() {
  974. var progressbar = document.getElementById("load-progressbar");
  975. if (progressbar) {
  976. progressbar.classList.remove("visible");
  977. progressbar.classList.add("not-visible");
  978. progressbar.classList.add("mdc-linear-progress--closed");
  979. }
  980. }
  981. showProgressBar() {
  982. let progressbar = document.getElementById("load-progressbar");
  983. if (progressbar) {
  984. progressbar.classList.add("visible");
  985. progressbar.classList.add("mdc-linear-progress--indeterminate");
  986. }
  987. }
  988. }
  989. export { App }