app.js 54 KB

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