app.js 57 KB

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