app.js 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909
  1. /*
  2. The MIT License (MIT)
  3. Copyright (c) 2014-2018 Nikolai Suslov and the Krestianstvo.org project contributors. (https://github.com/NikolaySuslov/livecodingspace/blob/master/LICENSE.md)
  4. Virtual World Framework Apache 2.0 license (https://github.com/NikolaySuslov/livecodingspace/blob/master/licenses/LICENSE_VWF.md)
  5. */
  6. import page from '/lib/page.mjs';
  7. import { Lang } from '/lib/polyglot/language.js';
  8. import { Helpers } from '/helpers.js';
  9. import { IndexApp } from '/web/index-app.js';
  10. import { WorldApp } from '/web/world-app.js';
  11. import { Widgets } from '/lib/widgets.js';
  12. class App {
  13. constructor() {
  14. console.log("app constructor");
  15. this.widgets = new Widgets;
  16. //globals
  17. window._app = this;
  18. window._cellWidgets = this.widgets;
  19. window._LangManager = new Lang;
  20. window._noty = new Noty;
  21. _LangManager.setLanguage().then(res => {
  22. return this.initDB()
  23. }).then(res => {
  24. this.helpers = new Helpers;
  25. this.initUser();
  26. //client routes
  27. page('/', this.HandleIndex);
  28. page('/setup', this.HandleSetupIndex);
  29. page('/settings', this.HandleSettingsIndex);
  30. page('/profile', this.HandleUserIndex);
  31. page('/worlds', this.HandleIndex);
  32. page('/:user/worlds', this.HandleUserWorlds);
  33. page('/:user/worlds/:type', this.HandleUserWorldsWithType);
  34. page('/:user/:type/:name/edit/:file', this.HandleFileEdit);
  35. page('/:user/:space', this.HandleParsableRequestGenID);
  36. page('/:user/:space/about', this.HandleWorldAbout);
  37. page('/:user/:space/:id', this.HandleParsableRequestWithID);
  38. page('/:user/:space/index.vwf/:id', this.HandleParsableRequestWithID);
  39. page('/:user/:space/load/:savename', this.HandleParsableLoadRequest);
  40. page('/:user/:space/load/:savename/about', this.HandleWorldAbout);
  41. page('/:user/:space/:id/load/:savename', this.HandleParsableRequestWithID);
  42. page('/:user/:space/load/:savename/:rev', this.HandleParsableLoadRequestWithRev);
  43. page('/:user/:space/:id/load/:savename/:rev', this.HandleParsableRequestWithID);
  44. page('*', this.HandleNoPage);
  45. page();
  46. })
  47. }
  48. initDB() {
  49. var config = JSON.parse(localStorage.getItem('lcs_config'));
  50. if (!config) {
  51. config = {
  52. 'dbhost': 'https://' + window.location.hostname + ':8080/gun', //'http://localhost:8080/gun',
  53. 'reflector': 'https://' + window.location.hostname + ':3002',
  54. 'language': 'en'
  55. }
  56. localStorage.setItem('lcs_config', JSON.stringify(config));
  57. }
  58. const dbConnection = new Promise((resolve, reject) => {
  59. this.db = Gun(this.dbHost);
  60. this.user = this.db.user();
  61. window._LCSDB = this.db;
  62. window._LCSUSER = this.user;
  63. window._LCS_SYS_USER = undefined;
  64. window._LCS_WORLD_USER = undefined;
  65. _LCSDB.get('lcs/app').get('pub').once(res => {
  66. if (res) {
  67. window._LCS_SYS_USER = this.db.user(res);
  68. }
  69. });
  70. _LCSDB.on('hi', function (peer) {
  71. let msg = 'Connected to ' + peer.url;
  72. let noty = new Noty({
  73. text: msg,
  74. timeout: 2000,
  75. theme: 'mint',
  76. layout: 'bottomRight',
  77. type: 'success'
  78. });
  79. noty.show();
  80. console.log(msg)
  81. })
  82. _LCSDB.on('bye', function (peer) {
  83. let msg = 'No connection to ' + peer.url;
  84. let noty = new Noty({
  85. text: msg,
  86. timeout: 1000,
  87. theme: 'mint',
  88. layout: 'bottomRight',
  89. type: 'error'
  90. });
  91. noty.show();
  92. console.log(msg)
  93. })
  94. resolve('ok');
  95. });
  96. return dbConnection
  97. }
  98. initUser() {
  99. _LCSUSER.recall({ sessionStorage: 1 });
  100. }
  101. get reflectorHost() {
  102. var res = "";
  103. let config = localStorage.getItem('lcs_config');
  104. if (config) {
  105. res = JSON.parse(config).reflector;
  106. }
  107. return res;
  108. }
  109. get dbHost() {
  110. var res = "";
  111. let config = localStorage.getItem('lcs_config');
  112. if (config) {
  113. res = JSON.parse(config).dbhost;
  114. }
  115. return res;
  116. }
  117. async loadProxyDefaults() {
  118. //load to DB default proxy files (VWF & A-Frame components)
  119. let proxyResponse = await fetch('/proxy-files', { method: 'get' });
  120. let proxyFiles = await proxyResponse.json();
  121. let filterProxyFiles = proxyFiles.filter(el => (el !== null));
  122. console.log(filterProxyFiles);
  123. var origin = window.location.origin;
  124. //var userPub = _LCSUSER.is.pub;
  125. let proxyObj = {};
  126. for (var index in filterProxyFiles) {
  127. let doc = filterProxyFiles[index];
  128. if (doc) {
  129. var url = origin + doc;
  130. var entryName = url.replace(origin + '/defaults/', "").split(".").join("_");
  131. let proxyFile = await fetch(url, { method: 'get' });
  132. let responseText = await proxyFile.text();
  133. if (responseText) {
  134. let created = new Date().valueOf();
  135. let obj = {
  136. //'owner': userPub,
  137. 'file': responseText,
  138. 'modified': created,
  139. 'created': created
  140. }
  141. proxyObj[entryName] = obj;
  142. }
  143. }
  144. }
  145. console.log(proxyObj);
  146. Object.keys(proxyObj).forEach(res => {
  147. _LCSDB.user().get('proxy').get(res).put(proxyObj[res]);
  148. })
  149. }
  150. async loadWorldsDefaults(replace) {
  151. //load to DB default worlds
  152. let worldsResponse = await fetch('/world-files', { method: 'get' });
  153. let worldFiles = await worldsResponse.json();
  154. let filterworldFiles = worldFiles.filter(el => (el !== null));
  155. console.log(filterworldFiles);
  156. let worldsObj = {};
  157. for (var index in filterworldFiles) {
  158. let doc = filterworldFiles[index];
  159. if (doc) {
  160. let url = window.location.origin + doc;
  161. var entryName = url.replace(window.location.origin + '/defaults/worlds/', "").split(".").join("_");
  162. let worldName = entryName.split("/")[0];
  163. let userPub = _LCSUSER.is.pub;
  164. let worldFile = await fetch(url, { method: 'get' });
  165. let worldSource = await worldFile.text();
  166. if (worldSource) {
  167. //let modified = new Date().valueOf();
  168. let created = new Date().valueOf();
  169. let obj = {
  170. 'file': worldSource,
  171. 'modified': created,
  172. 'created': created
  173. }
  174. if (!worldsObj[worldName]) {
  175. worldsObj[worldName] = {
  176. 'parent': '-',
  177. 'owner': userPub,
  178. 'featured': true,
  179. 'published': true
  180. }
  181. }
  182. let entry = entryName.replace(worldName + '/', "");
  183. worldsObj[worldName][entry] = obj;
  184. }
  185. }
  186. }
  187. console.log(worldsObj);
  188. if (replace) {
  189. Object.entries(worldsObj).forEach(res => {
  190. let worldName = res[0];
  191. let files = res[1];
  192. Object.entries(files).forEach(file => {
  193. _LCSDB.user().get('worlds').get(worldName).get(file[0]).put(file[1]);
  194. })
  195. })
  196. } else {
  197. //force replace all default worlds
  198. Object.entries(worldsObj).forEach(res => {
  199. let worldName = res[0];
  200. let files = res[1];
  201. Object.entries(files).forEach(file => {
  202. _LCSDB.user().get('worlds').get(worldName).get(file[0]).not(res => {
  203. _LCSDB.user().get('worlds').get(worldName).get(file[0]).put(file[1]);
  204. })
  205. })
  206. })
  207. }
  208. }
  209. async loadEmptyDefaultProto() {
  210. //empty proto world
  211. let userPub = _LCSUSER.is.pub;
  212. let worldsObj = {};
  213. let emptyWorld = {
  214. "index_vwf_yaml": YAML.stringify(
  215. {
  216. "extends": "http://vwf.example.com/aframe/ascene.vwf"
  217. }, 4),
  218. "index_vwf_config_yaml": YAML.stringify(
  219. {
  220. "info": {
  221. "title": "Empty World"
  222. },
  223. "model": {
  224. "vwf/model/aframe": null
  225. },
  226. "view": {
  227. "vwf/view/aframe": null,
  228. "vwf/view/editor-new": null
  229. }
  230. }, 4),
  231. "assets_json": JSON.stringify({}),
  232. "index_vwf_html": JSON.stringify("<!-- DEFAULT HTML -->"),
  233. "appui_js": JSON.stringify("//appui in JS"),
  234. "info_json": JSON.stringify({
  235. "info": {
  236. "en": {
  237. "title": "Empty World",
  238. "imgUrl": "",
  239. "text": "Empty World"
  240. },
  241. "ru": {
  242. "title": "Новый Мир",
  243. "imgUrl": "",
  244. "text": "Новый Мир"
  245. }
  246. }
  247. }, null, 4)
  248. }
  249. worldsObj['empty'] = {
  250. 'parent': '-',
  251. 'owner': userPub,
  252. 'featured': true,
  253. 'published': true
  254. }
  255. Object.keys(emptyWorld).forEach(el => {
  256. //let modified = new Date().valueOf();
  257. let created = new Date().valueOf();
  258. let obj = {
  259. 'file': emptyWorld[el],
  260. 'modified': created,
  261. 'created': created
  262. }
  263. worldsObj['empty'][el] = obj;
  264. })
  265. console.log(worldsObj);
  266. Object.entries(worldsObj).forEach(el => {
  267. let worldName = el[0];
  268. let files = el[1];
  269. Object.entries(files).forEach(file => {
  270. _LCSDB.user().get('worlds').get(worldName).get(file[0]).put(file[1]);
  271. })
  272. })
  273. }
  274. //load defaults for first registered user running ./setup
  275. HandleSettingsIndex() {
  276. window._app.hideProgressBar();
  277. window._app.hideUIControl();
  278. let el = document.createElement("div");
  279. el.setAttribute("id", "appGUI");
  280. document.body.appendChild(el);
  281. _cellWidgets.reflectorGUI();
  282. }
  283. async HandleWorldAbout(ctx) {
  284. console.log("about world");
  285. let userAlias = ctx.params.user;
  286. let worldName = ctx.params.space;
  287. let saveName = ctx.params.savename;
  288. window._app.hideProgressBar();
  289. window._app.hideUIControl();
  290. if (!_app.indexApp) {
  291. _app.indexApp = new IndexApp;
  292. _app.indexApp.initHTML();
  293. _app.indexApp.initApp();
  294. }
  295. let worldApp = new WorldApp(userAlias, worldName, saveName);
  296. await worldApp.initWorldGUI();
  297. }
  298. HandleSetupIndex() {
  299. window._app.hideProgressBar();
  300. window._app.hideUIControl();
  301. let el = document.createElement("div");
  302. el.setAttribute("id", "admin");
  303. document.body.appendChild(el);
  304. _LCSDB.on('auth',
  305. async function (ack) {
  306. if (_LCSUSER.is) {
  307. let setPubKey = {
  308. $cell: true,
  309. $components: [
  310. {
  311. $type: "p",
  312. class: "mdc-typography--headline5",
  313. $text: "1. Set app system user PUB key"
  314. },
  315. {
  316. $type: "button",
  317. class: "mdc-button mdc-button--raised",
  318. $text: "Set app PUB key",
  319. onclick: function (e) {
  320. console.log("admin action");
  321. _LCSDB.get('lcs/app').get('pub').put(_LCSUSER.is.pub);
  322. }
  323. }
  324. ]
  325. }
  326. let adminComponents = [];
  327. let defaultPub = await _LCSDB.get('lcs/app').get('pub').once().then();
  328. if (!defaultPub) {
  329. adminComponents.push(setPubKey);
  330. }
  331. if (_LCSUSER.is.pub == defaultPub) {
  332. let loadEmpty = {
  333. $cell: true,
  334. $components: [
  335. {
  336. $type: "p",
  337. class: "mdc-typography--headline5",
  338. $text: "3. Initialize empty World proto"
  339. },
  340. {
  341. $type: "button",
  342. id: "loadDefaults",
  343. class: "mdc-button mdc-button--raised",
  344. $text: "Init empty world",
  345. onclick: function (e) {
  346. console.log("admin action");
  347. window._app.loadEmptyDefaultProto();
  348. }
  349. }
  350. ]
  351. }
  352. let loadDefaults = {
  353. $cell: true,
  354. _replaceSwitch: null,
  355. $components: [
  356. {
  357. $type: "p",
  358. class: "mdc-typography--headline5",
  359. $text: "4. Load Sample Worlds protos from server (optional)"
  360. },
  361. {
  362. $type: "button",
  363. id: "loadDefaults",
  364. class: "mdc-button mdc-button--raised",
  365. $text: "Load default worlds (from server)",
  366. onclick: function (e) {
  367. console.log("admin action");
  368. let forceReplace = this._replaceSwitch.checked;
  369. //console.log(forceReplace);
  370. window._app.loadWorldsDefaults(forceReplace);
  371. }
  372. },
  373. {
  374. $type: 'p'
  375. },
  376. _cellWidgets.switch({
  377. 'id': 'forceReplace',
  378. 'init': function () {
  379. this._switch = new mdc.switchControl.MDCSwitch(this);
  380. this._replaceSwitch = this._switch;
  381. this._switch.checked = false;
  382. }
  383. }
  384. ),
  385. {
  386. $type: 'label',
  387. for: 'input-forceReplace',
  388. $text: 'Force replace'
  389. }
  390. ]
  391. }
  392. let loadDefaultsProxy = {
  393. $cell: true,
  394. $components: [
  395. {
  396. $type: "p",
  397. class: "mdc-typography--headline5",
  398. $text: "3. Load VWF & A-Frame default components"
  399. },
  400. {
  401. $type: "button",
  402. class: "mdc-button mdc-button--raised",
  403. $text: "Load defaults Proxy",
  404. onclick: function (e) {
  405. console.log("admin action");
  406. window._app.loadProxyDefaults();
  407. }
  408. }
  409. ]
  410. }
  411. adminComponents.push(setPubKey, loadDefaultsProxy, loadEmpty, loadDefaults);
  412. }
  413. document.querySelector("#admin").$cell({
  414. $cell: true,
  415. id: 'adminComponents',
  416. $type: "div",
  417. $components: adminComponents
  418. });
  419. }
  420. })
  421. }
  422. //TODO: profile
  423. HandleUserIndex(ctx) {
  424. console.log("USER INDEX");
  425. window._app.hideProgressBar();
  426. window._app.hideUIControl();
  427. _LCSDB.on('auth',
  428. async function (ack) {
  429. if (ack.pub) {
  430. document.querySelector("#profile")._status = "User: " + _LCSUSER.is.alias //+' pub: ' + _LCSUSER.is.pub;
  431. document.querySelector("#profile").$update();
  432. }
  433. })
  434. let el = document.createElement("div");
  435. el.setAttribute("id", "userProfile");
  436. document.body.appendChild(el);
  437. let userProfile = {
  438. $type: 'div',
  439. id: "profile",
  440. _status: "",
  441. $init: function () {
  442. this._status = "user is not signed in..."
  443. },
  444. $update: function () {
  445. this.$components = [
  446. {
  447. $type: "h1",
  448. class: "mdc-typography--headline4",
  449. $text: this._status //"Profile for: " + _LCSUSER.is.alias
  450. }
  451. ]
  452. }
  453. }
  454. document.querySelector("#userProfile").$cell({
  455. $cell: true,
  456. $type: "div",
  457. $components: [userProfile]
  458. })
  459. }
  460. async HandleUserWorlds(ctx) {
  461. console.log("USER WORLDS INDEX");
  462. console.log(ctx.params);
  463. let user = ctx.params.user;
  464. page.redirect('/' + user + '/worlds/protos');
  465. }
  466. async HandleFileEdit(ctx) {
  467. console.log("USER WORLD FILE EDIT");
  468. let user = ctx.params.user;
  469. let worldName = ctx.params.name;
  470. let fileOriginal = ctx.params.file;
  471. let type = ctx.params.type;
  472. window._app.hideProgressBar();
  473. window._app.hideUIControl();
  474. _LCSDB.on('auth',
  475. async function (ack) {
  476. if (_LCSUSER.is) {
  477. if (_LCSUSER.is.alias == user) {
  478. var worldType = 'worlds';
  479. var file = fileOriginal;
  480. if (type == 'state') {
  481. worldType = 'documents';
  482. file = _app.helpers.replaceSubStringALL(fileOriginal, "~", '/');
  483. }
  484. let worldFile = await _LCSUSER.get(worldType).get(worldName).get(file).once().then();
  485. if (worldFile) {
  486. console.log(worldFile.file);
  487. let el = document.createElement("div");
  488. el.setAttribute("id", "worldFILE");
  489. document.body.appendChild(el);
  490. let aceEditorCell = {
  491. $type: "div",
  492. $components: [
  493. {
  494. class: "aceEditor",
  495. id: "aceEditor",
  496. //style: "width:1200px; height: 800px",
  497. $type: "div",
  498. $text: worldFile.file,
  499. $init: function () {
  500. var mode = "ace/mode/json";
  501. if (file.includes('_yaml'))
  502. mode = "ace/mode/yaml"
  503. if (file.includes('_js'))
  504. mode = "ace/mode/javascript"
  505. var editor = ace.edit("aceEditor");
  506. editor.setTheme("ace/theme/monokai");
  507. editor.setFontSize(16);
  508. editor.getSession().setMode(mode);
  509. editor.setOptions({
  510. maxLines: Infinity
  511. });
  512. }
  513. },
  514. {
  515. $type: "button",
  516. class: "mdc-button mdc-button--raised",
  517. $text: "Save",
  518. onclick: async function (e) {
  519. console.log("save new info");
  520. let editor = document.querySelector("#aceEditor").env.editor;
  521. let newInfo = editor.getValue();
  522. _LCSUSER.get(worldType).get(worldName).get(file).get('file').put(newInfo, res => {
  523. if (res) {
  524. let modified = new Date().valueOf();
  525. _LCSUSER.get(worldType).get(worldName).get(file).get('modified').put(modified);
  526. }
  527. })
  528. }
  529. },
  530. {
  531. $type: "button",
  532. class: "mdc-button mdc-button--raised",
  533. $text: "Close",
  534. onclick: function (e) {
  535. console.log("close");
  536. window.history.back();
  537. // if (type == "proto")
  538. // window.location.pathname = "/" + user + '/' + worldName + '/about'
  539. // if (type == "state")
  540. // window.location.pathname = "/" + user + '/' + worldName + '/about'
  541. }
  542. }
  543. ]
  544. }
  545. document.querySelector("#worldFILE").$cell({
  546. $cell: true,
  547. $type: "div",
  548. $components: [aceEditorCell
  549. ]
  550. })
  551. }
  552. }
  553. }
  554. })
  555. }
  556. async HandleUserWorldsWithType(ctx) {
  557. console.log("USER WORLDS INDEX");
  558. console.log(ctx.params);
  559. let user = ctx.params.user;
  560. let type = ctx.params.type;
  561. window._app.hideProgressBar();
  562. window._app.hideUIControl();
  563. if (!_app.indexApp) {
  564. _app.indexApp = new IndexApp;
  565. _app.indexApp.initHTML();
  566. _app.indexApp.initApp();
  567. }
  568. if (type == 'protos') {
  569. await _app.indexApp.initWorldsProtosListForUser(user)//.getWorldsProtosListForUser(user);
  570. } else if (type == 'states') {
  571. await _app.indexApp.initWorldsStatesListForUser(user);
  572. //await _app.indexApp.getWorldsFromUserDB(user);
  573. }
  574. }
  575. async HandleIndex() {
  576. console.log("INDEX");
  577. window._app.hideProgressBar();
  578. window._app.hideUIControl();
  579. if (!_app.indexApp) {
  580. _app.indexApp = new IndexApp;
  581. await _app.indexApp.generateFrontPage();
  582. _app.indexApp.initHTML();
  583. }
  584. _app.indexApp.initApp();
  585. await _app.indexApp.initWorldsProtosListForUser('app');
  586. //await _app.indexApp.getAppDetailsFromDB();
  587. }
  588. HandleNoPage() {
  589. console.log("no such page")
  590. }
  591. //handle parcable requests
  592. HandleParsableLoadRequest(ctx) {
  593. let app = window._app;
  594. console.log(ctx.params);
  595. //var pathname = ctx.pathname;
  596. var spaceName = ctx.params.space;
  597. var saveName = ctx.params.savename;
  598. let user = ctx.params.user;
  599. page.redirect('/' + user + '/' + spaceName + '/' + app.helpers.GenerateInstanceID() + '/load/' + saveName);
  600. }
  601. HandleParsableLoadRequestWithRev(ctx) {
  602. let app = window._app;
  603. console.log(ctx.params);
  604. //var pathname = ctx.pathname;
  605. var spaceName = ctx.params.space;
  606. var saveName = ctx.params.savename;
  607. var rev = ctx.params.rev;
  608. let user = ctx.params.user;
  609. page.redirect('/' + user + '/' + spaceName + '/' + app.helpers.GenerateInstanceID() + '/load/' + saveName + '/' + rev);
  610. }
  611. async setUserPaths(user) {
  612. await _LCSDB.get('users').get(user).get('pub').once(res => {
  613. if (res)
  614. window._LCS_WORLD_USER = _LCSDB.user(res);
  615. }).then();
  616. }
  617. async HandleParsableRequestGenID(ctx) {
  618. let app = window._app;
  619. console.log(ctx.params);
  620. let user = ctx.params.user;
  621. var pathname = ctx.pathname;
  622. await app.setUserPaths(user);
  623. if (pathname[pathname.length - 1] == '/') {
  624. pathname = pathname.slice(0, -1)
  625. }
  626. let pathToParse = pathname.replace('/' + user, "");
  627. app.helpers.Process(pathToParse).then(parsedRequest => {
  628. localStorage.setItem('lcs_app', JSON.stringify({ path: parsedRequest }));
  629. console.log(parsedRequest);
  630. if ((parsedRequest['instance'] == undefined) && (parsedRequest['private_path'] == undefined) && (parsedRequest['public_path'] !== "/") && (parsedRequest['application'] !== undefined)) {
  631. page.redirect(pathname + '/' + app.helpers.GenerateInstanceID());
  632. }
  633. });
  634. }
  635. async HandleParsableRequestWithID(ctx) {
  636. let app = window._app;
  637. console.log(ctx.params);
  638. var pathname = ctx.pathname;
  639. let user = ctx.params.user;
  640. if (pathname[pathname.length - 1] == '/') {
  641. pathname = pathname.slice(0, -1)
  642. }
  643. await app.setUserPaths(user);
  644. let pathToParse = pathname.replace('/' + user, "");
  645. app.helpers.Process(pathToParse).then(async function (parsedRequest) {
  646. localStorage.setItem('lcs_app', JSON.stringify({ path: parsedRequest }));
  647. console.log(parsedRequest);
  648. var userLibraries = { model: {}, view: {} };
  649. var application;
  650. await vwf.loadConfiguration(application, userLibraries, compatibilityCheck);
  651. });
  652. }
  653. async HandleParsableRequest(ctx) {
  654. let app = window._app;
  655. console.log(ctx.params);
  656. var pathname = ctx.pathname;
  657. if (pathname[pathname.length - 1] == '/') {
  658. pathname = pathname.slice(0, -1)
  659. }
  660. var parsedRequest = await app.helpers.Process(pathname);
  661. localStorage.setItem('lcs_app', JSON.stringify({ path: parsedRequest }));
  662. console.log(parsedRequest);
  663. if ((parsedRequest['instance'] == undefined) && (parsedRequest['private_path'] == undefined) && (parsedRequest['public_path'] !== "/") && (parsedRequest['application'] !== undefined)) {
  664. // Redirect if the url request does not include an application/file && a default 'index.vwf.yaml' exists
  665. // page.redirect(pathname + '/' + app.helpers.GenerateInstanceID());
  666. window.location.pathname = pathname + '/' + app.helpers.GenerateInstanceID()
  667. //return true;
  668. } else {
  669. //return false;
  670. }
  671. var userLibraries = { model: {}, view: {} };
  672. var application;
  673. await vwf.loadConfiguration(application, userLibraries, compatibilityCheck);
  674. }
  675. //get DB application state information for reflector (called from VWF)
  676. async getApplicationState() {
  677. let dataJson = JSON.parse(localStorage.getItem('lcs_app'));
  678. if (dataJson) {
  679. if (!dataJson.path['instance']) return undefined;
  680. }
  681. let userAlias = await _LCS_WORLD_USER.get('alias').once().then();
  682. let userPub = await _LCSDB.get('users').get(userAlias).get('pub').once().then();
  683. let loadInfo = await this.getLoadInformation(dataJson);
  684. let saveInfo = await this.loadSaveObject(loadInfo);
  685. let loadObj = {
  686. loadInfo: loadInfo,
  687. path: dataJson.path,
  688. saveObject: saveInfo,
  689. user: userAlias
  690. }
  691. //dataJson.app = loadObj;
  692. localStorage.setItem('lcs_app', JSON.stringify(loadObj));
  693. console.log(loadObj);
  694. //temporary solution for syncing DB replicas using Gun.load()
  695. // _LCS_SYS_USER.get('proxy').load(res=>{
  696. // if (res)
  697. // {console.log('proxy loaded');
  698. // _LCSDB.user(userPub).get('worlds').get(loadObj.path.public_path.slice(1)).load(w=>{
  699. // if (w) {
  700. // console.log('world files loaded');
  701. // vwf.ready( vwf.application, loadObj)
  702. // }
  703. // }, {wait: 200});
  704. // }
  705. // }, {wait: 200});
  706. return loadObj
  707. }
  708. // LookupSaveRevisions takes the public path and the name of a save, and provides
  709. // an array of all revisions for that save. (If the save does not exist, this will be
  710. // an empty array).
  711. async lookupSaveRevisions(public_path, save_name) {
  712. var result = [];
  713. var states = [];
  714. let docName = 'savestate_/' + public_path + '/' + save_name + '_vwf_json';
  715. let revs = await _LCS_WORLD_USER.get('documents').get(public_path).get(docName).get('revs').once().then();
  716. if (revs) {
  717. for (const res of Object.keys(revs)) {
  718. if (res !== '_') {
  719. let el = await _LCS_WORLD_USER.get('documents').get(public_path).get(docName).get('revs').get(res).once().then();
  720. if (el)
  721. result.push(parseInt(el.revision));
  722. }
  723. }
  724. return result
  725. }
  726. }
  727. // GetLoadInformation receives a parsed request {private_path, public_path, instance, application} and returns the
  728. // details of the save that is designated by the initial request. The details are returned in an object
  729. // composed of: save_name (name of the save) save_revision (revision of the save), explicit_revision (boolean, true if the request
  730. // explicitly specified the revision, false if it did not), and application_path (the public_path of the application this is a save for).
  731. async getLoadInformation(response) {
  732. let parsedRequest = response.path;
  733. var result = { 'save_name': undefined, 'save_revision': undefined, 'explicit_revision': undefined, 'application_path': undefined };
  734. if (parsedRequest['private_path']) {
  735. var segments = this.helpers.GenerateSegments(parsedRequest['private_path']);
  736. if ((segments.length > 1) && (segments[0] == "load")) {
  737. var potentialRevisions = await this.lookupSaveRevisions((parsedRequest['public_path']).slice(1), segments[1]);
  738. console.log('!!!!! - ', potentialRevisions);
  739. if (potentialRevisions.length > 0) {
  740. result['save_name'] = segments[1];
  741. if (segments.length > 2) {
  742. var requestedRevision = parseInt(segments[2]);
  743. if (requestedRevision) {
  744. if (potentialRevisions.indexOf(requestedRevision) > -1) {
  745. result['save_revision'] = requestedRevision;
  746. result['explicit_revision'] = true;
  747. result['application_path'] = parsedRequest['public_path'];
  748. }
  749. }
  750. }
  751. if (result['explicit_revision'] == undefined) {
  752. result['explicit_revision'] = false;
  753. potentialRevisions.sort();
  754. result['save_revision'] = potentialRevisions.pop();
  755. result['application_path'] = parsedRequest['public_path'];
  756. }
  757. }
  758. }
  759. }
  760. return result;
  761. }
  762. async loadSaveObject(loadInfo) {
  763. //let objName = loadInfo[ 'save_name' ] +'/'+ "savestate_" + loadInfo[ 'save_revision' ];
  764. if (!loadInfo.save_name) {
  765. return undefined
  766. }
  767. let objName = "savestate_" + loadInfo['application_path'] + '/' + loadInfo['save_name'] + '_vwf_json';
  768. let objNameRev = "savestate_" + loadInfo['save_revision'] + loadInfo['application_path'] + '/' + loadInfo['save_name'] + '_vwf_json';
  769. // if(loadInfo[ 'save_revision' ]){
  770. // }
  771. let worldName = this.helpers.appPath //loadInfo[ 'application_path' ].slice(1);
  772. let saveObject = await _LCS_WORLD_USER.get('documents').get(worldName).get(objName).get('revs').get(objNameRev).once().then();
  773. let saveInfo = saveObject ? JSON.parse(saveObject.jsonState) : saveObject;
  774. return saveInfo;
  775. }
  776. // GetSaveInformation is a helper function that takes the application_path (/path/to/application).
  777. // It returns an array of all saves found for that
  778. // application (including separate entries for individual revisions of saves ).
  779. async getSaveInformation(application_path, userPUB) {
  780. var result = [];
  781. let user = _LCSDB.user(userPUB);
  782. var docName = application_path.slice(1);
  783. let potentialSaveNames = await user.get('documents').get(docName).once().then();
  784. if (potentialSaveNames) {
  785. for (const res of Object.keys(potentialSaveNames)) {
  786. if (res !== '_') {
  787. let el = await user.get('documents').path(docName).get(res).once().then();
  788. let revisionList = await this.lookupSaveRevisions(application_path.slice(1), el.filename);
  789. var latestsave = true;
  790. revisionList.sort();
  791. while (revisionList.length > 0) {
  792. var newEntry = {};
  793. newEntry['applicationpath'] = application_path;
  794. newEntry['savename'] = el.filename;
  795. newEntry['revision'] = revisionList.pop().toString();
  796. newEntry['latestsave'] = latestsave;
  797. if (latestsave) {
  798. newEntry['url'] = this.helpers.JoinPath(window.location.origin, application_path, "load", el.filename + "/");
  799. }
  800. else {
  801. newEntry['url'] = this.helpers.JoinPath(window.location.origin, application_path, "load", el.filename + "/", newEntry['revision'] + "/");
  802. }
  803. latestsave = false;
  804. result.push(newEntry);
  805. }
  806. }
  807. }
  808. }
  809. return result;
  810. }
  811. async getProtoWorldFiles(userPub, worldName, date) {
  812. let fileNamesAll = await _LCSDB.user(userPub).get('worlds').get(worldName).once().then();
  813. let worldFileNames = Object.keys(fileNamesAll).filter(el => (el !== '_') && (el !== 'owner') && (el !== 'parent') && (el !== 'featured') && (el !== 'published') && (el !== 'info_json'));
  814. let worldObj = {};
  815. for (var doc in worldFileNames) {
  816. let fn = worldFileNames[doc];
  817. let res = await _LCSDB.user(userPub).get('worlds').get(worldName).get(fn).once().then();
  818. var data = {
  819. 'file': res.file,
  820. 'modified': res.modified,
  821. 'created': res.created
  822. }
  823. if (!date) {
  824. data = {
  825. 'file': res.file
  826. }
  827. }
  828. worldObj[fn] = data;
  829. }
  830. console.log(worldObj);
  831. return worldObj
  832. }
  833. async cloneWorldPrototype(worldName, userName, newWorldName) {
  834. _app.showProgressBar();
  835. let userPub = await _LCSDB.get('users').get(userName).get('pub').once().then();
  836. //let worldProto = await _LCSDB.user(userPub).get('worlds').get(worldName).once().then();
  837. var worldID = window._app.helpers.GenerateInstanceID().toString();
  838. if (newWorldName) {
  839. worldID = newWorldName
  840. }
  841. //let modified = new Date().valueOf();
  842. console.log('clone: ' + worldName + 'to: ' + worldID);
  843. let newOwner = _LCSUSER.is.pub;
  844. let created = new Date().valueOf();
  845. let worldObj = {
  846. 'owner': newOwner,
  847. 'parent': userName + '/' + worldName,
  848. 'featured': true,
  849. 'published': true
  850. };
  851. let fileNamesAll = await _LCSDB.user(userPub).get('worlds').get(worldName).once().then();
  852. let worldFileNames = Object.keys(fileNamesAll).filter(el => (el !== '_') && (el !== 'owner') && (el !== 'parent') && (el !== 'featured') && (el !== 'published'));
  853. for (var doc in worldFileNames) {
  854. let fn = worldFileNames[doc];
  855. let res = await _LCSDB.user(userPub).get('worlds').get(worldName).get(fn).once().then();
  856. let data = {
  857. 'file': res.file,
  858. 'modified': created
  859. }
  860. worldObj[fn] = data;
  861. }
  862. console.log(worldObj);
  863. for (const obj of Object.keys(worldObj)) {
  864. await _LCSUSER.get('worlds').get(worldID).get(obj).put(worldObj[obj]).then();
  865. }
  866. _app.hideProgressBar();
  867. console.log('CLONED!!!');
  868. let appEl = document.createElement("div");
  869. appEl.setAttribute("id", 'cloneLink');
  870. let entry = document.querySelector('#worldActionsGUI');
  871. if (entry) {
  872. entry.appendChild(appEl);
  873. document.querySelector("#cloneLink").$cell({
  874. id: 'cloneLink',
  875. $cell: true,
  876. $type: "div",
  877. $components: [
  878. {
  879. $type: "a",
  880. class: "mdc-button mdc-button--raised mdc-card__action",
  881. $text: "Go to new cloned World!",
  882. onclick: function (e) {
  883. window.location.pathname = '/' + userName + '/' + worldID + '/about'
  884. }
  885. }
  886. ]
  887. })
  888. }
  889. //window.location.pathname = '/' + userName + '/' + worldID + '/about'
  890. //page()
  891. // Object.keys(worldObj).forEach(el => {
  892. // _LCSUSER.get('worlds').get(worldID).get(el).put(worldObj[el]);
  893. // })
  894. }
  895. async cloneWorldState(filename) {
  896. let myWorldProtos = await _LCSUSER.get('worlds').once().then();
  897. let userName = this.helpers.worldUser;
  898. let userPub = await _LCSDB.get('users').get(userName).get('pub').once().then();
  899. let protoUserRoot = this.helpers.getRoot(true).root;
  900. //let myName = _LCSUSER.is.alias;
  901. //let proto = Object.keys(myWorldProtos).filter(el => el == protoUserRoot);
  902. var protosKeys = [];
  903. if (myWorldProtos)
  904. protosKeys = Object.keys(myWorldProtos);
  905. if (protosKeys.includes(protoUserRoot)) {
  906. let userProtoFiles = await this.getProtoWorldFiles(userPub, protoUserRoot);
  907. let myProtoFiles = await this.getProtoWorldFiles(_LCSUSER.is.pub, protoUserRoot);
  908. let hashUP = await this.helpers.sha256(JSON.stringify(userProtoFiles));
  909. let hashMP = await this.helpers.sha256(JSON.stringify(myProtoFiles));
  910. if (hashUP == hashMP) {
  911. this.saveStateAsFile(filename);
  912. } else {
  913. let noty = new Noty({
  914. text: 'world prototype is modified.. could not clone world state',
  915. timeout: 2000,
  916. theme: 'mint',
  917. layout: 'bottomRight',
  918. type: 'error'
  919. });
  920. noty.show();
  921. }
  922. } else {
  923. await this.cloneWorldPrototype(protoUserRoot, userName, protoUserRoot);
  924. this.saveStateAsFile(filename);
  925. }
  926. }
  927. //TODO: refactor and config save
  928. saveStateAsFile(filename, otherProto) // invoke with the view as "this"
  929. {
  930. console.log("Saving: " + filename);
  931. //var clients = this.nodes["http://vwf.example.com/clients.vwf"];
  932. // Save State Information
  933. var state = vwf.getState();
  934. state.nodes[0].children = {};
  935. var timestamp = state["queue"].time;
  936. timestamp = Math.round(timestamp * 1000);
  937. var objectIsTypedArray = function (candidate) {
  938. var typedArrayTypes = [
  939. Int8Array,
  940. Uint8Array,
  941. // Uint8ClampedArray,
  942. Int16Array,
  943. Uint16Array,
  944. Int32Array,
  945. Uint32Array,
  946. Float32Array,
  947. Float64Array
  948. ];
  949. var isTypedArray = false;
  950. if (typeof candidate == "object" && candidate != null) {
  951. typedArrayTypes.forEach(function (typedArrayType) {
  952. isTypedArray = isTypedArray || candidate instanceof typedArrayType;
  953. });
  954. }
  955. return isTypedArray;
  956. };
  957. var transitTransformation = function (object) {
  958. return objectIsTypedArray(object) ?
  959. Array.prototype.slice.call(object) : object;
  960. };
  961. let jsonValuePure = require("vwf/utility").transform(
  962. state, transitTransformation
  963. );
  964. //remove all Ohm generated grammarsfrom state
  965. let jsonValue = _app.helpers.removeGrammarObj(jsonValuePure);
  966. var jsonState = JSON.stringify(jsonValue);
  967. let rootPath = this.helpers.getRoot(true);
  968. var inst = rootPath.inst;
  969. if (filename == '') filename = inst;
  970. //if (root.indexOf('.vwf') != -1) root = root.substring(0, root.lastIndexOf('/'));
  971. var root = rootPath.root;
  972. var json = jsonState;
  973. if (otherProto) {
  974. console.log('need to modify state...');
  975. json = this.helpers.replaceSubStringALL(jsonState, '/' + root + '/', '/' + otherProto + '/');//jsonState.replace(('/' + root + '/'), ('/' + otherProto +'/') );
  976. root = otherProto;
  977. console.log(json);
  978. }
  979. //var documents = _LCSUSER.get('documents');
  980. var saveRevision = new Date().valueOf();
  981. var stateForStore = {
  982. "root": root,
  983. "filename": filename,
  984. "inst": inst,
  985. "timestamp": timestamp,
  986. "extension": ".vwf.json",
  987. "jsonState": json,
  988. "publish": true
  989. };
  990. //let objName = loadInfo[ 'save_name' ] +'/'+ "savestate_" + loadInfo[ 'save_revision' ];
  991. // "savestate_" + loadInfo[ 'save_revision' ] + '/' + loadInfo[ 'save_name' ] + '_vwf_json'
  992. var docName = 'savestate_/' + root + '/' + filename + '_vwf_json';
  993. _LCSUSER.get('documents').get(root).get(docName).put(stateForStore, res => {
  994. if (res) {
  995. let noty = new Noty({
  996. text: 'Saved to ' + docName,
  997. timeout: 2000,
  998. theme: 'mint',
  999. layout: 'bottomRight',
  1000. type: 'success'
  1001. });
  1002. noty.show();
  1003. }
  1004. });
  1005. _LCSUSER.get('worlds').get(root).get('info_json').once(res => {
  1006. if (res) {
  1007. let modified = saveRevision;
  1008. let newOwner = _LCSUSER.is.pub;
  1009. let userName = _LCSUSER.is.alias;
  1010. let obj = {
  1011. 'parent': userName + '/' + root,
  1012. 'owner': newOwner,
  1013. 'file': res.file,
  1014. //'modified': modified,
  1015. 'created': modified
  1016. }
  1017. let docInfoName = 'savestate_/' + root + '/' + filename + '_info_vwf_json';
  1018. _LCSUSER.get('documents').get(root).get(docInfoName).not(res => {
  1019. _LCSUSER.get('documents').get(root).get(docInfoName).put(obj);
  1020. });
  1021. _LCSUSER.get('documents').get(root).get(docInfoName).get('created').not(res => {
  1022. _LCSUSER.get('documents').get(root).get(docInfoName).get('created').put(modified);
  1023. });
  1024. _LCSUSER.get('documents').get(root).get(docInfoName).get('modified').put(modified);
  1025. }
  1026. });
  1027. var docNameRev = 'savestate_' + saveRevision.toString() + '/' + root + '/' + filename + '_vwf_json';
  1028. _LCSUSER.get('documents').get(root).get(docName).get('revs').get(docNameRev).put(stateForStore)
  1029. .path("revision").put(saveRevision);
  1030. // Save Config Information
  1031. var config = { "info": {}, "model": {}, "view": {} };
  1032. // Save browser title
  1033. config["info"]["title"] = document.title//$('title').html();
  1034. // Save model drivers
  1035. Object.keys(vwf_view.kernel.kernel.models).forEach(function (modelDriver) {
  1036. if (modelDriver.indexOf('vwf/model/') != -1) config["model"][modelDriver] = "";
  1037. });
  1038. // If neither glge or threejs model drivers are defined, specify nodriver
  1039. if (config["model"]["vwf/model/glge"] === undefined && config["model"]["vwf/model/threejs"] === undefined) config["model"]["nodriver"] = "";
  1040. // Save view drivers and associated parameters, if any
  1041. Object.keys(vwf_view.kernel.kernel.views).forEach(function (viewDriver) {
  1042. if (viewDriver.indexOf('vwf/view/') != -1) {
  1043. if (vwf_view.kernel.kernel.views[viewDriver].parameters) {
  1044. config["view"][viewDriver] = vwf_view.kernel.kernel.views[viewDriver].parameters;
  1045. }
  1046. else config["view"][viewDriver] = "";
  1047. }
  1048. });
  1049. //var jsonConfig = $.encoder.encodeForURL(JSON.stringify(config));
  1050. var jsonConfig = JSON.stringify(config);
  1051. let configStateForStore = {
  1052. "root": root,
  1053. "filename": filename,
  1054. "inst": inst,
  1055. "timestamp": timestamp,
  1056. "extension": "config.vwf.json",
  1057. "jsonState": jsonConfig
  1058. };
  1059. //let objName = loadInfo[ 'save_name' ] +'/'+ "savestate_" + loadInfo[ 'save_revision' ];
  1060. // "savestate_" + loadInfo[ 'save_revision' ] + '/' + loadInfo[ 'save_name' ] + '_vwf_json'
  1061. // let configName = 'savestate_/' + root + '/' + filename + '_config_vwf_json';
  1062. // let documentSaveConfigState = _LCSUSER.get(configName).put(configStateForStore);
  1063. // //documents.path(root).set(documentSaveConfigState);
  1064. // let configNameRev = 'savestate_' + saveRevision.toString() + '/' + root + '/' + filename + '_config_vwf_json';
  1065. // _LCSUSER.get(configNameRev).put(configStateForStore);
  1066. // _LCSUSER.get(configNameRev).path("revision").put(saveRevision);
  1067. //documentSaveConfigState.path('revs').set(documentSaveStateRevision);
  1068. // Save config file to server
  1069. // var xhrConfig = new XMLHttpRequest();
  1070. // xhrConfig.open("POST", "/" + root + "/save/" + filename, true);
  1071. // xhrConfig.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  1072. // xhrConfig.send("root=" + root + "/" + filename + "&filename=saveState&inst=" + inst + "&timestamp=" + timestamp + "&extension=.vwf.config.json" + "&jsonState=" + jsonConfig);
  1073. }
  1074. // LoadSavedState
  1075. async loadSavedState(filename, applicationpath, revision) {
  1076. console.log("Loading: " + filename);
  1077. let userName = await _LCS_WORLD_USER.get('alias').once().then();
  1078. if (revision) {
  1079. window.location.pathname = '/' + userName + applicationpath + '/load/' + filename + '/' + revision + '/';
  1080. }
  1081. else { // applicationpath + "/" + inst + '/load/' + filename + '/';
  1082. window.location.pathname = '/' + userName + applicationpath + '/load/' + filename + '/';
  1083. }
  1084. }
  1085. hideUIControl() {
  1086. let el = document.getElementById("ui-controls");
  1087. if (el) {
  1088. el.classList.remove("visible");
  1089. el.classList.add("not-visible");
  1090. }
  1091. }
  1092. showUIControl() {
  1093. let el = document.getElementById("ui-controls");
  1094. if (el) {
  1095. el.classList.remove("not-visible");
  1096. el.classList.add("visible");
  1097. }
  1098. }
  1099. hideProgressBar() {
  1100. var progressbar = document.getElementById("load-progressbar");
  1101. if (progressbar) {
  1102. progressbar.classList.remove("visible");
  1103. progressbar.classList.remove("mdc-linear-progress--indeterminate");
  1104. progressbar.classList.add("not-visible");
  1105. progressbar.classList.add("mdc-linear-progress--closed");
  1106. }
  1107. }
  1108. showProgressBar() {
  1109. let progressbar = document.getElementById("load-progressbar");
  1110. if (progressbar) {
  1111. progressbar.classList.remove("not-visible");
  1112. progressbar.classList.remove("mdc-linear-progress--closed");
  1113. progressbar.classList.add("visible");
  1114. progressbar.classList.add("mdc-linear-progress--indeterminate");
  1115. }
  1116. }
  1117. // SUPPORT of DELETE USER WORLDS & SAVE STATES (experimental)
  1118. // TODO: manual garbage collection
  1119. async deleteWorldState(worldName, indexState) {
  1120. let revs = await _LCSUSER.get('documents').get(worldName).get(indexState).get('revs').once().then();
  1121. if (revs) {
  1122. for (const el of Object.keys(revs)) {
  1123. if (el !== '_') {
  1124. let doc = await _LCSUSER.get('documents').get(worldName).get(indexState).get('revs').get(el).once().then();
  1125. for (const rev of Object.keys(doc)) {
  1126. if (rev !== '_') {
  1127. await _LCSUSER.get('documents').get(worldName).get(indexState).get('revs').get(el).get(rev).put(null).then();
  1128. }
  1129. }
  1130. await _LCSUSER.get('documents').get(worldName).get(indexState).get('revs').get(el).put(null).then();
  1131. }
  1132. }
  1133. }
  1134. // clear all state params
  1135. let stateDoc = await _LCSUSER.get('documents').get(worldName).get(indexState).once().then();
  1136. for (const state of Object.keys(stateDoc)) {
  1137. if (state !== '_' && state !== 'revs') {
  1138. await _LCSUSER.get('documents').get(worldName).get(indexState).get(state).put(null).then();
  1139. }
  1140. }
  1141. await _LCSUSER.get('documents').get(worldName).get(indexState).get('revs').put(null).then();
  1142. await _LCSUSER.get('documents').get(worldName).get(indexState).put(null).then();
  1143. }
  1144. async deleteWorld(name, type) {
  1145. if (type == 'proto') {
  1146. let worldName = name;
  1147. //TODO check for states (ask for deleting all states first...)
  1148. //delete states
  1149. let documents = await _LCSUSER.get('documents').once().then();
  1150. if (documents) {
  1151. let states = await _LCSUSER.get('documents').get(worldName).once().then();
  1152. if (states) {
  1153. for (const st of Object.keys(states)) {
  1154. if (st !== '_') {
  1155. if (states[st]) {
  1156. await this.deleteWorldState(worldName, st);
  1157. }
  1158. }
  1159. }
  1160. }
  1161. }
  1162. let worldFiles = await _LCSUSER.get('worlds').get(worldName).once().then();
  1163. if (worldFiles) {
  1164. for (const el of Object.keys(worldFiles)) {
  1165. if (el !== '_') {
  1166. let doc = await _LCSUSER.get('worlds').get(worldName).get(el).once().then();
  1167. if (doc) {
  1168. if (doc.file) {
  1169. for (const fEl of Object.keys(doc)) {
  1170. if (fEl !== '_') {
  1171. await _LCSUSER.get('worlds').get(worldName).get(el).get(fEl).put(null).then();
  1172. }
  1173. }
  1174. await _LCSUSER.get('worlds').get(worldName).get(el).put(null).then();
  1175. } else {
  1176. await _LCSUSER.get('worlds').get(worldName).get(el).put(null).then()
  1177. }
  1178. }
  1179. }
  1180. }
  1181. }
  1182. // _LCSUSER.get('worlds').get(worldName).map((res, index) => {
  1183. // if(typeof res == 'object'){
  1184. // _LCSUSER.get('worlds').get(worldName).get(index)
  1185. // .get('file').put("null")
  1186. // .back(1)
  1187. // .get('modified').put("null")
  1188. // .back(1)
  1189. // .get('created').put("null")
  1190. // .back(1).put("null")
  1191. // } else {
  1192. // _LCSUSER.get('worlds').get(worldName).get(index).put("null")
  1193. // }
  1194. // })
  1195. await _LCSUSER.get('worlds').get(worldName).put(null).then();
  1196. } else if (type == 'state') {
  1197. let worldName = name.split('/')[0];
  1198. let stateName = name.split('/')[2];
  1199. let stateEntryInfo = 'savestate_/' + worldName + '/' + stateName + '_info_vwf_json';
  1200. let stateEntry = 'savestate_/' + worldName + '/' + stateName + '_vwf_json';
  1201. await this.deleteWorldState(worldName, stateEntryInfo);
  1202. await this.deleteWorldState(worldName, stateEntry);
  1203. }
  1204. let noty = new Noty({
  1205. text: "World Deleted!",
  1206. timeout: 2000,
  1207. theme: 'mint',
  1208. layout: 'bottomRight',
  1209. type: 'success'
  1210. });
  1211. noty.show();
  1212. }
  1213. parseAppInstancesData(data) {
  1214. let jsonObj = JSON.parse(data);
  1215. var parsed = {};
  1216. let listData = {};
  1217. for (var prop in jsonObj) {
  1218. var name = prop.split('/')[1];
  1219. if (parsed[name]) {
  1220. parsed[name][prop] = jsonObj[prop];
  1221. } else {
  1222. parsed[name] = {};
  1223. parsed[name][prop] = jsonObj[prop];
  1224. }
  1225. }
  1226. //console.log(parsed);
  1227. for (var prop in parsed) {
  1228. var name = prop;
  1229. let obj = Object.entries(parsed[prop]);
  1230. var lists = {};
  1231. obj.forEach(el => {
  1232. if (el[1].loadInfo['save_name']) {
  1233. let saveName = prop + '/load/' + el[1].loadInfo.save_name;
  1234. if (!lists[saveName])
  1235. lists[saveName] = {};
  1236. lists[saveName][el[0]] = el[1]
  1237. } else {
  1238. if (!lists[name])
  1239. lists[name] = {};
  1240. lists[name][el[0]] = el[1]
  1241. }
  1242. });
  1243. // console.log(lists);
  1244. Object.entries(lists).forEach(list => {
  1245. listData[list[0]] = list[1];
  1246. })
  1247. }
  1248. return listData
  1249. // console.log(data)
  1250. }
  1251. async getAllStateWorldsInfoForUser(userAlias, cb) {
  1252. let userPub = await _LCSDB.get('users').get(userAlias).get('pub').once().then();
  1253. var db = _LCSDB.user(userPub);
  1254. if (_LCSUSER.is) {
  1255. if (_LCSUSER.is.alias == userAlias)
  1256. db = _LCSUSER;
  1257. }
  1258. db.get('worlds').once().map().once((val, index)=>{
  1259. db.get('documents').get(index).once().map().once((res, datI)=>{
  1260. var doc = {};
  1261. if (datI.includes('_info_vwf_json')){
  1262. if (res && res !== 'null') {
  1263. if (res.file && res.file !== 'null') {
  1264. let saveName = datI.split('/')[2].replace('_info_vwf_json', "");
  1265. let worldDesc = JSON.parse(res.file);
  1266. let root = Object.keys(worldDesc)[0];
  1267. var appInfo = worldDesc[root]['en'];
  1268. let langID = localStorage.getItem('krestianstvo_locale');
  1269. if (langID) {
  1270. appInfo = worldDesc[root][langID]
  1271. }
  1272. doc = {
  1273. 'worldName': index + '/load/' + saveName,
  1274. 'created': res.created ? res.created : res.modified,
  1275. 'modified': res.modified,
  1276. 'type': 'saveState',
  1277. 'userAlias': userAlias,
  1278. 'info': appInfo
  1279. }
  1280. }
  1281. }
  1282. }
  1283. if (Object.keys(doc).length !== 0)
  1284. cb({[doc.worldName]: doc})
  1285. })
  1286. })
  1287. }
  1288. async getAllStateWorldsInfoForUserPromise(userAlias) {
  1289. let userPub = await _LCSDB.get('users').get(userAlias).get('pub').once().then();
  1290. var db = _LCSDB.user(userPub);
  1291. if (_LCSUSER.is) {
  1292. if (_LCSUSER.is.alias == userAlias)
  1293. db = _LCSUSER;
  1294. }
  1295. var states = {};
  1296. let worldDocs = await db.get('worlds').once().then();
  1297. if (worldDocs) {
  1298. let protos = Object.keys(worldDocs).filter(el => el !== '_');
  1299. if (protos) {
  1300. for (const el of protos) {
  1301. let info = await this.getSaveStates(userAlias, el);
  1302. if (Object.keys(info).length !== 0)
  1303. states[el] = info;
  1304. }
  1305. }
  1306. }
  1307. return states
  1308. }
  1309. async getAllProtoWorldsInfoForUser (userAlias, cb){
  1310. let userPub = await _LCSDB.get('users').get(userAlias).get('pub').once().then();
  1311. var db = _LCSDB.user(userPub);
  1312. if (_LCSUSER.is) {
  1313. if (_LCSUSER.is.alias == userAlias)
  1314. db = _LCSUSER;
  1315. }
  1316. db.get('worlds').once().map().once((val, index)=>{
  1317. db.get('worlds').get(index).get('info_json').once(res=>{
  1318. var doc = {};
  1319. if (res && res !== 'null') {
  1320. if (res.file && res.file !== 'null') {
  1321. let worldDesc = JSON.parse(res.file);
  1322. let root = Object.keys(worldDesc)[0];
  1323. var appInfo = worldDesc[root]['en'];
  1324. let langID = localStorage.getItem('krestianstvo_locale');
  1325. if (langID) {
  1326. appInfo = worldDesc[root][langID]
  1327. }
  1328. doc = {
  1329. 'worldName': index,
  1330. 'created': res.created ? res.created : res.modified,
  1331. 'modified': res.modified,
  1332. 'type': 'proto',
  1333. 'userAlias': userAlias,
  1334. 'info': appInfo
  1335. }
  1336. }
  1337. }
  1338. if (Object.keys(doc).length !== 0)
  1339. cb({[index]: doc})
  1340. })
  1341. })
  1342. }
  1343. async getAllProtoWorldsInfoForUserPromise(userAlias) {
  1344. let userPub = await _LCSDB.get('users').get(userAlias).get('pub').once().then();
  1345. var db = _LCSDB.user(userPub);
  1346. if (_LCSUSER.is) {
  1347. if (_LCSUSER.is.alias == userAlias)
  1348. db = _LCSUSER;
  1349. }
  1350. var worlds = {};
  1351. let worldDocs = await db.get('worlds').once().then();
  1352. if (worldDocs) {
  1353. let protos = Object.keys(worldDocs).filter(el => el !== '_');
  1354. if (protos) {
  1355. for (const el of protos) {
  1356. let info = await this.getWorldInfo(userAlias, el);
  1357. if (Object.keys(info).length !== 0)
  1358. worlds[el] = info;
  1359. }
  1360. }
  1361. }
  1362. return worlds
  1363. }
  1364. async getSaveStates(userAlias, worldName) {
  1365. let userPub = await _LCSDB.get('users').get(userAlias).get('pub').once().then();
  1366. var db = _LCSDB.user(userPub);
  1367. if (_LCSUSER.is) {
  1368. if (_LCSUSER.is.alias == userAlias)
  1369. db = _LCSUSER;
  1370. }
  1371. var states = {};
  1372. let documents = await db.get('documents').once().then();
  1373. if(documents) {
  1374. let docs = await db.get('documents').get(worldName).once().then();
  1375. if (docs) {
  1376. let saves = Object.keys(docs).filter(el => el.includes('_info_vwf_json'));
  1377. if (saves) {
  1378. for (const el of saves) {
  1379. let stateName = el.split('/')[2].replace('_info_vwf_json', "");
  1380. let info = await this.getStateInfo(userAlias, worldName, stateName);
  1381. if (Object.keys(info).length !== 0)
  1382. states[stateName] = info;
  1383. }
  1384. }
  1385. }
  1386. }
  1387. return states
  1388. }
  1389. async getStateInfo(user, space, saveName) {
  1390. let userPub = await _LCSDB.get('users').get(user).get('pub').once().then();
  1391. var db = _LCSDB.user(userPub);
  1392. if (_LCSUSER.is) {
  1393. if (_LCSUSER.is.alias == user)
  1394. db = _LCSUSER;
  1395. }
  1396. var info = {};
  1397. let docName = 'savestate_/' + space + '/' + saveName + '_info_vwf_json';
  1398. let world = await db.get('documents').get(space).get(docName).once().then();
  1399. if (world) {
  1400. let res = await db.get('documents').get(space).get(docName).once().then();
  1401. if (res && res !== 'null') {
  1402. if (res.file && res.file !== 'null') {
  1403. let worldDesc = JSON.parse(res.file);
  1404. let root = Object.keys(worldDesc)[0];
  1405. var appInfo = worldDesc[root]['en'];
  1406. let langID = localStorage.getItem('krestianstvo_locale');
  1407. if (langID) {
  1408. appInfo = worldDesc[root][langID]
  1409. }
  1410. info = {
  1411. 'worldName': space + '/load/' + saveName,
  1412. 'created': res.created ? res.created : res.modified,
  1413. 'modified': res.modified,
  1414. 'type': 'saveState',
  1415. 'userAlias': user,
  1416. 'info': appInfo
  1417. }
  1418. }
  1419. }
  1420. }
  1421. return info
  1422. }
  1423. async getWorldInfo(user, space) {
  1424. //get space for user
  1425. let userPub = await _LCSDB.get('users').get(user).get('pub').once().then();
  1426. var db = _LCSDB.user(userPub);
  1427. if (_LCSUSER.is) {
  1428. if (_LCSUSER.is.alias == user)
  1429. db = _LCSUSER;
  1430. }
  1431. var info = {};
  1432. let world = await db.get('worlds').get(space).once().then();
  1433. if (world) {
  1434. let res = await db.get('worlds').get(space).get('info_json').once().then();
  1435. if (res && res !== 'null') {
  1436. if (res.file && res.file !== 'null') {
  1437. let worldDesc = JSON.parse(res.file);
  1438. let root = Object.keys(worldDesc)[0];
  1439. var appInfo = worldDesc[root]['en'];
  1440. let langID = localStorage.getItem('krestianstvo_locale');
  1441. if (langID) {
  1442. appInfo = worldDesc[root][langID]
  1443. }
  1444. info = {
  1445. 'worldName': space,
  1446. 'created': res.created ? res.created : res.modified,
  1447. 'modified': res.modified,
  1448. 'type': 'proto',
  1449. 'userAlias': user,
  1450. 'info': appInfo
  1451. }
  1452. }
  1453. }
  1454. }
  1455. return info
  1456. }
  1457. }
  1458. export { App }