app.js 51 KB

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