app.js 64 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225
  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 = source;//JSON.stringify(source, null, '\t');
  576. }
  577. let el = document.createElement("div");
  578. el.setAttribute("id", "worldFILE");
  579. document.body.appendChild(el);
  580. var saveGUI = {};
  581. if (type == 'proto' || file.includes('_info_vwf_json')) {
  582. saveGUI = {
  583. $type: "button",
  584. class: "mdc-button mdc-button--raised",
  585. $text: "Save",
  586. onclick: async function (e) {
  587. console.log("save new info");
  588. let editor = document.querySelector("#aceEditor").env.editor;
  589. let newInfo = editor.getValue();
  590. _LCSDB.user().get(worldType).get(worldName).get(file).get('file').put(newInfo, function (res) {
  591. if (res) {
  592. let noty = new Noty({
  593. text: 'Saved!',
  594. timeout: 2000,
  595. theme: 'mint',
  596. layout: 'bottomRight',
  597. type: 'success'
  598. });
  599. noty.show();
  600. let modified = new Date().valueOf();
  601. _LCSDB.user().get(worldType).get(worldName).get(file).get('modified').put(modified);
  602. }
  603. })
  604. }
  605. }
  606. }
  607. if (type == 'state' && !file.includes('_info_vwf_json')) {
  608. saveGUI =
  609. {
  610. $type: "div",
  611. class: "",
  612. $components: [
  613. {
  614. $type: "button",
  615. class: "mdc-button mdc-button--raised",
  616. $text: "Replace state",
  617. onclick: async function (e) {
  618. console.log("fix state");
  619. let editor = document.querySelector("#aceEditor").env.editor;
  620. let newInfo = editor.getValue();
  621. let fixedState = newInfo; //_app.fixSaveState(newInfo, worldName, oldProtoName);
  622. let userPub = (await _LCSDB.get('users').get(user).get('pub').promOnce()).data;
  623. let revs = await _app.lookupSaveRevisions(worldName, saveName, userPub);
  624. let lastRevision = revs.sort()[0];
  625. var newFile = file.replace('savestate_', 'savestate_' + lastRevision.toString());
  626. _LCSDB.user().get(worldType).get(worldName).get(file).get('revs').get(newFile).get('jsonState').put(fixedState);
  627. _LCSDB.user().get(worldType).get(worldName).get(file).get('jsonState').put(fixedState, function (res) {
  628. if (res) {
  629. let noty = new Noty({
  630. text: 'Repalced!',
  631. timeout: 2000,
  632. theme: 'mint',
  633. layout: 'bottomRight',
  634. type: 'success'
  635. });
  636. noty.show();
  637. let modified = new Date().valueOf();
  638. _LCSDB.user().get(worldType).get(worldName).get(file).get('modified').put(modified);
  639. }
  640. })
  641. }
  642. }
  643. ]
  644. }
  645. }
  646. let aceEditorCell = {
  647. $type: "div",
  648. $components: [
  649. {
  650. class: "aceEditor",
  651. id: "aceEditor",
  652. //style: "width:1200px; height: 800px",
  653. $type: "div",
  654. $text: source,
  655. $init: function () {
  656. var mode = "ace/mode/json";
  657. if (file.includes('_yaml'))
  658. mode = "ace/mode/yaml"
  659. if (file.includes('_js'))
  660. mode = "ace/mode/javascript"
  661. var editor = ace.edit("aceEditor");
  662. editor.setTheme("ace/theme/monokai");
  663. editor.setFontSize(16);
  664. editor.getSession().setMode(mode);
  665. editor.setOptions({
  666. maxLines: Infinity
  667. });
  668. editor.session.setUseWrapMode(true);
  669. }
  670. },
  671. saveGUI,
  672. {
  673. $type: "button",
  674. class: "mdc-button mdc-button--raised",
  675. $text: "Close",
  676. onclick: function (e) {
  677. console.log("close");
  678. //window.location.pathname = "/" + user + '/' + worldName + '/about'
  679. window.history.back();
  680. // if (type == "proto")
  681. // window.location.pathname = "/" + user + '/' + worldName + '/about'
  682. // if (type == "state")
  683. // window.location.pathname = "/" + user + '/' + worldName + '/about'
  684. }
  685. }
  686. ]
  687. }
  688. document.querySelector("#worldFILE").$cell({
  689. $cell: true,
  690. $type: "div",
  691. $components: [aceEditorCell
  692. ]
  693. })
  694. }
  695. });
  696. }
  697. }
  698. })
  699. }
  700. async HandleUserWorldsWithType(ctx) {
  701. console.log("USER WORLDS INDEX");
  702. console.log(ctx.params);
  703. let user = ctx.params.user;
  704. let type = ctx.params.type;
  705. window._app.hideProgressBar();
  706. window._app.hideUIControl();
  707. if (!_app.indexApp) {
  708. _app.indexApp = new IndexApp;
  709. _app.indexApp.initHTML();
  710. _app.indexApp.initApp();
  711. }
  712. if (type == 'protos') {
  713. await _app.indexApp.initWorldsProtosListForUser(user)//.getWorldsProtosListForUser(user);
  714. } else if (type == 'states') {
  715. await _app.indexApp.initWorldsStatesListForUser(user);
  716. //await _app.indexApp.getWorldsFromUserDB(user);
  717. }
  718. }
  719. async HandleIndex() {
  720. console.log("INDEX");
  721. window._app.hideProgressBar();
  722. window._app.hideUIControl();
  723. if (!_app.indexApp) {
  724. _app.indexApp = new IndexApp;
  725. await _app.indexApp.generateFrontPage();
  726. _app.indexApp.initHTML();
  727. }
  728. _app.indexApp.initApp();
  729. _LCSDB.get('~@app').once(res=>{
  730. if (res){
  731. _app.indexApp.initWorldsProtosListForUser('app');
  732. }
  733. })
  734. //await _app.indexApp.getAppDetailsFromDB();
  735. }
  736. HandleNoPage() {
  737. console.log("no such page")
  738. }
  739. //handle parcable requests
  740. HandleParsableLoadRequest(ctx) {
  741. let app = window._app;
  742. console.log(ctx.params);
  743. //var pathname = ctx.pathname;
  744. var spaceName = ctx.params.space;
  745. var saveName = ctx.params.savename;
  746. let user = ctx.params.user;
  747. page.redirect('/' + user + '/' + spaceName + '/' + app.helpers.GenerateInstanceID() + '/load/' + saveName);
  748. }
  749. HandleParsableLoadRequestWithRev(ctx) {
  750. let app = window._app;
  751. console.log(ctx.params);
  752. //var pathname = ctx.pathname;
  753. var spaceName = ctx.params.space;
  754. var saveName = ctx.params.savename;
  755. var rev = ctx.params.rev;
  756. let user = ctx.params.user;
  757. page.redirect('/' + user + '/' + spaceName + '/' + app.helpers.GenerateInstanceID() + '/load/' + saveName + '/' + rev);
  758. }
  759. async setUserPaths(user) {
  760. let users = _LCSDB.get('users');
  761. await _LCSDB.get('users').get(user).get('pub').then(function (res) {
  762. if (res)
  763. window._LCS_WORLD_USER = {
  764. alias: user,
  765. pub: res
  766. }
  767. })
  768. // await _LCSDB.get('users').get(user).get('pub').once(res => {
  769. // if (res)
  770. // window._LCS_WORLD_USER = _LCSDB.user(res);
  771. // }).then();
  772. }
  773. HandleParsableRequestGenID(ctx) {
  774. let app = window._app;
  775. console.log(ctx.params);
  776. let user = ctx.params.user;
  777. var pathname = ctx.pathname;
  778. //await app.setUserPaths(user);
  779. _LCSDB.get('users').get(user).get('pub').once(function (res) {
  780. if (res)
  781. window._LCS_WORLD_USER = {
  782. alias: user,
  783. pub: res
  784. }
  785. if (pathname[pathname.length - 1] == '/') {
  786. pathname = pathname.slice(0, -1)
  787. }
  788. let pathToParse = pathname.replace('/' + user, "");
  789. app.helpers.Process(pathToParse).then(parsedRequest => {
  790. localStorage.setItem('lcs_app', JSON.stringify({ path: parsedRequest }));
  791. console.log(parsedRequest);
  792. if ((parsedRequest['instance'] == undefined) && (parsedRequest['private_path'] == undefined) && (parsedRequest['public_path'] !== "/") && (parsedRequest['application'] !== undefined)) {
  793. //page.redirect(pathname + '/' + app.helpers.GenerateInstanceID());
  794. window.location.pathname = pathname + '/' + app.helpers.GenerateInstanceID()
  795. }
  796. })
  797. })
  798. }
  799. HandleParsableRequestWithID(ctx) {
  800. let app = window._app;
  801. console.log(ctx.params);
  802. var pathname = ctx.pathname;
  803. let user = ctx.params.user;
  804. if (pathname[pathname.length - 1] == '/') {
  805. pathname = pathname.slice(0, -1)
  806. }
  807. //await app.setUserPaths(user);
  808. _LCSDB.get('users').get(user).get('pub').once(function (res) {
  809. if (res)
  810. window._LCS_WORLD_USER = {
  811. alias: user,
  812. pub: res
  813. }
  814. let pathToParse = pathname.replace('/' + user, "");
  815. app.helpers.Process(pathToParse).then(parsedRequest => {
  816. localStorage.setItem('lcs_app', JSON.stringify({ path: parsedRequest }));
  817. var userLibraries = { model: {}, view: {} };
  818. var application;
  819. vwf.loadConfiguration(application, userLibraries, compatibilityCheck);
  820. })
  821. })
  822. }
  823. //get DB application state information for reflector (called from VWF)
  824. async getApplicationState() {
  825. let dataJson = JSON.parse(localStorage.getItem('lcs_app'));
  826. if (dataJson) {
  827. if (!dataJson.path['instance']) return undefined;
  828. }
  829. //let userAlias = await _LCS_WORLD_USER.get('alias').once().then();
  830. // let userPub = await _LCSDB.get('users').get(userAlias).get('pub').once().then();
  831. let userAlias = _LCS_WORLD_USER.alias;
  832. let userPub = _LCS_WORLD_USER.pub;
  833. let loadInfo = await this.getLoadInformation(dataJson);
  834. let saveInfo = await this.loadSaveObject(loadInfo);
  835. let loadObj = {
  836. loadInfo: loadInfo,
  837. path: dataJson.path,
  838. saveObject: saveInfo,
  839. user: userAlias
  840. }
  841. //dataJson.app = loadObj;
  842. localStorage.setItem('lcs_app', JSON.stringify(loadObj));
  843. console.log(loadObj);
  844. //temporary solution for syncing DB replicas using Gun.load()
  845. // _LCS_SYS_USER.get('proxy').load(res=>{
  846. // if (res)
  847. // {console.log('proxy loaded');
  848. // _LCSDB.user(userPub).get('worlds').get(loadObj.path.public_path.slice(1)).load(w=>{
  849. // if (w) {
  850. // console.log('world files loaded');
  851. // vwf.ready( vwf.application, loadObj)
  852. // }
  853. // });
  854. // }
  855. // });
  856. return loadObj
  857. }
  858. // LookupSaveRevisions takes the public path and the name of a save, and provides
  859. // an array of all revisions for that save. (If the save does not exist, this will be
  860. // an empty array).
  861. async lookupSaveRevisions(public_path, save_name, userPub) {
  862. var pub = "";
  863. if (!_LCS_WORLD_USER) {
  864. pub = userPub;
  865. } else {
  866. pub = _LCS_WORLD_USER.pub
  867. }
  868. let userDB = _LCSDB.user(pub);
  869. var result = [];
  870. var states = [];
  871. let docName = 'savestate_/' + public_path + '/' + save_name + '_vwf_json';
  872. let revs = await userDB.get('documents').get(public_path).get(docName).get('revs').promOnce();
  873. if (revs) {
  874. for (const res of Object.keys(revs.data)) {
  875. if (res !== '_') {
  876. let el = await userDB.get('documents').get(public_path).get(docName).get('revs').get(res).promOnce();
  877. if (el)
  878. result.push(parseInt(el.data.revision));
  879. }
  880. }
  881. return result
  882. }
  883. }
  884. // GetLoadInformation receives a parsed request {private_path, public_path, instance, application} and returns the
  885. // details of the save that is designated by the initial request. The details are returned in an object
  886. // composed of: save_name (name of the save) save_revision (revision of the save), explicit_revision (boolean, true if the request
  887. // explicitly specified the revision, false if it did not), and application_path (the public_path of the application this is a save for).
  888. async getLoadInformation(response) {
  889. let parsedRequest = response.path;
  890. var result = { 'save_name': undefined, 'save_revision': undefined, 'explicit_revision': undefined, 'application_path': undefined };
  891. if (parsedRequest['private_path']) {
  892. var segments = this.helpers.GenerateSegments(parsedRequest['private_path']);
  893. if ((segments.length > 1) && (segments[0] == "load")) {
  894. var potentialRevisions = await this.lookupSaveRevisions((parsedRequest['public_path']).slice(1), segments[1]);
  895. console.log('!!!!! - ', potentialRevisions);
  896. if (potentialRevisions.length > 0) {
  897. result['save_name'] = segments[1];
  898. if (segments.length > 2) {
  899. var requestedRevision = parseInt(segments[2]);
  900. if (requestedRevision) {
  901. if (potentialRevisions.indexOf(requestedRevision) > -1) {
  902. result['save_revision'] = requestedRevision;
  903. result['explicit_revision'] = true;
  904. result['application_path'] = parsedRequest['public_path'];
  905. }
  906. }
  907. }
  908. if (result['explicit_revision'] == undefined) {
  909. result['explicit_revision'] = false;
  910. potentialRevisions.sort();
  911. result['save_revision'] = potentialRevisions.pop();
  912. result['application_path'] = parsedRequest['public_path'];
  913. }
  914. }
  915. }
  916. }
  917. return result;
  918. }
  919. async loadSaveObject(loadInfo) {
  920. //let objName = loadInfo[ 'save_name' ] +'/'+ "savestate_" + loadInfo[ 'save_revision' ];
  921. let userDB = _LCSDB.user(_LCS_WORLD_USER.pub);
  922. if (!loadInfo.save_name) {
  923. return undefined
  924. }
  925. let objName = "savestate_" + loadInfo['application_path'] + '/' + loadInfo['save_name'] + '_vwf_json';
  926. let objNameRev = "savestate_" + loadInfo['save_revision'] + loadInfo['application_path'] + '/' + loadInfo['save_name'] + '_vwf_json';
  927. // if(loadInfo[ 'save_revision' ]){
  928. // }
  929. let worldName = this.helpers.appPath //loadInfo[ 'application_path' ].slice(1);
  930. let saveObject = (await userDB.get('documents').get(worldName).get(objName).get('revs').get(objNameRev).promOnce()).data;
  931. var saveInfo = null;
  932. if (saveObject) {
  933. saveInfo = (typeof (saveObject.jsonState) == 'object') ? saveObject.jsonState : JSON.parse(saveObject.jsonState);
  934. }
  935. //typeof(saveObject == 'object')
  936. return saveInfo;
  937. }
  938. // GetSaveInformation is a helper function that takes the application_path (/path/to/application).
  939. // It returns an array of all saves found for that
  940. // application (including separate entries for individual revisions of saves ).
  941. async getSaveInformation(application_path, userPUB) {
  942. var result = [];
  943. let user = _LCSDB.user(userPUB);
  944. var docName = application_path.slice(1);
  945. let potentialSaveNames = (await user.get('documents').get(docName).promOnce()).data;
  946. if (potentialSaveNames) {
  947. for (const res of Object.keys(potentialSaveNames)) {
  948. if (res !== '_') {
  949. let el = (await user.get('documents').path(docName).get(res).promOnce()).data;
  950. let revisionList = await this.lookupSaveRevisions(application_path.slice(1), el.filename);
  951. var latestsave = true;
  952. revisionList.sort();
  953. while (revisionList.length > 0) {
  954. var newEntry = {};
  955. newEntry['applicationpath'] = application_path;
  956. newEntry['savename'] = el.filename;
  957. newEntry['revision'] = revisionList.pop().toString();
  958. newEntry['latestsave'] = latestsave;
  959. if (latestsave) {
  960. newEntry['url'] = this.helpers.JoinPath(window.location.origin, application_path, "load", el.filename + "/");
  961. }
  962. else {
  963. newEntry['url'] = this.helpers.JoinPath(window.location.origin, application_path, "load", el.filename + "/", newEntry['revision'] + "/");
  964. }
  965. latestsave = false;
  966. result.push(newEntry);
  967. }
  968. }
  969. }
  970. }
  971. return result;
  972. }
  973. async getProtoWorldFiles(userPub, worldName, date) {
  974. let fileNamesAll = (await _LCSDB.user(userPub).get('worlds').get(worldName).promOnce()).data;
  975. 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'));
  976. let worldObj = {};
  977. for (var doc in worldFileNames) {
  978. let fn = worldFileNames[doc];
  979. let res = (await _LCSDB.user(userPub).get('worlds').get(worldName).get(fn).promOnce()).data;
  980. var data = {
  981. 'file': res.file,
  982. 'modified': res.modified,
  983. 'created': res.created
  984. }
  985. if (!date) {
  986. data = {
  987. 'file': res.file
  988. }
  989. }
  990. worldObj[fn] = data;
  991. }
  992. console.log(worldObj);
  993. return worldObj
  994. }
  995. async cloneWorldPrototype(worldName, userName, newWorldName, stateFileName) {
  996. let self = this;
  997. _app.showProgressBar();
  998. //let users = await _LCSDB.get('users').then();
  999. let userPub = (await _LCSDB.get('users').get(userName).get('pub').promOnce()).data;
  1000. let newOwner = _LCSDB.user().is.pub;
  1001. let myWorlds = (await _LCSDB.user(newOwner).get('worlds').promOnce()).data;
  1002. //if (!myWorlds) _LCSDB.user(newOwner).get('worlds').put({});
  1003. _LCSDB.user(newOwner).get('worlds').not(res=>{
  1004. _LCSDB.user(newOwner).get('worlds').put({});
  1005. })
  1006. if(myWorlds) {
  1007. let checkExist = Object.keys(myWorlds).filter(el=> el == newWorldName);
  1008. if (newWorldName) {
  1009. //let worldProto = (await _LCSDB.user(newOwner).get('worlds').get(newWorldName).promOnce()).data;
  1010. if (checkExist.length > 0 && myWorlds[newWorldName]) {
  1011. console.log('already exist!');
  1012. return
  1013. }
  1014. }
  1015. }
  1016. var worldID = window._app.helpers.GenerateInstanceID().toString();
  1017. if (newWorldName) {
  1018. worldID = newWorldName
  1019. }
  1020. //let modified = new Date().valueOf();
  1021. console.log('clone: ' + worldName + 'to: ' + worldID);
  1022. let created = new Date().valueOf();
  1023. let worldObj = {
  1024. 'owner': newOwner,
  1025. 'parent': userName + '/' + worldName,
  1026. 'featured': true,
  1027. 'published': true
  1028. };
  1029. // let fileNamesAll =
  1030. await _LCSDB.user(userPub).get('worlds').get(worldName).load(all=> {
  1031. let worldFileNames = Object.keys(all).filter(el => (el !== '_') && (el !== 'owner') && (el !== 'parent') && (el !== 'featured') && (el !== 'published') && (el !== '_config_yaml') && (el !== '_yaml') && (el !== '_html'));
  1032. for (var doc in worldFileNames) {
  1033. let fn = worldFileNames[doc];
  1034. let res = all[fn]; //(await _LCSDB.user(userPub).get('worlds').get(worldName).get(fn).promOnce()).data;
  1035. let data = {
  1036. 'file': res.file, //JSON.stringify(res.file),
  1037. 'modified': created
  1038. }
  1039. worldObj[fn] = data;
  1040. }
  1041. console.log(worldObj);
  1042. // for (const obj of Object.keys(worldObj)) {
  1043. // let myWorlds = _LCSDB.user().get('worlds');
  1044. // let myNewWorld = myWorlds.get(worldID);
  1045. // myNewWorld.get(obj).put(worldObj[obj]);
  1046. // }
  1047. //let myWorlds = await _LCSDB.user(newOwner).get('worlds').once().then();
  1048. let myWorld = _LCSDB.user(newOwner).get('worlds').get(worldID).put({});
  1049. myWorld.put(worldObj, function (res) {
  1050. if(stateFileName){
  1051. self.saveStateAsFile(stateFileName)
  1052. }
  1053. console.log(res)
  1054. }); //.get(worldID) let myWorld =
  1055. // let myWorld = _LCSDB.user().get(worldID).put(worldObj);
  1056. // _LCSDB.user().get('worlds').set(myWorld);
  1057. _app.hideProgressBar();
  1058. console.log('CLONED!!!');
  1059. let appEl = document.createElement("div");
  1060. appEl.setAttribute("id", 'cloneLink');
  1061. let entry = document.querySelector('#worldActionsGUI');
  1062. if (entry) {
  1063. entry.appendChild(appEl);
  1064. document.querySelector("#cloneLink").$cell({
  1065. id: 'cloneLink',
  1066. $cell: true,
  1067. $type: "div",
  1068. $components: [
  1069. {
  1070. $type: "a",
  1071. class: "mdc-button mdc-button--raised mdc-card__action",
  1072. $text: "Go to new cloned World!",
  1073. onclick: function (e) {
  1074. let myName = _LCSDB.user().is.alias;
  1075. window.location.pathname = '/' + myName + '/' + worldID + '/about'
  1076. }
  1077. }
  1078. ]
  1079. })
  1080. }
  1081. },{wait: 500}).then();
  1082. //window.location.pathname = '/' + userName + '/' + worldID + '/about'
  1083. //page()
  1084. // Object.keys(worldObj).forEach(el => {
  1085. // this.db.user().get('worlds').get(worldID).get(el).put(worldObj[el]);
  1086. // })
  1087. }
  1088. async cloneWorldState(filename) {
  1089. let myWorldProtos = (await _LCSDB.user().get('worlds').promOnce()).data;
  1090. let userName = this.helpers.worldUser;
  1091. // let users = await _LCSDB.get('users').then();
  1092. let userPub = (await _LCSDB.get('users').get(userName).get('pub').promOnce()).data;
  1093. let protoUserRoot = this.helpers.getRoot(true).root;
  1094. //let myName = this.db.user().is.alias;
  1095. //let proto = Object.keys(myWorldProtos).filter(el => el == protoUserRoot);
  1096. var protosKeys = [];
  1097. if (myWorldProtos)
  1098. protosKeys = Object.keys(myWorldProtos);
  1099. if (protosKeys.includes(protoUserRoot) && myWorldProtos[protoUserRoot]) {
  1100. let userProtoFiles = await this.getProtoWorldFiles(userPub, protoUserRoot);
  1101. let myProtoFiles = await this.getProtoWorldFiles(_LCSDB.user().is.pub, protoUserRoot);
  1102. let hashUP = await this.helpers.sha256(JSON.stringify(userProtoFiles));
  1103. let hashMP = await this.helpers.sha256(JSON.stringify(myProtoFiles));
  1104. if (hashUP == hashMP) {
  1105. this.saveStateAsFile(filename);
  1106. } else {
  1107. let noty = new Noty({
  1108. text: 'world prototype is modified.. could not clone world state',
  1109. timeout: 2000,
  1110. theme: 'mint',
  1111. layout: 'bottomRight',
  1112. type: 'error'
  1113. });
  1114. noty.show();
  1115. }
  1116. } else {
  1117. await this.cloneWorldPrototype(protoUserRoot, userName, protoUserRoot, filename);
  1118. //this.saveStateAsFile(filename);
  1119. }
  1120. }
  1121. //TODO: refactor and config save
  1122. async saveStateAsFile(filename, otherProto) // invoke with the view as "this"
  1123. {
  1124. console.log("Saving: " + filename);
  1125. //var clients = this.nodes["http://vwf.example.com/clients.vwf"];
  1126. // Save State Information
  1127. var state = vwf.getState();
  1128. state.nodes[0].children = {};
  1129. var timestamp = state["queue"].time;
  1130. timestamp = Math.round(timestamp * 1000);
  1131. let jsonValuePure = _app.helpers.replaceFloatArraysInNodeDef(state);
  1132. //remove all Ohm generated grammarsfrom state
  1133. let jsonValue = _app.helpers.removeGrammarObj(jsonValuePure);
  1134. var jsonState = JSON.stringify(jsonValue, null, '\t'); //JSON.stringify(jsonValue);
  1135. let rootPath = this.helpers.getRoot(true);
  1136. var inst = rootPath.inst;
  1137. if (filename == '') filename = inst;
  1138. //if (root.indexOf('.vwf') != -1) root = root.substring(0, root.lastIndexOf('/'));
  1139. var root = rootPath.root;
  1140. var json = jsonState;
  1141. if (otherProto) {
  1142. console.log('need to modify state...');
  1143. json = this.helpers.replaceSubStringALL(jsonState, '/' + root + '/', '/' + otherProto + '/');//jsonState.replace(('/' + root + '/'), ('/' + otherProto +'/') );
  1144. root = otherProto;
  1145. console.log(json);
  1146. }
  1147. //var documents = this.db.user().get('documents');
  1148. var saveRevision = new Date().valueOf();
  1149. var stateForStore = {
  1150. "root": root,
  1151. "filename": filename,
  1152. "inst": inst,
  1153. "timestamp": timestamp,
  1154. "extension": ".vwf.json",
  1155. "jsonState": json,
  1156. "publish": true
  1157. };
  1158. let rev = JSON.stringify(saveRevision);
  1159. var docNameRev = 'savestate_' + rev + '/' + root + '/' + filename + '_vwf_json';
  1160. let stateWithRev = Object.assign({}, stateForStore);
  1161. stateWithRev.revs = { [docNameRev]: stateForStore };
  1162. stateWithRev.revs[docNameRev].revision = saveRevision;
  1163. //let objName = loadInfo[ 'save_name' ] +'/'+ "savestate_" + loadInfo[ 'save_revision' ];
  1164. // "savestate_" + loadInfo[ 'save_revision' ] + '/' + loadInfo[ 'save_name' ] + '_vwf_json'
  1165. var docName = 'savestate_/' + root + '/' + filename + '_vwf_json';
  1166. let myNewWorldState = _LCSDB.user().get('documents').get(root).get(docName).put({});
  1167. //_LCSDB.user().get('documents').get(root).get(docName).put(stateWithRev, function(res) {
  1168. myNewWorldState.put(stateWithRev, function (res) {
  1169. if (res) {
  1170. let noty = new Noty({
  1171. text: 'Saved to ' + docName,
  1172. timeout: 2000,
  1173. theme: 'mint',
  1174. layout: 'bottomRight',
  1175. type: 'success'
  1176. });
  1177. noty.show();
  1178. }
  1179. });
  1180. // let docInfo = await _LCSDB.user().get('worlds').get(root).get('info_json').get('file').then();
  1181. _LCSDB.user().get('worlds').get(root).get('info_json').get('file').once(function (file) {
  1182. if (file) {
  1183. let modified = saveRevision;
  1184. let newOwner = _LCSDB.user().is.pub;
  1185. let userName = _LCSDB.user().is.alias;
  1186. let obj = {
  1187. 'parent': userName + '/' + root,
  1188. 'owner': newOwner,
  1189. 'file': file, //JSON.stringify(file),
  1190. //'modified': modified,
  1191. 'created': modified
  1192. }
  1193. let docInfoName = 'savestate_/' + root + '/' + filename + '_info_vwf_json';
  1194. _LCSDB.user().get('documents').get(root).get(docInfoName).get('file').not(function (res) {
  1195. _LCSDB.user().get('documents').get(root).get(docInfoName).put(obj);
  1196. });
  1197. _LCSDB.user().get('documents').get(root).get(docInfoName).get('created').not(function (res) {
  1198. _LCSDB.user().get('documents').get(root).get(docInfoName).get('created').put(modified);
  1199. });
  1200. _LCSDB.user().get('documents').get(root).get(docInfoName).get('modified').put(modified);
  1201. }
  1202. });
  1203. // Save Config Information
  1204. var config = { "info": {}, "model": {}, "view": {} };
  1205. // Save browser title
  1206. config["info"]["title"] = document.title//$('title').html();
  1207. // Save model drivers
  1208. Object.keys(vwf_view.kernel.kernel.models).forEach(function (modelDriver) {
  1209. if (modelDriver.indexOf('vwf/model/') != -1) config["model"][modelDriver] = "";
  1210. });
  1211. // If neither glge or threejs model drivers are defined, specify nodriver
  1212. if (config["model"]["vwf/model/glge"] === undefined && config["model"]["vwf/model/threejs"] === undefined) config["model"]["nodriver"] = "";
  1213. // Save view drivers and associated parameters, if any
  1214. Object.keys(vwf_view.kernel.kernel.views).forEach(function (viewDriver) {
  1215. if (viewDriver.indexOf('vwf/view/') != -1) {
  1216. if (vwf_view.kernel.kernel.views[viewDriver].parameters) {
  1217. config["view"][viewDriver] = vwf_view.kernel.kernel.views[viewDriver].parameters;
  1218. }
  1219. else config["view"][viewDriver] = "";
  1220. }
  1221. });
  1222. //var jsonConfig = $.encoder.encodeForURL(JSON.stringify(config));
  1223. var jsonConfig = JSON.stringify(config);
  1224. let configStateForStore = {
  1225. "root": root,
  1226. "filename": filename,
  1227. "inst": inst,
  1228. "timestamp": timestamp,
  1229. "extension": "config.vwf.json",
  1230. "jsonState": jsonConfig
  1231. };
  1232. //let objName = loadInfo[ 'save_name' ] +'/'+ "savestate_" + loadInfo[ 'save_revision' ];
  1233. // "savestate_" + loadInfo[ 'save_revision' ] + '/' + loadInfo[ 'save_name' ] + '_vwf_json'
  1234. // let configName = 'savestate_/' + root + '/' + filename + '_config_vwf_json';
  1235. // let documentSaveConfigState = this.db.user().get(configName).put(configStateForStore);
  1236. // //documents.path(root).set(documentSaveConfigState);
  1237. // let configNameRev = 'savestate_' + saveRevision.toString() + '/' + root + '/' + filename + '_config_vwf_json';
  1238. // this.db.user().get(configNameRev).put(configStateForStore);
  1239. // this.db.user().get(configNameRev).path("revision").put(saveRevision);
  1240. //documentSaveConfigState.path('revs').set(documentSaveStateRevision);
  1241. // Save config file to server
  1242. // var xhrConfig = new XMLHttpRequest();
  1243. // xhrConfig.open("POST", "/" + root + "/save/" + filename, true);
  1244. // xhrConfig.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  1245. // xhrConfig.send("root=" + root + "/" + filename + "&filename=saveState&inst=" + inst + "&timestamp=" + timestamp + "&extension=.vwf.config.json" + "&jsonState=" + jsonConfig);
  1246. }
  1247. fixSaveState(jsonState, otherProto, oldProtoName) {
  1248. console.log('fix proto in state...');
  1249. let json = this.helpers.replaceSubStringALL(jsonState, '/' + oldProtoName + '/', '/' + otherProto + '/');//jsonState.replace(('/' + root + '/'), ('/' + otherProto +'/') );
  1250. console.log(json);
  1251. return json
  1252. }
  1253. // LoadSavedState
  1254. async loadSavedState(filename, applicationpath, revision) {
  1255. console.log("Loading: " + filename);
  1256. let userDB = _LCSDB.user(_LCS_WORLD_USER.pub);
  1257. let userName = (await userDB.get('alias').promOnce()).data;
  1258. if (revision) {
  1259. window.location.pathname = '/' + userName + applicationpath + '/load/' + filename + '/' + revision + '/';
  1260. }
  1261. else { // applicationpath + "/" + inst + '/load/' + filename + '/';
  1262. window.location.pathname = '/' + userName + applicationpath + '/load/' + filename + '/';
  1263. }
  1264. }
  1265. hideUIControl() {
  1266. let el = document.getElementById("ui-controls");
  1267. if (el) {
  1268. el.classList.remove("visible");
  1269. el.classList.add("not-visible");
  1270. }
  1271. }
  1272. showUIControl() {
  1273. let el = document.getElementById("ui-controls");
  1274. if (el) {
  1275. el.classList.remove("not-visible");
  1276. el.classList.add("visible");
  1277. }
  1278. }
  1279. hideProgressBar() {
  1280. var progressbar = document.getElementById("load-progressbar");
  1281. if (progressbar) {
  1282. progressbar.classList.remove("visible");
  1283. progressbar.classList.remove("mdc-linear-progress--indeterminate");
  1284. progressbar.classList.add("not-visible");
  1285. progressbar.classList.add("mdc-linear-progress--closed");
  1286. }
  1287. }
  1288. showProgressBar() {
  1289. let progressbar = document.getElementById("load-progressbar");
  1290. if (progressbar) {
  1291. progressbar.classList.remove("not-visible");
  1292. progressbar.classList.remove("mdc-linear-progress--closed");
  1293. progressbar.classList.add("visible");
  1294. progressbar.classList.add("mdc-linear-progress--indeterminate");
  1295. }
  1296. }
  1297. // SUPPORT of DELETE USER WORLDS & SAVE STATES (experimental)
  1298. // TODO: manual garbage collection
  1299. async deleteWorldState(worldName, indexState) {
  1300. let revs = (await _LCSDB.user().get('documents').get(worldName).get(indexState).get('revs').promOnce()).data;
  1301. if (revs) {
  1302. for (const el of Object.keys(revs)) {
  1303. if (el !== '_') {
  1304. let doc = (await _LCSDB.user().get('documents').get(worldName).get(indexState).get('revs').get(el).promOnce()).data;
  1305. for (const rev of Object.keys(doc)) {
  1306. if (rev !== '_') {
  1307. await _LCSDB.user().get('documents').get(worldName).get(indexState).get('revs').get(el).get(rev).put(null).promOnce();
  1308. }
  1309. }
  1310. await _LCSDB.user().get('documents').get(worldName).get(indexState).get('revs').get(el).put(null).promOnce();
  1311. }
  1312. }
  1313. }
  1314. // clear all state params
  1315. let stateDoc = (await _LCSDB.user().get('documents').get(worldName).get(indexState).promOnce()).data;
  1316. for (const state of Object.keys(stateDoc)) {
  1317. if (state !== '_' && state !== 'revs') {
  1318. await _LCSDB.user().get('documents').get(worldName).get(indexState).get(state).put(null).promOnce();
  1319. }
  1320. }
  1321. await _LCSDB.user().get('documents').get(worldName).get(indexState).get('revs').put(null).promOnce();
  1322. await _LCSDB.user().get('documents').get(worldName).get(indexState).put(null).promOnce();
  1323. }
  1324. async deleteWorld(name, type) {
  1325. if (type == 'proto') {
  1326. let worldName = name;
  1327. //TODO check for states (ask for deleting all states first...)
  1328. //delete states
  1329. let documents = (await _LCSDB.user().get('documents').promOnce()).data;
  1330. if (documents) {
  1331. let states = (await _LCSDB.user().get('documents').get(worldName).promOnce()).data;
  1332. if (states) {
  1333. for (const st of Object.keys(states)) {
  1334. if (st !== '_') {
  1335. if (states[st]) {
  1336. await this.deleteWorldState(worldName, st);
  1337. }
  1338. }
  1339. }
  1340. }
  1341. }
  1342. let worldFiles = (await _LCSDB.user().get('worlds').get(worldName).promOnce()).data;
  1343. if (worldFiles) {
  1344. for (const el of Object.keys(worldFiles)) {
  1345. if (el !== '_') {
  1346. let doc = (await _LCSDB.user().get('worlds').get(worldName).get(el).promOnce()).data;
  1347. if (doc) {
  1348. if (doc.file) {
  1349. for (const fEl of Object.keys(doc)) {
  1350. if (fEl !== '_') {
  1351. await _LCSDB.user().get('worlds').get(worldName).get(el).get(fEl).put(null).promOnce();
  1352. }
  1353. }
  1354. await _LCSDB.user().get('worlds').get(worldName).get(el).put(null).promOnce();
  1355. } else {
  1356. await _LCSDB.user().get('worlds').get(worldName).get(el).put(null).promOnce()
  1357. }
  1358. }
  1359. }
  1360. }
  1361. }
  1362. // this.db.user().get('worlds').get(worldName).map((res, index) => {
  1363. // if(typeof res == 'object'){
  1364. // this.db.user().get('worlds').get(worldName).get(index)
  1365. // .get('file').put("null")
  1366. // .back(1)
  1367. // .get('modified').put("null")
  1368. // .back(1)
  1369. // .get('created').put("null")
  1370. // .back(1).put("null")
  1371. // } else {
  1372. // this.db.user().get('worlds').get(worldName).get(index).put("null")
  1373. // }
  1374. // })
  1375. await _LCSDB.user().get('worlds').get(worldName).put(null).promOnce();
  1376. } else if (type == 'state') {
  1377. let worldName = name.split('/')[0];
  1378. let stateName = name.split('/')[2];
  1379. let stateEntryInfo = 'savestate_/' + worldName + '/' + stateName + '_info_vwf_json';
  1380. let stateEntry = 'savestate_/' + worldName + '/' + stateName + '_vwf_json';
  1381. await this.deleteWorldState(worldName, stateEntryInfo);
  1382. await this.deleteWorldState(worldName, stateEntry);
  1383. }
  1384. let noty = new Noty({
  1385. text: "World Deleted!",
  1386. timeout: 2000,
  1387. theme: 'mint',
  1388. layout: 'bottomRight',
  1389. type: 'success'
  1390. });
  1391. noty.show();
  1392. }
  1393. parseAppInstancesData(data) {
  1394. let jsonObj = JSON.parse(data);
  1395. var parsed = {};
  1396. let listData = {};
  1397. for (var prop in jsonObj) {
  1398. var name = prop.split('/')[1];
  1399. if (parsed[name]) {
  1400. parsed[name][prop] = jsonObj[prop];
  1401. } else {
  1402. parsed[name] = {};
  1403. parsed[name][prop] = jsonObj[prop];
  1404. }
  1405. }
  1406. //console.log(parsed);
  1407. for (var prop in parsed) {
  1408. var name = prop;
  1409. let obj = Object.entries(parsed[prop]);
  1410. var lists = {};
  1411. obj.forEach(el => {
  1412. if (el[1].loadInfo['save_name']) {
  1413. let saveName = prop + '/load/' + el[1].loadInfo.save_name;
  1414. if (!lists[saveName])
  1415. lists[saveName] = {};
  1416. lists[saveName][el[0]] = el[1]
  1417. } else {
  1418. if (!lists[name])
  1419. lists[name] = {};
  1420. lists[name][el[0]] = el[1]
  1421. }
  1422. });
  1423. // console.log(lists);
  1424. Object.entries(lists).forEach(list => {
  1425. listData[list[0]] = list[1];
  1426. })
  1427. }
  1428. return listData
  1429. // console.log(data)
  1430. }
  1431. async getAllStateWorldsInfoForUser(userAlias, cb) {
  1432. //let users = await _LCSDB.get('users').then();
  1433. let userPub = (await _LCSDB.get('users').get(userAlias).get('pub').promOnce()).data;
  1434. var db = _LCSDB.user(userPub);
  1435. if (_LCSDB.user().is) {
  1436. if (_LCSDB.user().is.alias == userAlias)
  1437. db = _LCSDB.user();
  1438. }
  1439. //let myWorlds = (await db.get('documents').promOnce()).data;
  1440. db.get('documents').load(myWorlds => {
  1441. if (myWorlds) {
  1442. Object.keys(myWorlds).filter(el => el !== '_').forEach(w => {
  1443. db.get('documents').get(w).map(function (res, datI) {
  1444. var doc = {};
  1445. if (datI.includes('_info_vwf_json')) {
  1446. if (res && res !== 'null') {
  1447. if (res.file && res.file !== 'null') {
  1448. let saveName = datI.split('/')[2].replace('_info_vwf_json', "");
  1449. // let worldDesc = JSON.parse(res.file);
  1450. var worldDesc = {};
  1451. if (typeof (res.file) == 'object') {
  1452. worldDesc = res.file
  1453. } else {
  1454. worldDesc = JSON.parse(res.file)
  1455. }
  1456. let root = Object.keys(worldDesc)[0];
  1457. var appInfo = worldDesc[root]['en'];
  1458. let langID = localStorage.getItem('krestianstvo_locale');
  1459. if (langID) {
  1460. appInfo = worldDesc[root][langID]
  1461. }
  1462. doc = {
  1463. 'worldName': w + '/load/' + saveName,
  1464. 'created': res.created ? res.created : res.modified,
  1465. 'modified': res.modified,
  1466. 'type': 'saveState',
  1467. 'userAlias': userAlias,
  1468. 'info': appInfo
  1469. }
  1470. }
  1471. }
  1472. }
  1473. if (Object.keys(doc).length !== 0)
  1474. cb({ [doc.worldName]: doc })
  1475. })
  1476. })
  1477. }
  1478. })
  1479. //})
  1480. }
  1481. async getAllStateWorldsInfoForUserPromise(userAlias) {
  1482. //let users = await _LCSDB.get('users').then();
  1483. let userPub = (await _LCSDB.get('users').get(userAlias).get('pub').promOnce()).data;
  1484. var db = _LCSDB.user(userPub);
  1485. if (_LCSDB.user().is) {
  1486. if (_LCSDB.user().is.alias == userAlias)
  1487. db = _LCSDB.user();
  1488. }
  1489. var states = {};
  1490. let worldDocs = (await db.get('worlds').promOnce()).data;
  1491. if (worldDocs) {
  1492. let protos = Object.keys(worldDocs).filter(el => el !== '_');
  1493. if (protos) {
  1494. for (const el of protos) {
  1495. let info = await this.getSaveStates(userAlias, el);
  1496. if (Object.keys(info).length !== 0)
  1497. states[el] = info;
  1498. }
  1499. }
  1500. }
  1501. return states
  1502. }
  1503. async getAllProtoWorldsInfoForUser(userAlias, cb) {
  1504. //let users = await _LCSDB.get('users').then();
  1505. let userPub = (await _LCSDB.get('users').get(userAlias).get('pub').promOnce()).data;
  1506. var db = _LCSDB.user(userPub);
  1507. if (_LCSDB.user().is) {
  1508. if (_LCSDB.user().is.alias == userAlias)
  1509. db = _LCSDB.user();
  1510. }
  1511. db.get('worlds').once(res=>{
  1512. if (res) {
  1513. db.get('worlds').map(function (val, index) {
  1514. db.get('worlds').get(index).get('info_json').load(function (res) {
  1515. var doc = {};
  1516. if (res && res !== 'null') {
  1517. if (res.file && res.file !== 'null') {
  1518. //let worldDesc = JSON.parse(res.file);
  1519. var worldDesc = {};
  1520. if (typeof (res.file) == 'object') {
  1521. worldDesc = res.file
  1522. } else {
  1523. worldDesc = JSON.parse(res.file)
  1524. }
  1525. let root = Object.keys(worldDesc)[0];
  1526. var appInfo = worldDesc[root]['en'];
  1527. let langID = localStorage.getItem('krestianstvo_locale');
  1528. if (langID) {
  1529. appInfo = worldDesc[root][langID]
  1530. }
  1531. doc = {
  1532. 'worldName': index,
  1533. 'created': res.created ? res.created : res.modified,
  1534. 'modified': res.modified,
  1535. 'type': 'proto',
  1536. 'userAlias': userAlias,
  1537. 'info': appInfo
  1538. }
  1539. }
  1540. }
  1541. if (Object.keys(doc).length !== 0)
  1542. cb({ [index]: doc })
  1543. })
  1544. })
  1545. }
  1546. })
  1547. }
  1548. async getAllProtoWorldsInfoForUserPromise(userAlias) {
  1549. //let users = await _LCSDB.get('users').then();
  1550. let userPub = (await _LCSDB.get('users').get(userAlias).get('pub').promOnce()).data;
  1551. var db = _LCSDB.user(userPub);
  1552. if (_LCSDB.user().is) {
  1553. if (_LCSDB.user().is.alias == userAlias)
  1554. db = _LCSDB.user();
  1555. }
  1556. var worlds = {};
  1557. let worldDocs = (await db.get('worlds').promOnce()).data;
  1558. if (worldDocs) {
  1559. let protos = Object.keys(worldDocs).filter(el => el !== '_');
  1560. if (protos) {
  1561. for (const el of protos) {
  1562. let info = await this.getWorldInfo(userAlias, el);
  1563. if (Object.keys(info).length !== 0)
  1564. worlds[el] = info;
  1565. }
  1566. }
  1567. }
  1568. return worlds
  1569. }
  1570. async getSaveStates(userInfo, worldName) {
  1571. //let userPub = await _LCSDB.get('users').get(userAlias).get('pub').once().then();
  1572. let userPub = userInfo.pub;
  1573. let userAlias = userInfo.user;
  1574. var db = _LCSDB.user(userPub);
  1575. if (_LCSDB.user().is) {
  1576. if (_LCSDB.user().is.alias == userAlias)
  1577. db = _LCSDB.user();
  1578. }
  1579. var states = {};
  1580. let documents = (await db.get('documents').promOnce()).data;
  1581. if (documents) {
  1582. let docs = (await db.get('documents').get(worldName).promOnce()).data;
  1583. if (docs) {
  1584. let saves = Object.keys(docs).filter(el => el.includes('_info_vwf_json'));
  1585. if (saves) {
  1586. for (const el of saves) {
  1587. let stateName = el.split('/')[2].replace('_info_vwf_json', "");
  1588. let info = await this.getStateInfo(userInfo, worldName, stateName);
  1589. if (Object.keys(info).length !== 0) {
  1590. if (info.info)
  1591. states[stateName] = info;
  1592. }
  1593. }
  1594. }
  1595. }
  1596. }
  1597. return states
  1598. }
  1599. async getStateInfo(userInfo, space, saveName) {
  1600. //let userPub = await _LCSDB.get('users').get(user).get('pub').once().then();
  1601. let userPub = userInfo.pub;
  1602. let user = userInfo.user;
  1603. var db = _LCSDB.user(userPub);
  1604. if (_LCSDB.user().is) {
  1605. if (_LCSDB.user().is.alias == user)
  1606. db = _LCSDB.user();
  1607. }
  1608. var info = {};
  1609. //let worlds = await db.get('documents').then();
  1610. let docName = 'savestate_/' + space + '/' + saveName + '_info_vwf_json';
  1611. let world = (await db.get('documents').get(space).get(docName).promOnce()).data;
  1612. if (world) {
  1613. let file = (await db.get('documents').get(space).get(docName).get('file').promOnce()).data;
  1614. if (file && file !== 'null') {
  1615. // let worldDesc = JSON.parse(res.file);
  1616. var worldDesc = {};
  1617. if (typeof (file) == 'object') {
  1618. worldDesc = file
  1619. } else {
  1620. worldDesc = JSON.parse(file)
  1621. }
  1622. let root = Object.keys(worldDesc)[0];
  1623. var appInfo = worldDesc[root]['en'];
  1624. let langID = localStorage.getItem('krestianstvo_locale');
  1625. if (langID) {
  1626. appInfo = worldDesc[root][langID]
  1627. }
  1628. let created = (await db.get('documents').get(space).get(docName).get('created').promOnce()).data;
  1629. let modified = (await db.get('documents').get(space).get(docName).get('modified').promOnce()).data;
  1630. info = {
  1631. 'worldName': space + '/load/' + saveName,
  1632. 'created': created ? created : modified,
  1633. 'modified': modified,
  1634. 'type': 'saveState',
  1635. 'userAlias': user,
  1636. 'info': appInfo
  1637. }
  1638. }
  1639. }
  1640. return info
  1641. }
  1642. async getWorldInfo(userInfo, space) {
  1643. //get space for userA
  1644. let userPub = userInfo.pub;//await _LCSDB.get('users').get(user).get('pub').then();
  1645. let user = userInfo.user;
  1646. var userdb = _LCSDB.user(userPub);
  1647. if (_LCSDB.user().is) {
  1648. if (_LCSDB.user().is.alias == user)
  1649. userdb = _LCSDB.user();
  1650. }
  1651. var info = {};
  1652. //let worlds = await userdb.get('worlds').promOnce();
  1653. let world = (await userdb.get('worlds').get(space).promOnce()).data;
  1654. if (world) {
  1655. let file = (await userdb.get('worlds').get(space).get('info_json').get('file').promOnce()).data;
  1656. if (file && file !== 'null') {
  1657. var worldDesc = {};
  1658. if (typeof (file) == 'object') {
  1659. worldDesc = file
  1660. } else {
  1661. worldDesc = JSON.parse(file)
  1662. }
  1663. //let worldDesc = JSON.parse(res.file);
  1664. let root = Object.keys(worldDesc)[0];
  1665. var appInfo = worldDesc[root]['en'];
  1666. let settings = worldDesc[root].settings;
  1667. let langID = localStorage.getItem('krestianstvo_locale');
  1668. if (langID) {
  1669. appInfo = worldDesc[root][langID]
  1670. }
  1671. let created = (await userdb.get('worlds').get(space).get('info_json').get('created').promOnce()).data;
  1672. let modified = (await userdb.get('worlds').get(space).get('info_json').get('modified').promOnce()).data;
  1673. info = {
  1674. 'worldName': space,
  1675. 'created': created ? created : modified,
  1676. 'modified': modified,
  1677. 'type': 'proto',
  1678. 'userAlias': user,
  1679. 'info': appInfo,
  1680. 'settings': settings
  1681. }
  1682. }
  1683. }
  1684. return info
  1685. }
  1686. }
  1687. export { App }