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