app.js 63 KB

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