app.js 64 KB

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