app.js 64 KB

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