app.js 40 KB

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