app.js 65 KB

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