app.js 56 KB

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