app.js 38 KB

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