app.js 66 KB

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