app.js 37 KB

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