app.js 60 KB

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