app.js 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792
  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 { WorldApp } from '/web/world-app.js';
  6. import { Header } from '/web/header.js';
  7. import { Widgets } from '/lib/widgets.js';
  8. class App {
  9. constructor() {
  10. console.log("app constructor");
  11. this.widgets = new Widgets;
  12. //globals
  13. window._app = this;
  14. window._cellWidgets = this.widgets;
  15. window._LangManager = new Lang;
  16. window._noty = new Noty;
  17. _LangManager.setLanguage().then(res => {
  18. return this.initDB()
  19. }).then(res => {
  20. this.helpers = new Helpers;
  21. this.initUser();
  22. //client routes
  23. page('/', this.HandleIndex);
  24. page('/setup', this.HandleSetupIndex);
  25. page('/settings', this.HandleSettingsIndex);
  26. page('/profile', this.HandleUserIndex);
  27. page('/worlds', this.HandleIndex);
  28. page('/:user/worlds', this.HandleUserWorlds);
  29. page('/:user/worlds/:type', this.HandleUserWorldsWithType);
  30. page('/:user/:type/:name/edit/:file', this.HandleFileEdit);
  31. page('/:user/:space', this.HandleParsableRequestGenID);
  32. page('/:user/:space/about', this.HandleWorldAbout);
  33. page('/:user/:space/:id', this.HandleParsableRequestWithID);
  34. page('/:user/:space/index.vwf/:id', this.HandleParsableRequestWithID);
  35. page('/:user/:space/load/:savename', this.HandleParsableLoadRequest);
  36. page('/:user/:space/load/:savename/about', this.HandleWorldAbout);
  37. page('/:user/:space/:id/load/:savename', this.HandleParsableRequestWithID);
  38. page('/:user/:space/load/:savename/:rev', this.HandleParsableLoadRequestWithRev);
  39. page('/:user/:space/:id/load/:savename/:rev', this.HandleParsableRequestWithID);
  40. page('*', this.HandleNoPage);
  41. page();
  42. })
  43. }
  44. initDB() {
  45. var config = JSON.parse(localStorage.getItem('lcs_config'));
  46. if (!config) {
  47. config = {
  48. 'dbhost': 'https://' + window.location.hostname + ':8080/gun', //'http://localhost:8080/gun',
  49. 'reflector': 'https://' + window.location.hostname + ':3002',
  50. 'language': 'en'
  51. }
  52. localStorage.setItem('lcs_config', JSON.stringify(config));
  53. }
  54. const dbConnection = new Promise((resolve, reject) => {
  55. this.db = Gun(this.dbHost);
  56. this.user = this.db.user();
  57. window._LCSDB = this.db;
  58. window._LCSUSER = this.user;
  59. window._LCS_SYS_USER = undefined;
  60. window._LCS_WORLD_USER = undefined;
  61. _LCSDB.get('lcs/app').get('pub').once(res => {
  62. if (res) {
  63. window._LCS_SYS_USER = this.db.user(res);
  64. }
  65. });
  66. _LCSDB.on('hi', function (peer) {
  67. let msg = 'Connected to ' + peer.url;
  68. let noty = new Noty({
  69. text: msg,
  70. timeout: 2000,
  71. theme: 'mint',
  72. layout: 'bottomRight',
  73. type: 'success'
  74. });
  75. noty.show();
  76. console.log(msg)
  77. })
  78. _LCSDB.on('bye', function (peer) {
  79. let msg = 'No connection to ' + peer.url;
  80. let noty = new Noty({
  81. text: msg,
  82. timeout: 1000,
  83. theme: 'mint',
  84. layout: 'bottomRight',
  85. type: 'error'
  86. });
  87. noty.show();
  88. console.log(msg)
  89. })
  90. resolve('ok');
  91. });
  92. return dbConnection
  93. }
  94. initUser() {
  95. _LCSUSER.recall({ sessionStorage: 1 });
  96. }
  97. get reflectorHost() {
  98. var res = "";
  99. let config = localStorage.getItem('lcs_config');
  100. if (config) {
  101. res = JSON.parse(config).reflector;
  102. }
  103. return res;
  104. }
  105. get dbHost() {
  106. var res = "";
  107. let config = localStorage.getItem('lcs_config');
  108. if (config) {
  109. res = JSON.parse(config).dbhost;
  110. }
  111. return res;
  112. }
  113. async loadProxyDefaults() {
  114. //load to DB default proxy files (VWF & A-Frame components)
  115. let proxyResponse = await fetch('/proxy-files', { method: 'get' });
  116. let proxyFiles = await proxyResponse.json();
  117. let filterProxyFiles = proxyFiles.filter(el => (el !== null));
  118. console.log(filterProxyFiles);
  119. var origin = window.location.origin;
  120. //var userPub = _LCSUSER.is.pub;
  121. let proxyObj = {};
  122. for (var index in filterProxyFiles) {
  123. let el = filterProxyFiles[index];
  124. if (el) {
  125. var url = origin + el;
  126. var entryName = url.replace(origin + '/defaults/', "").split(".").join("_");
  127. let proxyFile = await fetch(url, { method: 'get' });
  128. let responseText = await proxyFile.text();
  129. if (responseText) {
  130. let created = new Date().valueOf();
  131. let obj = {
  132. //'owner': userPub,
  133. 'file': responseText,
  134. 'modified': created,
  135. 'created': created
  136. }
  137. proxyObj[entryName] = obj;
  138. }
  139. }
  140. }
  141. console.log(proxyObj);
  142. Object.keys(proxyObj).forEach(el => {
  143. _LCSDB.user().get('proxy').get(el).put(proxyObj[el]);
  144. })
  145. }
  146. async loadWorldsDefaults(replace) {
  147. //load to DB default worlds
  148. let worldsResponse = await fetch('/world-files', { method: 'get' });
  149. let worldFiles = await worldsResponse.json();
  150. let filterworldFiles = worldFiles.filter(el => (el !== null));
  151. console.log(filterworldFiles);
  152. let worldsObj = {};
  153. for (var index in filterworldFiles) {
  154. let el = filterworldFiles[index];
  155. if (el) {
  156. let url = window.location.origin + el;
  157. var entryName = url.replace(window.location.origin + '/defaults/worlds/', "").split(".").join("_");
  158. let worldName = entryName.split("/")[0];
  159. let userPub = _LCSUSER.is.pub;
  160. let worldFile = await fetch(url, { method: 'get' });
  161. let worldSource = await worldFile.text();
  162. if (worldSource) {
  163. //let modified = new Date().valueOf();
  164. let created = new Date().valueOf();
  165. let obj = {
  166. 'file': worldSource,
  167. 'modified': created,
  168. 'created': created
  169. }
  170. if (!worldsObj[worldName]) {
  171. worldsObj[worldName] = {
  172. 'parent': '-',
  173. 'owner': userPub,
  174. 'featured': true,
  175. 'published': true
  176. }
  177. }
  178. let entry = entryName.replace(worldName + '/', "");
  179. worldsObj[worldName][entry] = obj;
  180. }
  181. }
  182. }
  183. console.log(worldsObj);
  184. if (replace) {
  185. Object.entries(worldsObj).forEach(el => {
  186. let worldName = el[0];
  187. let files = el[1];
  188. Object.entries(files).forEach(file => {
  189. _LCSDB.user().get('worlds').get(worldName).get(file[0]).put(file[1]);
  190. })
  191. })
  192. } else {
  193. //force replace all default worlds
  194. Object.entries(worldsObj).forEach(el => {
  195. let worldName = el[0];
  196. let files = el[1];
  197. Object.entries(files).forEach(file => {
  198. _LCSDB.user().get('worlds').get(worldName).get(file[0]).not(res => {
  199. _LCSDB.user().get('worlds').get(worldName).get(file[0]).put(file[1]);
  200. })
  201. })
  202. })
  203. }
  204. }
  205. async loadEmptyDefaultProto() {
  206. //empty proto world
  207. let userPub = _LCSUSER.is.pub;
  208. let worldsObj = {};
  209. let emptyWorld = {
  210. "index_vwf_yaml": YAML.stringify(
  211. {
  212. "extends": "http://vwf.example.com/aframe/ascene.vwf"
  213. }, 4),
  214. "index_vwf_config_yaml": YAML.stringify(
  215. {
  216. "info": {
  217. "title": "Empty World"
  218. },
  219. "model": {
  220. "vwf/model/aframe": null
  221. },
  222. "view": {
  223. "vwf/view/aframe": null,
  224. "vwf/view/editor-new": null
  225. }
  226. }, 4),
  227. "assets_json": JSON.stringify({}),
  228. "index_vwf_html": JSON.stringify("<!-- DEFAULT HTML -->"),
  229. "appui_js": JSON.stringify("//appui in JS"),
  230. "info_json": JSON.stringify({
  231. "info": {
  232. "en": {
  233. "title": "Empty World",
  234. "imgUrl": "",
  235. "text": "Empty World"
  236. },
  237. "ru": {
  238. "title": "Новый Мир",
  239. "imgUrl": "",
  240. "text": "Новый Мир"
  241. }
  242. }
  243. }, null, 4)
  244. }
  245. worldsObj['empty'] = {
  246. 'parent': '-',
  247. 'owner': userPub,
  248. 'featured': true,
  249. 'published': true
  250. }
  251. Object.keys(emptyWorld).forEach(el => {
  252. //let modified = new Date().valueOf();
  253. let created = new Date().valueOf();
  254. let obj = {
  255. 'file': emptyWorld[el],
  256. 'modified': created,
  257. 'created': created
  258. }
  259. worldsObj['empty'][el] = obj;
  260. })
  261. console.log(worldsObj);
  262. Object.entries(worldsObj).forEach(el => {
  263. let worldName = el[0];
  264. let files = el[1];
  265. Object.entries(files).forEach(file => {
  266. _LCSDB.user().get('worlds').get(worldName).get(file[0]).put(file[1]);
  267. })
  268. })
  269. }
  270. //load defaults for first registered user running ./setup
  271. HandleSettingsIndex() {
  272. window._app.hideProgressBar();
  273. window._app.hideUIControl();
  274. let el = document.createElement("div");
  275. el.setAttribute("id", "appGUI");
  276. document.body.appendChild(el);
  277. _cellWidgets.reflectorGUI();
  278. }
  279. HandleWorldAbout(ctx) {
  280. console.log("about world");
  281. let userAlias = ctx.params.user;
  282. let worldName = ctx.params.space;
  283. let saveName = ctx.params.savename;
  284. window._app.hideProgressBar();
  285. window._app.hideUIControl();
  286. let headerGUI = new Header();
  287. headerGUI.init();
  288. // if (!_app.indexApp) {
  289. // _app.indexApp = new IndexApp;
  290. // document.querySelector('head').innerHTML += '<link rel="stylesheet" href="/web/index-app.css">';
  291. // }
  292. // if (!document.querySelector('#app')) {
  293. // _app.indexApp.initApp();
  294. // }
  295. let worldApp = new WorldApp(userAlias, worldName, saveName);
  296. 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. let indexApp = new IndexApp;
  564. indexApp.initApp();
  565. if (type == 'protos') {
  566. await indexApp.getWorldsProtosListForUser(user);
  567. } else if (type == 'states') {
  568. await indexApp.getWorldsStatesListForUser(user);
  569. //await _app.indexApp.getWorldsFromUserDB(user);
  570. }
  571. }
  572. async HandleIndex() {
  573. console.log("INDEX");
  574. window._app.hideProgressBar();
  575. window._app.hideUIControl();
  576. let indexApp = new IndexApp;
  577. await indexApp.generateFrontPage();
  578. indexApp.initApp();
  579. await indexApp.getWorldsProtosListForUser('app');
  580. //await _app.indexApp.getAppDetailsFromDB();
  581. }
  582. HandleNoPage() {
  583. console.log("no such page")
  584. }
  585. //handle parcable requests
  586. HandleParsableLoadRequest(ctx) {
  587. let app = window._app;
  588. console.log(ctx.params);
  589. //var pathname = ctx.pathname;
  590. var spaceName = ctx.params.space;
  591. var saveName = ctx.params.savename;
  592. let user = ctx.params.user;
  593. page.redirect('/' + user + '/' + spaceName + '/' + app.helpers.GenerateInstanceID() + '/load/' + saveName);
  594. }
  595. HandleParsableLoadRequestWithRev(ctx) {
  596. let app = window._app;
  597. console.log(ctx.params);
  598. //var pathname = ctx.pathname;
  599. var spaceName = ctx.params.space;
  600. var saveName = ctx.params.savename;
  601. var rev = ctx.params.rev;
  602. let user = ctx.params.user;
  603. page.redirect('/' + user + '/' + spaceName + '/' + app.helpers.GenerateInstanceID() + '/load/' + saveName + '/' + rev);
  604. }
  605. async setUserPaths(user) {
  606. await _LCSDB.get('users').get(user).get('pub').once(res => {
  607. if (res)
  608. window._LCS_WORLD_USER = _LCSDB.user(res);
  609. }).then();
  610. }
  611. async HandleParsableRequestGenID(ctx) {
  612. let app = window._app;
  613. console.log(ctx.params);
  614. let user = ctx.params.user;
  615. var pathname = ctx.pathname;
  616. await app.setUserPaths(user);
  617. if (pathname[pathname.length - 1] == '/') {
  618. pathname = pathname.slice(0, -1)
  619. }
  620. let pathToParse = pathname.replace('/' + user, "");
  621. app.helpers.Process(pathToParse).then(parsedRequest => {
  622. localStorage.setItem('lcs_app', JSON.stringify({ path: parsedRequest }));
  623. console.log(parsedRequest);
  624. if ((parsedRequest['instance'] == undefined) && (parsedRequest['private_path'] == undefined) && (parsedRequest['public_path'] !== "/") && (parsedRequest['application'] !== undefined)) {
  625. page.redirect(pathname + '/' + app.helpers.GenerateInstanceID());
  626. }
  627. });
  628. }
  629. async HandleParsableRequestWithID(ctx) {
  630. let app = window._app;
  631. console.log(ctx.params);
  632. var pathname = ctx.pathname;
  633. let user = ctx.params.user;
  634. if (pathname[pathname.length - 1] == '/') {
  635. pathname = pathname.slice(0, -1)
  636. }
  637. await app.setUserPaths(user);
  638. let pathToParse = pathname.replace('/' + user, "");
  639. app.helpers.Process(pathToParse).then(async function (parsedRequest) {
  640. localStorage.setItem('lcs_app', JSON.stringify({ path: parsedRequest }));
  641. console.log(parsedRequest);
  642. var userLibraries = { model: {}, view: {} };
  643. var application;
  644. await vwf.loadConfiguration(application, userLibraries, compatibilityCheck);
  645. });
  646. }
  647. async HandleParsableRequest(ctx) {
  648. let app = window._app;
  649. console.log(ctx.params);
  650. var pathname = ctx.pathname;
  651. if (pathname[pathname.length - 1] == '/') {
  652. pathname = pathname.slice(0, -1)
  653. }
  654. var parsedRequest = await app.helpers.Process(pathname);
  655. localStorage.setItem('lcs_app', JSON.stringify({ path: parsedRequest }));
  656. console.log(parsedRequest);
  657. if ((parsedRequest['instance'] == undefined) && (parsedRequest['private_path'] == undefined) && (parsedRequest['public_path'] !== "/") && (parsedRequest['application'] !== undefined)) {
  658. // Redirect if the url request does not include an application/file && a default 'index.vwf.yaml' exists
  659. // page.redirect(pathname + '/' + app.helpers.GenerateInstanceID());
  660. window.location.pathname = pathname + '/' + app.helpers.GenerateInstanceID()
  661. //return true;
  662. } else {
  663. //return false;
  664. }
  665. var userLibraries = { model: {}, view: {} };
  666. var application;
  667. await vwf.loadConfiguration(application, userLibraries, compatibilityCheck);
  668. }
  669. //get DB application state information for reflector (called from VWF)
  670. async getApplicationState() {
  671. let dataJson = JSON.parse(localStorage.getItem('lcs_app'));
  672. if (dataJson) {
  673. if (!dataJson.path['instance']) return undefined;
  674. }
  675. let userAlias = await _LCS_WORLD_USER.get('alias').once().then();
  676. let userPub = await _LCSDB.get('users').get(userAlias).get('pub').once().then();
  677. let loadInfo = await this.getLoadInformation(dataJson);
  678. let saveInfo = await this.loadSaveObject(loadInfo);
  679. let loadObj = {
  680. loadInfo: loadInfo,
  681. path: dataJson.path,
  682. saveObject: saveInfo,
  683. user: userAlias
  684. }
  685. //dataJson.app = loadObj;
  686. localStorage.setItem('lcs_app', JSON.stringify(loadObj));
  687. console.log(loadObj);
  688. //temporary solution for syncing DB replicas using Gun.load()
  689. // _LCS_SYS_USER.get('proxy').load(res=>{
  690. // if (res)
  691. // {console.log('proxy loaded');
  692. // _LCSDB.user(userPub).get('worlds').get(loadObj.path.public_path.slice(1)).load(w=>{
  693. // if (w) {
  694. // console.log('world files loaded');
  695. // vwf.ready( vwf.application, loadObj)
  696. // }
  697. // }, {wait: 200});
  698. // }
  699. // }, {wait: 200});
  700. return loadObj
  701. }
  702. // LookupSaveRevisions takes the public path and the name of a save, and provides
  703. // an array of all revisions for that save. (If the save does not exist, this will be
  704. // an empty array).
  705. async lookupSaveRevisions(public_path, save_name) {
  706. var result = [];
  707. var states = [];
  708. let docName = 'savestate_/' + public_path + '/' + save_name + '_vwf_json';
  709. let revs = await _LCS_WORLD_USER.get('documents').get(public_path).get(docName).get('revs').once().then();
  710. if (revs) {
  711. for (const res of Object.keys(revs)) {
  712. if (res !== '_') {
  713. let el = await _LCS_WORLD_USER.get('documents').get(public_path).get(docName).get('revs').get(res).once().then();
  714. if (el)
  715. result.push(parseInt(el.revision));
  716. }
  717. }
  718. return result
  719. }
  720. }
  721. // GetLoadInformation receives a parsed request {private_path, public_path, instance, application} and returns the
  722. // details of the save that is designated by the initial request. The details are returned in an object
  723. // composed of: save_name (name of the save) save_revision (revision of the save), explicit_revision (boolean, true if the request
  724. // explicitly specified the revision, false if it did not), and application_path (the public_path of the application this is a save for).
  725. async getLoadInformation(response) {
  726. let parsedRequest = response.path;
  727. var result = { 'save_name': undefined, 'save_revision': undefined, 'explicit_revision': undefined, 'application_path': undefined };
  728. if (parsedRequest['private_path']) {
  729. var segments = this.helpers.GenerateSegments(parsedRequest['private_path']);
  730. if ((segments.length > 1) && (segments[0] == "load")) {
  731. var potentialRevisions = await this.lookupSaveRevisions((parsedRequest['public_path']).slice(1), segments[1]);
  732. console.log('!!!!! - ', potentialRevisions);
  733. if (potentialRevisions.length > 0) {
  734. result['save_name'] = segments[1];
  735. if (segments.length > 2) {
  736. var requestedRevision = parseInt(segments[2]);
  737. if (requestedRevision) {
  738. if (potentialRevisions.indexOf(requestedRevision) > -1) {
  739. result['save_revision'] = requestedRevision;
  740. result['explicit_revision'] = true;
  741. result['application_path'] = parsedRequest['public_path'];
  742. }
  743. }
  744. }
  745. if (result['explicit_revision'] == undefined) {
  746. result['explicit_revision'] = false;
  747. potentialRevisions.sort();
  748. result['save_revision'] = potentialRevisions.pop();
  749. result['application_path'] = parsedRequest['public_path'];
  750. }
  751. }
  752. }
  753. }
  754. return result;
  755. }
  756. async loadSaveObject(loadInfo) {
  757. //let objName = loadInfo[ 'save_name' ] +'/'+ "savestate_" + loadInfo[ 'save_revision' ];
  758. if (!loadInfo.save_name) {
  759. return undefined
  760. }
  761. let objName = "savestate_" + loadInfo['application_path'] + '/' + loadInfo['save_name'] + '_vwf_json';
  762. let objNameRev = "savestate_" + loadInfo['save_revision'] + loadInfo['application_path'] + '/' + loadInfo['save_name'] + '_vwf_json';
  763. // if(loadInfo[ 'save_revision' ]){
  764. // }
  765. let worldName = this.helpers.appPath //loadInfo[ 'application_path' ].slice(1);
  766. let saveObject = await _LCS_WORLD_USER.get('documents').get(worldName).get(objName).get('revs').get(objNameRev).once().then();
  767. let saveInfo = saveObject ? JSON.parse(saveObject.jsonState) : saveObject;
  768. return saveInfo;
  769. }
  770. // GetSaveInformation is a helper function that takes the application_path (/path/to/application).
  771. // It returns an array of all saves found for that
  772. // application (including separate entries for individual revisions of saves ).
  773. async getSaveInformation(application_path, userPUB) {
  774. var result = [];
  775. let user = _LCSDB.user(userPUB);
  776. var docName = application_path.slice(1);
  777. let potentialSaveNames = await user.get('documents').get(docName).once().then();
  778. if (potentialSaveNames) {
  779. for (const res of Object.keys(potentialSaveNames)) {
  780. if (res !== '_') {
  781. let el = await user.get('documents').path(docName).get(res).once().then();
  782. let revisionList = await this.lookupSaveRevisions(application_path.slice(1), el.filename);
  783. var latestsave = true;
  784. revisionList.sort();
  785. while (revisionList.length > 0) {
  786. var newEntry = {};
  787. newEntry['applicationpath'] = application_path;
  788. newEntry['savename'] = el.filename;
  789. newEntry['revision'] = revisionList.pop().toString();
  790. newEntry['latestsave'] = latestsave;
  791. if (latestsave) {
  792. newEntry['url'] = this.helpers.JoinPath(window.location.origin, application_path, "load", el.filename + "/");
  793. }
  794. else {
  795. newEntry['url'] = this.helpers.JoinPath(window.location.origin, application_path, "load", el.filename + "/", newEntry['revision'] + "/");
  796. }
  797. latestsave = false;
  798. result.push(newEntry);
  799. }
  800. }
  801. }
  802. }
  803. return result;
  804. }
  805. async getProtoWorldFiles(userPub, worldName, date) {
  806. let fileNamesAll = await _LCSDB.user(userPub).get('worlds').get(worldName).once().then();
  807. let worldFileNames = Object.keys(fileNamesAll).filter(el => (el !== '_') && (el !== 'owner') && (el !== 'parent') && (el !== 'featured') && (el !== 'published') && (el !== 'info_json'));
  808. let worldObj = {};
  809. for (var el in worldFileNames) {
  810. let fn = worldFileNames[el];
  811. let res = await _LCSDB.user(userPub).get('worlds').get(worldName).get(fn).once().then();
  812. var data = {
  813. 'file': res.file,
  814. 'modified': res.modified,
  815. 'created': res.created
  816. }
  817. if (!date) {
  818. data = {
  819. 'file': res.file
  820. }
  821. }
  822. worldObj[fn] = data;
  823. }
  824. console.log(worldObj);
  825. return worldObj
  826. }
  827. async cloneWorldPrototype(worldName, userName, newWorldName) {
  828. let userPub = await _LCSDB.get('users').get(userName).get('pub').once().then();
  829. //let worldProto = await _LCSDB.user(userPub).get('worlds').get(worldName).once().then();
  830. var worldID = window._app.helpers.GenerateInstanceID().toString();
  831. if (newWorldName) {
  832. worldID = newWorldName
  833. }
  834. //let modified = new Date().valueOf();
  835. console.log('clone: ' + worldName + 'to: ' + worldID);
  836. let newOwner = _LCSUSER.is.pub;
  837. let created = new Date().valueOf();
  838. let worldObj = {
  839. 'owner': newOwner,
  840. 'parent': userName + '/' + worldName,
  841. 'featured': true,
  842. 'published': true
  843. };
  844. let fileNamesAll = await _LCSDB.user(userPub).get('worlds').get(worldName).once().then();
  845. let worldFileNames = Object.keys(fileNamesAll).filter(el => (el !== '_') && (el !== 'owner') && (el !== 'parent') && (el !== 'featured') && (el !== 'published'));
  846. for (var el in worldFileNames) {
  847. let fn = worldFileNames[el];
  848. let res = await _LCSDB.user(userPub).get('worlds').get(worldName).get(fn).once().then();
  849. let data = {
  850. 'file': res.file,
  851. 'modified': created
  852. }
  853. worldObj[fn] = data;
  854. }
  855. console.log(worldObj);
  856. Object.keys(worldObj).forEach(el => {
  857. _LCSUSER.get('worlds').get(worldID).get(el).put(worldObj[el]);
  858. })
  859. }
  860. async cloneWorldState(filename) {
  861. let myWorldProtos = await _LCSUSER.get('worlds').once().then();
  862. let userName = this.helpers.worldUser;
  863. let userPub = await _LCSDB.get('users').get(userName).get('pub').once().then();
  864. let protoUserRoot = this.helpers.getRoot(true).root;
  865. //let myName = _LCSUSER.is.alias;
  866. //let proto = Object.keys(myWorldProtos).filter(el => el == protoUserRoot);
  867. var protosKeys = [];
  868. if (myWorldProtos)
  869. protosKeys = Object.keys(myWorldProtos);
  870. if (protosKeys.includes(protoUserRoot)) {
  871. let userProtoFiles = await this.getProtoWorldFiles(userPub, protoUserRoot);
  872. let myProtoFiles = await this.getProtoWorldFiles(_LCSUSER.is.pub, protoUserRoot);
  873. let hashUP = await this.helpers.sha256(JSON.stringify(userProtoFiles));
  874. let hashMP = await this.helpers.sha256(JSON.stringify(myProtoFiles));
  875. if (hashUP == hashMP) {
  876. this.saveStateAsFile(filename);
  877. } else {
  878. let noty = new Noty({
  879. text: 'world prototype is modified.. could not clone world state',
  880. timeout: 2000,
  881. theme: 'mint',
  882. layout: 'bottomRight',
  883. type: 'error'
  884. });
  885. noty.show();
  886. }
  887. } else {
  888. await this.cloneWorldPrototype(protoUserRoot, userName, protoUserRoot);
  889. this.saveStateAsFile(filename);
  890. }
  891. }
  892. //TODO: refactor and config save
  893. saveStateAsFile(filename, otherProto) // invoke with the view as "this"
  894. {
  895. console.log("Saving: " + filename);
  896. //var clients = this.nodes["http://vwf.example.com/clients.vwf"];
  897. // Save State Information
  898. var state = vwf.getState();
  899. state.nodes[0].children = {};
  900. var timestamp = state["queue"].time;
  901. timestamp = Math.round(timestamp * 1000);
  902. var objectIsTypedArray = function (candidate) {
  903. var typedArrayTypes = [
  904. Int8Array,
  905. Uint8Array,
  906. // Uint8ClampedArray,
  907. Int16Array,
  908. Uint16Array,
  909. Int32Array,
  910. Uint32Array,
  911. Float32Array,
  912. Float64Array
  913. ];
  914. var isTypedArray = false;
  915. if (typeof candidate == "object" && candidate != null) {
  916. typedArrayTypes.forEach(function (typedArrayType) {
  917. isTypedArray = isTypedArray || candidate instanceof typedArrayType;
  918. });
  919. }
  920. return isTypedArray;
  921. };
  922. var transitTransformation = function (object) {
  923. return objectIsTypedArray(object) ?
  924. Array.prototype.slice.call(object) : object;
  925. };
  926. let jsonValuePure = require("vwf/utility").transform(
  927. state, transitTransformation
  928. );
  929. //remove all Ohm generated grammarsfrom state
  930. let jsonValue = _app.helpers.removeGrammarObj(jsonValuePure);
  931. var jsonState = JSON.stringify(jsonValue);
  932. let rootPath = this.helpers.getRoot(true);
  933. var inst = rootPath.inst;
  934. if (filename == '') filename = inst;
  935. //if (root.indexOf('.vwf') != -1) root = root.substring(0, root.lastIndexOf('/'));
  936. var root = rootPath.root;
  937. var json = jsonState;
  938. if (otherProto) {
  939. console.log('need to modify state...');
  940. json = this.helpers.replaceSubStringALL(jsonState, '/' + root + '/', '/' + otherProto + '/');//jsonState.replace(('/' + root + '/'), ('/' + otherProto +'/') );
  941. root = otherProto;
  942. console.log(json);
  943. }
  944. //var documents = _LCSUSER.get('documents');
  945. var saveRevision = new Date().valueOf();
  946. var stateForStore = {
  947. "root": root,
  948. "filename": filename,
  949. "inst": inst,
  950. "timestamp": timestamp,
  951. "extension": ".vwf.json",
  952. "jsonState": json,
  953. "publish": true
  954. };
  955. //let objName = loadInfo[ 'save_name' ] +'/'+ "savestate_" + loadInfo[ 'save_revision' ];
  956. // "savestate_" + loadInfo[ 'save_revision' ] + '/' + loadInfo[ 'save_name' ] + '_vwf_json'
  957. var docName = 'savestate_/' + root + '/' + filename + '_vwf_json';
  958. _LCSUSER.get('documents').get(root).get(docName).put(stateForStore, res => {
  959. if (res) {
  960. let noty = new Noty({
  961. text: 'Saved to ' + docName,
  962. timeout: 2000,
  963. theme: 'mint',
  964. layout: 'bottomRight',
  965. type: 'success'
  966. });
  967. noty.show();
  968. }
  969. });
  970. _LCSUSER.get('worlds').get(root).get('info_json').once(res => {
  971. if (res) {
  972. let modified = saveRevision;
  973. let newOwner = _LCSUSER.is.pub;
  974. let userName = _LCSUSER.is.alias;
  975. let obj = {
  976. 'parent': userName + '/' + root,
  977. 'owner': newOwner,
  978. 'file': res.file,
  979. //'modified': modified,
  980. 'created': modified
  981. }
  982. let docInfoName = 'savestate_/' + root + '/' + filename + '_info_vwf_json';
  983. _LCSUSER.get('documents').get(root).get(docInfoName).not(res => {
  984. _LCSUSER.get('documents').get(root).get(docInfoName).put(obj);
  985. });
  986. _LCSUSER.get('documents').get(root).get(docInfoName).get('created').not(res => {
  987. _LCSUSER.get('documents').get(root).get(docInfoName).get('created').put(modified);
  988. });
  989. _LCSUSER.get('documents').get(root).get(docInfoName).get('modified').put(modified);
  990. }
  991. });
  992. var docNameRev = 'savestate_' + saveRevision.toString() + '/' + root + '/' + filename + '_vwf_json';
  993. _LCSUSER.get('documents').get(root).get(docName).get('revs').get(docNameRev).put(stateForStore)
  994. .path("revision").put(saveRevision);
  995. // Save Config Information
  996. var config = { "info": {}, "model": {}, "view": {} };
  997. // Save browser title
  998. config["info"]["title"] = document.title//$('title').html();
  999. // Save model drivers
  1000. Object.keys(vwf_view.kernel.kernel.models).forEach(function (modelDriver) {
  1001. if (modelDriver.indexOf('vwf/model/') != -1) config["model"][modelDriver] = "";
  1002. });
  1003. // If neither glge or threejs model drivers are defined, specify nodriver
  1004. if (config["model"]["vwf/model/glge"] === undefined && config["model"]["vwf/model/threejs"] === undefined) config["model"]["nodriver"] = "";
  1005. // Save view drivers and associated parameters, if any
  1006. Object.keys(vwf_view.kernel.kernel.views).forEach(function (viewDriver) {
  1007. if (viewDriver.indexOf('vwf/view/') != -1) {
  1008. if (vwf_view.kernel.kernel.views[viewDriver].parameters) {
  1009. config["view"][viewDriver] = vwf_view.kernel.kernel.views[viewDriver].parameters;
  1010. }
  1011. else config["view"][viewDriver] = "";
  1012. }
  1013. });
  1014. //var jsonConfig = $.encoder.encodeForURL(JSON.stringify(config));
  1015. var jsonConfig = JSON.stringify(config);
  1016. let configStateForStore = {
  1017. "root": root,
  1018. "filename": filename,
  1019. "inst": inst,
  1020. "timestamp": timestamp,
  1021. "extension": "config.vwf.json",
  1022. "jsonState": jsonConfig
  1023. };
  1024. //let objName = loadInfo[ 'save_name' ] +'/'+ "savestate_" + loadInfo[ 'save_revision' ];
  1025. // "savestate_" + loadInfo[ 'save_revision' ] + '/' + loadInfo[ 'save_name' ] + '_vwf_json'
  1026. // let configName = 'savestate_/' + root + '/' + filename + '_config_vwf_json';
  1027. // let documentSaveConfigState = _LCSUSER.get(configName).put(configStateForStore);
  1028. // //documents.path(root).set(documentSaveConfigState);
  1029. // let configNameRev = 'savestate_' + saveRevision.toString() + '/' + root + '/' + filename + '_config_vwf_json';
  1030. // _LCSUSER.get(configNameRev).put(configStateForStore);
  1031. // _LCSUSER.get(configNameRev).path("revision").put(saveRevision);
  1032. //documentSaveConfigState.path('revs').set(documentSaveStateRevision);
  1033. // Save config file to server
  1034. // var xhrConfig = new XMLHttpRequest();
  1035. // xhrConfig.open("POST", "/" + root + "/save/" + filename, true);
  1036. // xhrConfig.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  1037. // xhrConfig.send("root=" + root + "/" + filename + "&filename=saveState&inst=" + inst + "&timestamp=" + timestamp + "&extension=.vwf.config.json" + "&jsonState=" + jsonConfig);
  1038. }
  1039. // LoadSavedState
  1040. async loadSavedState(filename, applicationpath, revision) {
  1041. console.log("Loading: " + filename);
  1042. let userName = await _LCS_WORLD_USER.get('alias').once().then();
  1043. if (revision) {
  1044. window.location.pathname = '/' + userName + applicationpath + '/load/' + filename + '/' + revision + '/';
  1045. }
  1046. else { // applicationpath + "/" + inst + '/load/' + filename + '/';
  1047. window.location.pathname = '/' + userName + applicationpath + '/load/' + filename + '/';
  1048. }
  1049. }
  1050. hideUIControl() {
  1051. var el = document.getElementById("ui-controls");
  1052. if (el) {
  1053. el.classList.remove("visible");
  1054. el.classList.add("not-visible");
  1055. }
  1056. }
  1057. showUIControl() {
  1058. var el = document.getElementById("ui-controls");
  1059. if (el) {
  1060. el.classList.remove("not-visible");
  1061. el.classList.add("visible");
  1062. }
  1063. }
  1064. hideProgressBar() {
  1065. var progressbar = document.getElementById("load-progressbar");
  1066. if (progressbar) {
  1067. progressbar.classList.remove("visible");
  1068. progressbar.classList.add("not-visible");
  1069. progressbar.classList.add("mdc-linear-progress--closed");
  1070. }
  1071. }
  1072. showProgressBar() {
  1073. let progressbar = document.getElementById("load-progressbar");
  1074. if (progressbar) {
  1075. progressbar.classList.add("visible");
  1076. progressbar.classList.add("mdc-linear-progress--indeterminate");
  1077. }
  1078. }
  1079. // SUPPORT of DELETE USER WORLDS & SAVE STATES (experimental)
  1080. // TODO: manual garbage collection
  1081. async deleteWorldState(worldName, indexState) {
  1082. let revs = await _LCSUSER.get('documents').get(worldName).get(indexState).get('revs').once().then();
  1083. if (revs) {
  1084. for (const el of Object.keys(revs)) {
  1085. if (el !== '_') {
  1086. let doc = await _LCSUSER.get('documents').get(worldName).get(indexState).get('revs').get(el).once().then();
  1087. for (const rev of Object.keys(doc)) {
  1088. if (rev !== '_') {
  1089. await _LCSUSER.get('documents').get(worldName).get(indexState).get('revs').get(el).get(rev).put(null).then();
  1090. }
  1091. }
  1092. await _LCSUSER.get('documents').get(worldName).get(indexState).get('revs').get(el).put(null).then();
  1093. }
  1094. }
  1095. }
  1096. // clear all state params
  1097. let stateDoc = await _LCSUSER.get('documents').get(worldName).get(indexState).once().then();
  1098. for (const state of Object.keys(stateDoc)) {
  1099. if (state !== '_' && state !== 'revs') {
  1100. await _LCSUSER.get('documents').get(worldName).get(indexState).get(state).put(null).then();
  1101. }
  1102. }
  1103. await _LCSUSER.get('documents').get(worldName).get(indexState).get('revs').put(null).then();
  1104. await _LCSUSER.get('documents').get(worldName).get(indexState).put(null).then();
  1105. }
  1106. async deleteWorld(name, type) {
  1107. if (type == 'proto') {
  1108. let worldName = name;
  1109. //TODO check for states (ask for deleting all states first...)
  1110. //delete states
  1111. let documents = await _LCSUSER.get('documents').once().then();
  1112. if (documents) {
  1113. let states = await _LCSUSER.get('documents').get(worldName).once().then();
  1114. if (states) {
  1115. for (const el of Object.keys(states)) {
  1116. if (el !== '_') {
  1117. if (states[el]) {
  1118. await this.deleteWorldState(worldName, el);
  1119. }
  1120. }
  1121. }
  1122. }
  1123. }
  1124. let worldFiles = await _LCSUSER.get('worlds').get(worldName).once().then();
  1125. if (worldFiles) {
  1126. for (const el of Object.keys(worldFiles)) {
  1127. if (el !== '_') {
  1128. let doc = await _LCSUSER.get('worlds').get(worldName).get(el).once().then();
  1129. if (doc) {
  1130. if (doc.file) {
  1131. for (const fEl of Object.keys(doc)) {
  1132. if (fEl !== '_') {
  1133. await _LCSUSER.get('worlds').get(worldName).get(el).get(fEl).put(null).then();
  1134. }
  1135. }
  1136. await _LCSUSER.get('worlds').get(worldName).get(el).put(null).then();
  1137. } else {
  1138. await _LCSUSER.get('worlds').get(worldName).get(el).put(null).then()
  1139. }
  1140. }
  1141. }
  1142. }
  1143. }
  1144. // _LCSUSER.get('worlds').get(worldName).map((res, index) => {
  1145. // if(typeof res == 'object'){
  1146. // _LCSUSER.get('worlds').get(worldName).get(index)
  1147. // .get('file').put("null")
  1148. // .back(1)
  1149. // .get('modified').put("null")
  1150. // .back(1)
  1151. // .get('created').put("null")
  1152. // .back(1).put("null")
  1153. // } else {
  1154. // _LCSUSER.get('worlds').get(worldName).get(index).put("null")
  1155. // }
  1156. // })
  1157. await _LCSUSER.get('worlds').get(worldName).put(null).then();
  1158. } else if (type == 'state') {
  1159. let worldName = name.split('/')[0];
  1160. let stateName = name.split('/')[2];
  1161. let stateEntryInfo = 'savestate_/' + worldName + '/' + stateName + '_info_vwf_json';
  1162. let stateEntry = 'savestate_/' + worldName + '/' + stateName + '_vwf_json';
  1163. await this.deleteWorldState(worldName, stateEntryInfo);
  1164. await this.deleteWorldState(worldName, stateEntry);
  1165. }
  1166. let noty = new Noty({
  1167. text: "World Deleted!",
  1168. timeout: 2000,
  1169. theme: 'mint',
  1170. layout: 'bottomRight',
  1171. type: 'success'
  1172. });
  1173. noty.show();
  1174. }
  1175. parseAppInstancesData(data) {
  1176. let jsonObj = JSON.parse(data);
  1177. var parsed = {};
  1178. let listData = {};
  1179. for (var prop in jsonObj) {
  1180. var name = prop.split('/')[1];
  1181. if (parsed[name]) {
  1182. parsed[name][prop] = jsonObj[prop];
  1183. } else {
  1184. parsed[name] = {};
  1185. parsed[name][prop] = jsonObj[prop];
  1186. }
  1187. }
  1188. //console.log(parsed);
  1189. for (var prop in parsed) {
  1190. var name = prop;
  1191. let obj = Object.entries(parsed[prop]);
  1192. var lists = {};
  1193. obj.forEach(el => {
  1194. if (el[1].loadInfo['save_name']) {
  1195. let saveName = prop + '/load/' + el[1].loadInfo.save_name;
  1196. if (!lists[saveName])
  1197. lists[saveName] = {};
  1198. lists[saveName][el[0]] = el[1]
  1199. } else {
  1200. if (!lists[name])
  1201. lists[name] = {};
  1202. lists[name][el[0]] = el[1]
  1203. }
  1204. });
  1205. // console.log(lists);
  1206. Object.entries(lists).forEach(list => {
  1207. listData[list[0]] = list[1];
  1208. // let element = document.getElementById(list[0] + 'List');
  1209. // if (element) {
  1210. // element._setListData(list[1]);
  1211. // }
  1212. })
  1213. }
  1214. return listData
  1215. // console.log(data)
  1216. }
  1217. async getAllStateWorldsInfoForUser (userAlias) {
  1218. let userPub = await _LCSDB.get('users').get(userAlias).get('pub').once().then();
  1219. var db = _LCSDB.user(userPub);
  1220. if (_LCSUSER.is) {
  1221. if (_LCSUSER.is.alias == userAlias)
  1222. db = _LCSUSER;
  1223. }
  1224. var states = {};
  1225. let worldDocs = await db.get('worlds').once().then();
  1226. if(worldDocs) {
  1227. let protos = Object.keys(worldDocs).filter(el => el !== '_');
  1228. if (protos) {
  1229. for (const el of protos) {
  1230. let info = await this.getSaveStates(userAlias, el);
  1231. if (Object.keys(info).length !== 0)
  1232. states[el] = info;
  1233. }
  1234. }
  1235. }
  1236. return states
  1237. }
  1238. async getAllProtoWorldsInfoForUser(userAlias) {
  1239. let userPub = await _LCSDB.get('users').get(userAlias).get('pub').once().then();
  1240. var db = _LCSDB.user(userPub);
  1241. if (_LCSUSER.is) {
  1242. if (_LCSUSER.is.alias == userAlias)
  1243. db = _LCSUSER;
  1244. }
  1245. var worlds = {};
  1246. let worldDocs = await db.get('worlds').once().then();
  1247. if(worldDocs) {
  1248. let protos = Object.keys(worldDocs).filter(el => el !== '_');
  1249. if (protos) {
  1250. for (const el of protos) {
  1251. let info = await this.getWorldInfo(userAlias, el);
  1252. if (Object.keys(info).length !== 0)
  1253. worlds[el] = info;
  1254. }
  1255. }
  1256. }
  1257. return worlds
  1258. // await db.get('worlds').once(async (proto, index) => {
  1259. // let protos = Object.keys(proto).filter(el => el !== '_');
  1260. // // console.log(protos);
  1261. // if (protos) {
  1262. // for (const el of protos) {
  1263. // let info = await this.getWorldInfo(userAlias, el);
  1264. // worlds[el] = info;
  1265. // }
  1266. // }
  1267. // }).then();
  1268. // return worlds
  1269. }
  1270. async getSaveStates(userAlias, worldName) {
  1271. let userPub = await _LCSDB.get('users').get(userAlias).get('pub').once().then();
  1272. var db = _LCSDB.user(userPub);
  1273. if (_LCSUSER.is) {
  1274. if (_LCSUSER.is.alias == userAlias)
  1275. db = _LCSUSER;
  1276. }
  1277. var states = {};
  1278. let docs = await db.get('documents').get(worldName).once().then();
  1279. if(docs){
  1280. let saves = Object.keys(docs).filter(el => el.includes('_info_vwf_json'));
  1281. if (saves) {
  1282. for (const el of saves) {
  1283. let stateName = el.split('/')[2].replace('_info_vwf_json', "");
  1284. let info = await this.getStateInfo(userAlias, worldName, stateName);
  1285. if (Object.keys(info).length !== 0)
  1286. states[stateName] = info;
  1287. }
  1288. }
  1289. }
  1290. return states
  1291. // return await db.get('documents').get(worldName).once(async (save, index) => {
  1292. // let saves = Object.keys(save).filter(el => el.includes('_info_vwf_json'));
  1293. // //console.log(saves);
  1294. // if (saves) {
  1295. // for (const el of saves) {
  1296. // let stateName = el.split('/')[2].replace('_info_vwf_json', "");
  1297. // let info = await this.getStateInfo(userAlias, worldName, stateName);
  1298. // states[stateName] = info;
  1299. // }
  1300. // }
  1301. // return states
  1302. // }).then();
  1303. // //return states
  1304. }
  1305. async getStateInfo(user, space, saveName) {
  1306. let userPub = await _LCSDB.get('users').get(user).get('pub').once().then();
  1307. var db = _LCSDB.user(userPub);
  1308. if (_LCSUSER.is) {
  1309. if (_LCSUSER.is.alias == user)
  1310. db = _LCSUSER;
  1311. }
  1312. var info = {};
  1313. let docName = 'savestate_/' + space + '/' + saveName + '_info_vwf_json';
  1314. let world = await db.get('documents').get(space).get(docName).once().then();
  1315. if (world) {
  1316. let doc = await db.get('documents').get(space).get(docName).once((res) => {
  1317. if (res && res !== 'null') {
  1318. if (res.file && res.file !== 'null') {
  1319. let worldDesc = JSON.parse(res.file);
  1320. let root = Object.keys(worldDesc)[0];
  1321. var appInfo = worldDesc[root]['en'];
  1322. let langID = localStorage.getItem('krestianstvo_locale');
  1323. if (langID) {
  1324. appInfo = worldDesc[root][langID]
  1325. }
  1326. info = {
  1327. 'worldName': space + '/load/' + saveName,
  1328. 'created': res.created ? res.created : res.modified,
  1329. 'modified': res.modified,
  1330. 'type': 'saveState',
  1331. 'userAlias': user,
  1332. 'info': appInfo
  1333. }
  1334. }
  1335. }
  1336. }).then();
  1337. }
  1338. return info
  1339. }
  1340. async getWorldInfo(user, space) {
  1341. //get space for user
  1342. let userPub = await _LCSDB.get('users').get(user).get('pub').once().then();
  1343. var db = _LCSDB.user(userPub);
  1344. if (_LCSUSER.is) {
  1345. if (_LCSUSER.is.alias == user)
  1346. db = _LCSUSER;
  1347. }
  1348. var info = {};
  1349. let world = await db.get('worlds').get(space).once().then();
  1350. if (world) {
  1351. let doc = await db.get('worlds').get(space).get('info_json').once((res) => {
  1352. if (res && res !== 'null') {
  1353. if (res.file && res.file !== 'null') {
  1354. let worldDesc = JSON.parse(res.file);
  1355. let root = Object.keys(worldDesc)[0];
  1356. var appInfo = worldDesc[root]['en'];
  1357. let langID = localStorage.getItem('krestianstvo_locale');
  1358. if (langID) {
  1359. appInfo = worldDesc[root][langID]
  1360. }
  1361. info = {
  1362. 'worldName': space,
  1363. 'created': res.created ? res.created : res.modified,
  1364. 'modified': res.modified,
  1365. 'type': 'proto',
  1366. 'userAlias': user,
  1367. 'info': appInfo
  1368. }
  1369. }
  1370. }
  1371. }).then();
  1372. }
  1373. return info
  1374. }
  1375. }
  1376. export { App }