app.js 61 KB

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