app.js 65 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229
  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. for (const res of Object.keys(revs.data)) {
  876. if (res !== '_') {
  877. let el = await userDB.get('documents').get(public_path).get(docName).get('revs').get(res).promOnce();
  878. if (el)
  879. result.push(parseInt(el.data.revision));
  880. }
  881. }
  882. return result
  883. }
  884. }
  885. // GetLoadInformation receives a parsed request {private_path, public_path, instance, application} and returns the
  886. // details of the save that is designated by the initial request. The details are returned in an object
  887. // composed of: save_name (name of the save) save_revision (revision of the save), explicit_revision (boolean, true if the request
  888. // explicitly specified the revision, false if it did not), and application_path (the public_path of the application this is a save for).
  889. async getLoadInformation(response) {
  890. let parsedRequest = response.path;
  891. var result = { 'save_name': undefined, 'save_revision': undefined, 'explicit_revision': undefined, 'application_path': undefined };
  892. if (parsedRequest['private_path']) {
  893. var segments = this.helpers.GenerateSegments(parsedRequest['private_path']);
  894. if ((segments.length > 1) && (segments[0] == "load")) {
  895. var potentialRevisions = await this.lookupSaveRevisions((parsedRequest['public_path']).slice(1), segments[1]);
  896. console.log('!!!!! - ', potentialRevisions);
  897. if (potentialRevisions.length > 0) {
  898. result['save_name'] = segments[1];
  899. if (segments.length > 2) {
  900. var requestedRevision = parseInt(segments[2]);
  901. if (requestedRevision) {
  902. if (potentialRevisions.indexOf(requestedRevision) > -1) {
  903. result['save_revision'] = requestedRevision;
  904. result['explicit_revision'] = true;
  905. result['application_path'] = parsedRequest['public_path'];
  906. }
  907. }
  908. }
  909. if (result['explicit_revision'] == undefined) {
  910. result['explicit_revision'] = false;
  911. potentialRevisions.sort();
  912. result['save_revision'] = potentialRevisions.pop();
  913. result['application_path'] = parsedRequest['public_path'];
  914. }
  915. }
  916. }
  917. }
  918. return result;
  919. }
  920. async loadSaveObject(loadInfo) {
  921. //let objName = loadInfo[ 'save_name' ] +'/'+ "savestate_" + loadInfo[ 'save_revision' ];
  922. let userDB = _LCSDB.user(_LCS_WORLD_USER.pub);
  923. if (!loadInfo.save_name) {
  924. return undefined
  925. }
  926. let objName = "savestate_" + loadInfo['application_path'] + '/' + loadInfo['save_name'] + '_vwf_json';
  927. let objNameRev = "savestate_" + loadInfo['save_revision'] + loadInfo['application_path'] + '/' + loadInfo['save_name'] + '_vwf_json';
  928. // if(loadInfo[ 'save_revision' ]){
  929. // }
  930. let worldName = this.helpers.appPath //loadInfo[ 'application_path' ].slice(1);
  931. let saveObject = (await userDB.get('documents').get(worldName).get(objName).get('revs').get(objNameRev).promOnce()).data;
  932. var saveInfo = null;
  933. if (saveObject) {
  934. saveInfo = (typeof (saveObject.jsonState) == 'object') ? saveObject.jsonState : JSON.parse(saveObject.jsonState);
  935. }
  936. //typeof(saveObject == 'object')
  937. return saveInfo;
  938. }
  939. // GetSaveInformation is a helper function that takes the application_path (/path/to/application).
  940. // It returns an array of all saves found for that
  941. // application (including separate entries for individual revisions of saves ).
  942. async getSaveInformation(application_path, userPUB) {
  943. var result = [];
  944. let user = _LCSDB.user(userPUB);
  945. var docName = application_path.slice(1);
  946. let potentialSaveNames = (await user.get('documents').get(docName).promOnce()).data;
  947. if (potentialSaveNames) {
  948. for (const res of Object.keys(potentialSaveNames)) {
  949. if (res !== '_') {
  950. let el = (await user.get('documents').path(docName).get(res).promOnce()).data;
  951. let revisionList = await this.lookupSaveRevisions(application_path.slice(1), el.filename);
  952. var latestsave = true;
  953. revisionList.sort();
  954. while (revisionList.length > 0) {
  955. var newEntry = {};
  956. newEntry['applicationpath'] = application_path;
  957. newEntry['savename'] = el.filename;
  958. newEntry['revision'] = revisionList.pop().toString();
  959. newEntry['latestsave'] = latestsave;
  960. if (latestsave) {
  961. newEntry['url'] = this.helpers.JoinPath(window.location.origin, application_path, "load", el.filename + "/");
  962. }
  963. else {
  964. newEntry['url'] = this.helpers.JoinPath(window.location.origin, application_path, "load", el.filename + "/", newEntry['revision'] + "/");
  965. }
  966. latestsave = false;
  967. result.push(newEntry);
  968. }
  969. }
  970. }
  971. }
  972. return result;
  973. }
  974. async getProtoWorldFiles(userPub, worldName, date) {
  975. let fileNamesAll = (await _LCSDB.user(userPub).get('worlds').get(worldName).promOnce()).data;
  976. 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'));
  977. let worldObj = {};
  978. for (var doc in worldFileNames) {
  979. let fn = worldFileNames[doc];
  980. let res = (await _LCSDB.user(userPub).get('worlds').get(worldName).get(fn).promOnce()).data;
  981. var data = {
  982. 'file': res.file,
  983. 'modified': res.modified,
  984. 'created': res.created
  985. }
  986. if (!date) {
  987. data = {
  988. 'file': res.file
  989. }
  990. }
  991. worldObj[fn] = data;
  992. }
  993. console.log(worldObj);
  994. return worldObj
  995. }
  996. async cloneWorldPrototype(worldName, userName, newWorldName, stateFileName) {
  997. let self = this;
  998. _app.showProgressBar();
  999. //let users = await _LCSDB.get('users').then();
  1000. let userPub = (await _LCSDB.get('users').get(userName).get('pub').promOnce()).data;
  1001. let newOwner = _LCSDB.user().is.pub;
  1002. let myWorlds = (await _LCSDB.user(newOwner).get('worlds').promOnce()).data;
  1003. //if (!myWorlds) _LCSDB.user(newOwner).get('worlds').put({});
  1004. _LCSDB.user(newOwner).get('worlds').not(res=>{
  1005. _LCSDB.user(newOwner).get('worlds').put({});
  1006. })
  1007. if(myWorlds) {
  1008. let checkExist = Object.keys(myWorlds).filter(el=> el == newWorldName);
  1009. if (newWorldName) {
  1010. //let worldProto = (await _LCSDB.user(newOwner).get('worlds').get(newWorldName).promOnce()).data;
  1011. if (checkExist.length > 0 && myWorlds[newWorldName]) {
  1012. console.log('already exist!');
  1013. return
  1014. }
  1015. }
  1016. }
  1017. var worldID = window._app.helpers.GenerateInstanceID().toString();
  1018. if (newWorldName) {
  1019. worldID = newWorldName
  1020. }
  1021. //let modified = new Date().valueOf();
  1022. console.log('clone: ' + worldName + 'to: ' + worldID);
  1023. let created = new Date().valueOf();
  1024. let worldObj = {
  1025. 'owner': newOwner,
  1026. 'parent': userName + '/' + worldName,
  1027. 'featured': true,
  1028. 'published': true
  1029. };
  1030. // let fileNamesAll =
  1031. await _LCSDB.user(userPub).get('worlds').get(worldName).load(all=> {
  1032. let worldFileNames = Object.keys(all).filter(el => (el !== '_') && (el !== 'owner') && (el !== 'parent') && (el !== 'featured') && (el !== 'published') && (el !== '_config_yaml') && (el !== '_yaml') && (el !== '_html'));
  1033. for (var doc in worldFileNames) {
  1034. let fn = worldFileNames[doc];
  1035. let res = all[fn]; //(await _LCSDB.user(userPub).get('worlds').get(worldName).get(fn).promOnce()).data;
  1036. let fileData = (typeof res.file == 'object')? JSON.stringify(res.file):res.file;
  1037. let data = {
  1038. 'file': fileData, //JSON.stringify(res.file),
  1039. 'modified': created
  1040. }
  1041. worldObj[fn] = data;
  1042. }
  1043. console.log(worldObj);
  1044. // for (const obj of Object.keys(worldObj)) {
  1045. // let myWorlds = _LCSDB.user().get('worlds');
  1046. // let myNewWorld = myWorlds.get(worldID);
  1047. // myNewWorld.get(obj).put(worldObj[obj]);
  1048. // }
  1049. //let myWorlds = await _LCSDB.user(newOwner).get('worlds').once().then();
  1050. let myWorld = _LCSDB.user(newOwner).get('worlds').get(worldID).put({});
  1051. myWorld.put(worldObj, function (res) {
  1052. if(stateFileName){
  1053. self.saveStateAsFile(stateFileName)
  1054. }
  1055. console.log(res)
  1056. }); //.get(worldID) let myWorld =
  1057. // let myWorld = _LCSDB.user().get(worldID).put(worldObj);
  1058. // _LCSDB.user().get('worlds').set(myWorld);
  1059. _app.hideProgressBar();
  1060. console.log('CLONED!!!');
  1061. let appEl = document.createElement("div");
  1062. appEl.setAttribute("id", 'cloneLink');
  1063. let entry = document.querySelector('#worldActionsGUI');
  1064. if (entry) {
  1065. entry.appendChild(appEl);
  1066. document.querySelector("#cloneLink").$cell({
  1067. id: 'cloneLink',
  1068. $cell: true,
  1069. $type: "div",
  1070. $components: [
  1071. {
  1072. $type: "a",
  1073. class: "mdc-button mdc-button--raised mdc-card__action",
  1074. $text: "Go to new cloned World!",
  1075. onclick: function (e) {
  1076. let myName = _LCSDB.user().is.alias;
  1077. window.location.pathname = '/' + myName + '/' + worldID + '/about'
  1078. }
  1079. }
  1080. ]
  1081. })
  1082. }
  1083. },{wait: 500}).then();
  1084. //window.location.pathname = '/' + userName + '/' + worldID + '/about'
  1085. //page()
  1086. // Object.keys(worldObj).forEach(el => {
  1087. // this.db.user().get('worlds').get(worldID).get(el).put(worldObj[el]);
  1088. // })
  1089. }
  1090. async cloneWorldState(filename) {
  1091. let myWorldProtos = (await _LCSDB.user().get('worlds').promOnce()).data;
  1092. let userName = this.helpers.worldUser;
  1093. // let users = await _LCSDB.get('users').then();
  1094. let userPub = (await _LCSDB.get('users').get(userName).get('pub').promOnce()).data;
  1095. let protoUserRoot = this.helpers.getRoot(true).root;
  1096. //let myName = this.db.user().is.alias;
  1097. //let proto = Object.keys(myWorldProtos).filter(el => el == protoUserRoot);
  1098. var protosKeys = [];
  1099. if (myWorldProtos)
  1100. protosKeys = Object.keys(myWorldProtos);
  1101. if (protosKeys.includes(protoUserRoot) && myWorldProtos[protoUserRoot]) {
  1102. let userProtoFiles = await this.getProtoWorldFiles(userPub, protoUserRoot);
  1103. let myProtoFiles = await this.getProtoWorldFiles(_LCSDB.user().is.pub, protoUserRoot);
  1104. let hashUP = await this.helpers.sha256(JSON.stringify(userProtoFiles));
  1105. let hashMP = await this.helpers.sha256(JSON.stringify(myProtoFiles));
  1106. if (hashUP == hashMP) {
  1107. this.saveStateAsFile(filename);
  1108. } else {
  1109. let noty = new Noty({
  1110. text: 'world prototype is modified.. could not clone world state',
  1111. timeout: 2000,
  1112. theme: 'mint',
  1113. layout: 'bottomRight',
  1114. type: 'error'
  1115. });
  1116. noty.show();
  1117. }
  1118. } else {
  1119. await this.cloneWorldPrototype(protoUserRoot, userName, protoUserRoot, filename);
  1120. //this.saveStateAsFile(filename);
  1121. }
  1122. }
  1123. //TODO: refactor and config save
  1124. async saveStateAsFile(filename, otherProto) // invoke with the view as "this"
  1125. {
  1126. console.log("Saving: " + filename);
  1127. //var clients = this.nodes["http://vwf.example.com/clients.vwf"];
  1128. // Save State Information
  1129. var state = vwf.getState();
  1130. state.nodes[0].children = {};
  1131. var timestamp = state["queue"].time;
  1132. timestamp = Math.round(timestamp * 1000);
  1133. let jsonValuePure = _app.helpers.replaceFloatArraysInNodeDef(state);
  1134. //remove all Ohm generated grammarsfrom state
  1135. let jsonValue = _app.helpers.removeGrammarObj(jsonValuePure);
  1136. var jsonState = JSON.stringify(jsonValue, null, '\t'); //JSON.stringify(jsonValue);
  1137. let rootPath = this.helpers.getRoot(true);
  1138. var inst = rootPath.inst;
  1139. if (filename == '') filename = inst;
  1140. //if (root.indexOf('.vwf') != -1) root = root.substring(0, root.lastIndexOf('/'));
  1141. var root = rootPath.root;
  1142. var json = jsonState;
  1143. if (otherProto) {
  1144. console.log('need to modify state...');
  1145. json = this.helpers.replaceSubStringALL(jsonState, '/' + root + '/', '/' + otherProto + '/');//jsonState.replace(('/' + root + '/'), ('/' + otherProto +'/') );
  1146. root = otherProto;
  1147. console.log(json);
  1148. }
  1149. //var documents = this.db.user().get('documents');
  1150. var saveRevision = new Date().valueOf();
  1151. var stateForStore = {
  1152. "root": root,
  1153. "filename": filename,
  1154. "inst": inst,
  1155. "timestamp": timestamp,
  1156. "extension": ".vwf.json",
  1157. "jsonState": json,
  1158. "publish": true
  1159. };
  1160. let rev = JSON.stringify(saveRevision);
  1161. var docNameRev = 'savestate_' + rev + '/' + root + '/' + filename + '_vwf_json';
  1162. let stateWithRev = Object.assign({}, stateForStore);
  1163. stateWithRev.revs = { [docNameRev]: stateForStore };
  1164. stateWithRev.revs[docNameRev].revision = saveRevision;
  1165. //let objName = loadInfo[ 'save_name' ] +'/'+ "savestate_" + loadInfo[ 'save_revision' ];
  1166. // "savestate_" + loadInfo[ 'save_revision' ] + '/' + loadInfo[ 'save_name' ] + '_vwf_json'
  1167. var docName = 'savestate_/' + root + '/' + filename + '_vwf_json';
  1168. let myNewWorldState = _LCSDB.user().get('documents').get(root).get(docName).put({});
  1169. //_LCSDB.user().get('documents').get(root).get(docName).put(stateWithRev, function(res) {
  1170. myNewWorldState.put(stateWithRev, function (res) {
  1171. if (res) {
  1172. let noty = new Noty({
  1173. text: 'Saved to ' + docName,
  1174. timeout: 2000,
  1175. theme: 'mint',
  1176. layout: 'bottomRight',
  1177. type: 'success'
  1178. });
  1179. noty.show();
  1180. }
  1181. });
  1182. // let docInfo = await _LCSDB.user().get('worlds').get(root).get('info_json').get('file').then();
  1183. _LCSDB.user().get('worlds').get(root).get('info_json').get('file').once(function (file) {
  1184. if (file) {
  1185. let modified = saveRevision;
  1186. let newOwner = _LCSDB.user().is.pub;
  1187. let userName = _LCSDB.user().is.alias;
  1188. let fileData = (typeof file == 'object')? JSON.stringify(file):file;
  1189. let obj = {
  1190. 'parent': userName + '/' + root,
  1191. 'owner': newOwner,
  1192. 'file': fileData, //file, //JSON.stringify(file),
  1193. //'modified': modified,
  1194. 'created': modified
  1195. }
  1196. let docInfoName = 'savestate_/' + root + '/' + filename + '_info_vwf_json';
  1197. _LCSDB.user().get('documents').get(root).get(docInfoName).get('file').not(function (res) {
  1198. _LCSDB.user().get('documents').get(root).get(docInfoName).put(obj);
  1199. });
  1200. _LCSDB.user().get('documents').get(root).get(docInfoName).get('created').not(function (res) {
  1201. _LCSDB.user().get('documents').get(root).get(docInfoName).get('created').put(modified);
  1202. });
  1203. _LCSDB.user().get('documents').get(root).get(docInfoName).get('modified').put(modified);
  1204. }
  1205. });
  1206. // Save Config Information
  1207. var config = { "info": {}, "model": {}, "view": {} };
  1208. // Save browser title
  1209. config["info"]["title"] = document.title//$('title').html();
  1210. // Save model drivers
  1211. Object.keys(vwf_view.kernel.kernel.models).forEach(function (modelDriver) {
  1212. if (modelDriver.indexOf('vwf/model/') != -1) config["model"][modelDriver] = "";
  1213. });
  1214. // If neither glge or threejs model drivers are defined, specify nodriver
  1215. if (config["model"]["vwf/model/glge"] === undefined && config["model"]["vwf/model/threejs"] === undefined) config["model"]["nodriver"] = "";
  1216. // Save view drivers and associated parameters, if any
  1217. Object.keys(vwf_view.kernel.kernel.views).forEach(function (viewDriver) {
  1218. if (viewDriver.indexOf('vwf/view/') != -1) {
  1219. if (vwf_view.kernel.kernel.views[viewDriver].parameters) {
  1220. config["view"][viewDriver] = vwf_view.kernel.kernel.views[viewDriver].parameters;
  1221. }
  1222. else config["view"][viewDriver] = "";
  1223. }
  1224. });
  1225. //var jsonConfig = $.encoder.encodeForURL(JSON.stringify(config));
  1226. var jsonConfig = JSON.stringify(config);
  1227. let configStateForStore = {
  1228. "root": root,
  1229. "filename": filename,
  1230. "inst": inst,
  1231. "timestamp": timestamp,
  1232. "extension": "config.vwf.json",
  1233. "jsonState": jsonConfig
  1234. };
  1235. //let objName = loadInfo[ 'save_name' ] +'/'+ "savestate_" + loadInfo[ 'save_revision' ];
  1236. // "savestate_" + loadInfo[ 'save_revision' ] + '/' + loadInfo[ 'save_name' ] + '_vwf_json'
  1237. // let configName = 'savestate_/' + root + '/' + filename + '_config_vwf_json';
  1238. // let documentSaveConfigState = this.db.user().get(configName).put(configStateForStore);
  1239. // //documents.path(root).set(documentSaveConfigState);
  1240. // let configNameRev = 'savestate_' + saveRevision.toString() + '/' + root + '/' + filename + '_config_vwf_json';
  1241. // this.db.user().get(configNameRev).put(configStateForStore);
  1242. // this.db.user().get(configNameRev).path("revision").put(saveRevision);
  1243. //documentSaveConfigState.path('revs').set(documentSaveStateRevision);
  1244. // Save config file to server
  1245. // var xhrConfig = new XMLHttpRequest();
  1246. // xhrConfig.open("POST", "/" + root + "/save/" + filename, true);
  1247. // xhrConfig.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  1248. // xhrConfig.send("root=" + root + "/" + filename + "&filename=saveState&inst=" + inst + "&timestamp=" + timestamp + "&extension=.vwf.config.json" + "&jsonState=" + jsonConfig);
  1249. }
  1250. fixSaveState(jsonState, otherProto, oldProtoName) {
  1251. console.log('fix proto in state...');
  1252. let json = this.helpers.replaceSubStringALL(jsonState, '/' + oldProtoName + '/', '/' + otherProto + '/');//jsonState.replace(('/' + root + '/'), ('/' + otherProto +'/') );
  1253. console.log(json);
  1254. return json
  1255. }
  1256. // LoadSavedState
  1257. async loadSavedState(filename, applicationpath, revision) {
  1258. console.log("Loading: " + filename);
  1259. let userDB = _LCSDB.user(_LCS_WORLD_USER.pub);
  1260. let userName = (await userDB.get('alias').promOnce()).data;
  1261. if (revision) {
  1262. window.location.pathname = '/' + userName + applicationpath + '/load/' + filename + '/' + revision + '/';
  1263. }
  1264. else { // applicationpath + "/" + inst + '/load/' + filename + '/';
  1265. window.location.pathname = '/' + userName + applicationpath + '/load/' + filename + '/';
  1266. }
  1267. }
  1268. hideUIControl() {
  1269. let el = document.getElementById("ui-controls");
  1270. if (el) {
  1271. el.classList.remove("visible");
  1272. el.classList.add("not-visible");
  1273. }
  1274. }
  1275. showUIControl() {
  1276. let el = document.getElementById("ui-controls");
  1277. if (el) {
  1278. el.classList.remove("not-visible");
  1279. el.classList.add("visible");
  1280. }
  1281. }
  1282. hideProgressBar() {
  1283. var progressbar = document.getElementById("load-progressbar");
  1284. if (progressbar) {
  1285. progressbar.classList.remove("visible");
  1286. progressbar.classList.remove("mdc-linear-progress--indeterminate");
  1287. progressbar.classList.add("not-visible");
  1288. progressbar.classList.add("mdc-linear-progress--closed");
  1289. }
  1290. }
  1291. showProgressBar() {
  1292. let progressbar = document.getElementById("load-progressbar");
  1293. if (progressbar) {
  1294. progressbar.classList.remove("not-visible");
  1295. progressbar.classList.remove("mdc-linear-progress--closed");
  1296. progressbar.classList.add("visible");
  1297. progressbar.classList.add("mdc-linear-progress--indeterminate");
  1298. }
  1299. }
  1300. // SUPPORT of DELETE USER WORLDS & SAVE STATES (experimental)
  1301. // TODO: manual garbage collection
  1302. async deleteWorldState(worldName, indexState) {
  1303. let revs = (await _LCSDB.user().get('documents').get(worldName).get(indexState).get('revs').promOnce()).data;
  1304. if (revs) {
  1305. for (const el of Object.keys(revs)) {
  1306. if (el !== '_') {
  1307. let doc = (await _LCSDB.user().get('documents').get(worldName).get(indexState).get('revs').get(el).promOnce()).data;
  1308. for (const rev of Object.keys(doc)) {
  1309. if (rev !== '_') {
  1310. await _LCSDB.user().get('documents').get(worldName).get(indexState).get('revs').get(el).get(rev).put(null).promOnce();
  1311. }
  1312. }
  1313. await _LCSDB.user().get('documents').get(worldName).get(indexState).get('revs').get(el).put(null).promOnce();
  1314. }
  1315. }
  1316. }
  1317. // clear all state params
  1318. let stateDoc = (await _LCSDB.user().get('documents').get(worldName).get(indexState).promOnce()).data;
  1319. for (const state of Object.keys(stateDoc)) {
  1320. if (state !== '_' && state !== 'revs') {
  1321. await _LCSDB.user().get('documents').get(worldName).get(indexState).get(state).put(null).promOnce();
  1322. }
  1323. }
  1324. await _LCSDB.user().get('documents').get(worldName).get(indexState).get('revs').put(null).promOnce();
  1325. await _LCSDB.user().get('documents').get(worldName).get(indexState).put(null).promOnce();
  1326. }
  1327. async deleteWorld(name, type) {
  1328. if (type == 'proto') {
  1329. let worldName = name;
  1330. //TODO check for states (ask for deleting all states first...)
  1331. //delete states
  1332. let documents = (await _LCSDB.user().get('documents').promOnce()).data;
  1333. if (documents) {
  1334. let states = (await _LCSDB.user().get('documents').get(worldName).promOnce()).data;
  1335. if (states) {
  1336. for (const st of Object.keys(states)) {
  1337. if (st !== '_') {
  1338. if (states[st]) {
  1339. await this.deleteWorldState(worldName, st);
  1340. }
  1341. }
  1342. }
  1343. }
  1344. }
  1345. let worldFiles = (await _LCSDB.user().get('worlds').get(worldName).promOnce()).data;
  1346. if (worldFiles) {
  1347. for (const el of Object.keys(worldFiles)) {
  1348. if (el !== '_') {
  1349. let doc = (await _LCSDB.user().get('worlds').get(worldName).get(el).promOnce()).data;
  1350. if (doc) {
  1351. if (doc.file) {
  1352. for (const fEl of Object.keys(doc)) {
  1353. if (fEl !== '_') {
  1354. await _LCSDB.user().get('worlds').get(worldName).get(el).get(fEl).put(null).promOnce();
  1355. }
  1356. }
  1357. await _LCSDB.user().get('worlds').get(worldName).get(el).put(null).promOnce();
  1358. } else {
  1359. await _LCSDB.user().get('worlds').get(worldName).get(el).put(null).promOnce()
  1360. }
  1361. }
  1362. }
  1363. }
  1364. }
  1365. // this.db.user().get('worlds').get(worldName).map((res, index) => {
  1366. // if(typeof res == 'object'){
  1367. // this.db.user().get('worlds').get(worldName).get(index)
  1368. // .get('file').put("null")
  1369. // .back(1)
  1370. // .get('modified').put("null")
  1371. // .back(1)
  1372. // .get('created').put("null")
  1373. // .back(1).put("null")
  1374. // } else {
  1375. // this.db.user().get('worlds').get(worldName).get(index).put("null")
  1376. // }
  1377. // })
  1378. await _LCSDB.user().get('worlds').get(worldName).put(null).promOnce();
  1379. } else if (type == 'state') {
  1380. let worldName = name.split('/')[0];
  1381. let stateName = name.split('/')[2];
  1382. let stateEntryInfo = 'savestate_/' + worldName + '/' + stateName + '_info_vwf_json';
  1383. let stateEntry = 'savestate_/' + worldName + '/' + stateName + '_vwf_json';
  1384. await this.deleteWorldState(worldName, stateEntryInfo);
  1385. await this.deleteWorldState(worldName, stateEntry);
  1386. }
  1387. let noty = new Noty({
  1388. text: "World Deleted!",
  1389. timeout: 2000,
  1390. theme: 'mint',
  1391. layout: 'bottomRight',
  1392. type: 'success'
  1393. });
  1394. noty.show();
  1395. }
  1396. parseAppInstancesData(data) {
  1397. let jsonObj = JSON.parse(data);
  1398. var parsed = {};
  1399. let listData = {};
  1400. for (var prop in jsonObj) {
  1401. var name = prop.split('/')[1];
  1402. if (parsed[name]) {
  1403. parsed[name][prop] = jsonObj[prop];
  1404. } else {
  1405. parsed[name] = {};
  1406. parsed[name][prop] = jsonObj[prop];
  1407. }
  1408. }
  1409. //console.log(parsed);
  1410. for (var prop in parsed) {
  1411. var name = prop;
  1412. let obj = Object.entries(parsed[prop]);
  1413. var lists = {};
  1414. obj.forEach(el => {
  1415. if (el[1].loadInfo['save_name']) {
  1416. let saveName = prop + '/load/' + el[1].loadInfo.save_name;
  1417. if (!lists[saveName])
  1418. lists[saveName] = {};
  1419. lists[saveName][el[0]] = el[1]
  1420. } else {
  1421. if (!lists[name])
  1422. lists[name] = {};
  1423. lists[name][el[0]] = el[1]
  1424. }
  1425. });
  1426. // console.log(lists);
  1427. Object.entries(lists).forEach(list => {
  1428. listData[list[0]] = list[1];
  1429. })
  1430. }
  1431. return listData
  1432. // console.log(data)
  1433. }
  1434. async getAllStateWorldsInfoForUser(userAlias, cb) {
  1435. //let users = await _LCSDB.get('users').then();
  1436. let userPub = (await _LCSDB.get('users').get(userAlias).get('pub').promOnce()).data;
  1437. var db = _LCSDB.user(userPub);
  1438. if (_LCSDB.user().is) {
  1439. if (_LCSDB.user().is.alias == userAlias)
  1440. db = _LCSDB.user();
  1441. }
  1442. //let myWorlds = (await db.get('documents').promOnce()).data;
  1443. db.get('documents').load(myWorlds => {
  1444. if (myWorlds) {
  1445. Object.keys(myWorlds).filter(el => el !== '_').forEach(w => {
  1446. db.get('documents').get(w).map(function (res, datI) {
  1447. var doc = {};
  1448. if (datI.includes('_info_vwf_json')) {
  1449. if (res && res !== 'null') {
  1450. if (res.file && res.file !== 'null') {
  1451. let saveName = datI.split('/')[2].replace('_info_vwf_json', "");
  1452. // let worldDesc = JSON.parse(res.file);
  1453. var worldDesc = {};
  1454. if (typeof (res.file) == 'object') {
  1455. worldDesc = res.file
  1456. } else {
  1457. worldDesc = JSON.parse(res.file)
  1458. }
  1459. let root = Object.keys(worldDesc)[0];
  1460. var appInfo = worldDesc[root]['en'];
  1461. let langID = localStorage.getItem('krestianstvo_locale');
  1462. if (langID) {
  1463. appInfo = worldDesc[root][langID]
  1464. }
  1465. doc = {
  1466. 'worldName': w + '/load/' + saveName,
  1467. 'created': res.created ? res.created : res.modified,
  1468. 'modified': res.modified,
  1469. 'type': 'saveState',
  1470. 'userAlias': userAlias,
  1471. 'info': appInfo
  1472. }
  1473. }
  1474. }
  1475. }
  1476. if (Object.keys(doc).length !== 0)
  1477. cb({ [doc.worldName]: doc })
  1478. })
  1479. })
  1480. }
  1481. })
  1482. //})
  1483. }
  1484. async getAllStateWorldsInfoForUserPromise(userAlias) {
  1485. //let users = await _LCSDB.get('users').then();
  1486. let userPub = (await _LCSDB.get('users').get(userAlias).get('pub').promOnce()).data;
  1487. var db = _LCSDB.user(userPub);
  1488. if (_LCSDB.user().is) {
  1489. if (_LCSDB.user().is.alias == userAlias)
  1490. db = _LCSDB.user();
  1491. }
  1492. var states = {};
  1493. let worldDocs = (await db.get('worlds').promOnce()).data;
  1494. if (worldDocs) {
  1495. let protos = Object.keys(worldDocs).filter(el => el !== '_');
  1496. if (protos) {
  1497. for (const el of protos) {
  1498. let info = await this.getSaveStates(userAlias, el);
  1499. if (Object.keys(info).length !== 0)
  1500. states[el] = info;
  1501. }
  1502. }
  1503. }
  1504. return states
  1505. }
  1506. async getAllProtoWorldsInfoForUser(userAlias, cb) {
  1507. //let users = await _LCSDB.get('users').then();
  1508. let userPub = (await _LCSDB.get('users').get(userAlias).get('pub').promOnce()).data;
  1509. var db = _LCSDB.user(userPub);
  1510. if (_LCSDB.user().is) {
  1511. if (_LCSDB.user().is.alias == userAlias)
  1512. db = _LCSDB.user();
  1513. }
  1514. db.get('worlds').once(res=>{
  1515. if (res) {
  1516. db.get('worlds').map(function (val, index) {
  1517. db.get('worlds').get(index).get('info_json').load(function (res) {
  1518. var doc = {};
  1519. if (res && res !== 'null') {
  1520. if (res.file && res.file !== 'null') {
  1521. //let worldDesc = JSON.parse(res.file);
  1522. var worldDesc = {};
  1523. if (typeof (res.file) == 'object') {
  1524. worldDesc = res.file
  1525. } else {
  1526. worldDesc = JSON.parse(res.file)
  1527. }
  1528. let root = Object.keys(worldDesc)[0];
  1529. var appInfo = worldDesc[root]['en'];
  1530. let langID = localStorage.getItem('krestianstvo_locale');
  1531. if (langID) {
  1532. appInfo = worldDesc[root][langID]
  1533. }
  1534. doc = {
  1535. 'worldName': index,
  1536. 'created': res.created ? res.created : res.modified,
  1537. 'modified': res.modified,
  1538. 'type': 'proto',
  1539. 'userAlias': userAlias,
  1540. 'info': appInfo
  1541. }
  1542. }
  1543. }
  1544. if (Object.keys(doc).length !== 0)
  1545. cb({ [index]: doc })
  1546. })
  1547. })
  1548. }
  1549. })
  1550. }
  1551. async getAllProtoWorldsInfoForUserPromise(userAlias) {
  1552. //let users = await _LCSDB.get('users').then();
  1553. let userPub = (await _LCSDB.get('users').get(userAlias).get('pub').promOnce()).data;
  1554. var db = _LCSDB.user(userPub);
  1555. if (_LCSDB.user().is) {
  1556. if (_LCSDB.user().is.alias == userAlias)
  1557. db = _LCSDB.user();
  1558. }
  1559. var worlds = {};
  1560. let worldDocs = (await db.get('worlds').promOnce()).data;
  1561. if (worldDocs) {
  1562. let protos = Object.keys(worldDocs).filter(el => el !== '_');
  1563. if (protos) {
  1564. for (const el of protos) {
  1565. let info = await this.getWorldInfo(userAlias, el);
  1566. if (Object.keys(info).length !== 0)
  1567. worlds[el] = info;
  1568. }
  1569. }
  1570. }
  1571. return worlds
  1572. }
  1573. async getSaveStates(userInfo, worldName) {
  1574. //let userPub = await _LCSDB.get('users').get(userAlias).get('pub').once().then();
  1575. let userPub = userInfo.pub;
  1576. let userAlias = userInfo.user;
  1577. var db = _LCSDB.user(userPub);
  1578. if (_LCSDB.user().is) {
  1579. if (_LCSDB.user().is.alias == userAlias)
  1580. db = _LCSDB.user();
  1581. }
  1582. var states = {};
  1583. let documents = (await db.get('documents').promOnce()).data;
  1584. if (documents) {
  1585. let docs = (await db.get('documents').get(worldName).promOnce()).data;
  1586. if (docs) {
  1587. let saves = Object.keys(docs).filter(el => el.includes('_info_vwf_json'));
  1588. if (saves) {
  1589. for (const el of saves) {
  1590. let stateName = el.split('/')[2].replace('_info_vwf_json', "");
  1591. let info = await this.getStateInfo(userInfo, worldName, stateName);
  1592. if (Object.keys(info).length !== 0) {
  1593. if (info.info)
  1594. states[stateName] = info;
  1595. }
  1596. }
  1597. }
  1598. }
  1599. }
  1600. return states
  1601. }
  1602. async getStateInfo(userInfo, space, saveName) {
  1603. //let userPub = await _LCSDB.get('users').get(user).get('pub').once().then();
  1604. let userPub = userInfo.pub;
  1605. let user = userInfo.user;
  1606. var db = _LCSDB.user(userPub);
  1607. if (_LCSDB.user().is) {
  1608. if (_LCSDB.user().is.alias == user)
  1609. db = _LCSDB.user();
  1610. }
  1611. var info = {};
  1612. //let worlds = await db.get('documents').then();
  1613. let docName = 'savestate_/' + space + '/' + saveName + '_info_vwf_json';
  1614. let world = (await db.get('documents').get(space).get(docName).promOnce()).data;
  1615. if (world) {
  1616. let file = (await db.get('documents').get(space).get(docName).get('file').promOnce()).data;
  1617. if (file && file !== 'null') {
  1618. // let worldDesc = JSON.parse(res.file);
  1619. var worldDesc = {};
  1620. if (typeof (file) == 'object') {
  1621. worldDesc = file
  1622. } else {
  1623. worldDesc = JSON.parse(file)
  1624. }
  1625. let root = Object.keys(worldDesc)[0];
  1626. var appInfo = worldDesc[root]['en'];
  1627. let langID = localStorage.getItem('krestianstvo_locale');
  1628. if (langID) {
  1629. appInfo = worldDesc[root][langID]
  1630. }
  1631. let created = (await db.get('documents').get(space).get(docName).get('created').promOnce()).data;
  1632. let modified = (await db.get('documents').get(space).get(docName).get('modified').promOnce()).data;
  1633. info = {
  1634. 'worldName': space + '/load/' + saveName,
  1635. 'created': created ? created : modified,
  1636. 'modified': modified,
  1637. 'type': 'saveState',
  1638. 'userAlias': user,
  1639. 'info': appInfo
  1640. }
  1641. }
  1642. }
  1643. return info
  1644. }
  1645. async getWorldInfo(userInfo, space) {
  1646. //get space for userA
  1647. let userPub = userInfo.pub;//await _LCSDB.get('users').get(user).get('pub').then();
  1648. let user = userInfo.user;
  1649. var userdb = _LCSDB.user(userPub);
  1650. if (_LCSDB.user().is) {
  1651. if (_LCSDB.user().is.alias == user)
  1652. userdb = _LCSDB.user();
  1653. }
  1654. var info = {};
  1655. //let worlds = await userdb.get('worlds').promOnce();
  1656. let world = (await userdb.get('worlds').get(space).promOnce()).data;
  1657. if (world) {
  1658. let file = (await userdb.get('worlds').get(space).get('info_json').get('file').promOnce()).data;
  1659. if (file && file !== 'null') {
  1660. var worldDesc = {};
  1661. if (typeof (file) == 'object') {
  1662. worldDesc = file
  1663. } else {
  1664. worldDesc = JSON.parse(file)
  1665. }
  1666. //let worldDesc = JSON.parse(res.file);
  1667. let root = Object.keys(worldDesc)[0];
  1668. var appInfo = worldDesc[root]['en'];
  1669. let settings = worldDesc[root].settings;
  1670. let langID = localStorage.getItem('krestianstvo_locale');
  1671. if (langID) {
  1672. appInfo = worldDesc[root][langID]
  1673. }
  1674. let created = (await userdb.get('worlds').get(space).get('info_json').get('created').promOnce()).data;
  1675. let modified = (await userdb.get('worlds').get(space).get('info_json').get('modified').promOnce()).data;
  1676. info = {
  1677. 'worldName': space,
  1678. 'created': created ? created : modified,
  1679. 'modified': modified,
  1680. 'type': 'proto',
  1681. 'userAlias': user,
  1682. 'info': appInfo,
  1683. 'settings': settings
  1684. }
  1685. }
  1686. }
  1687. return info
  1688. }
  1689. }
  1690. export { App }