app.js 56 KB

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