app.js 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289
  1. import { Lang } from '/lib/polyglot/language.js';
  2. import { Helpers } from '/helpers.js';
  3. import { IndexApp } from '/web/index-app.js';
  4. import { Widgets } from '/lib/widgets.js';
  5. class App {
  6. constructor() {
  7. console.log("app constructor");
  8. this.widgets = new Widgets;
  9. //globals
  10. window._app = this;
  11. window._cellWidgets = this.widgets;
  12. window._LangManager = new Lang;
  13. window._noty = new Noty;
  14. _LangManager.setLanguage().then(res => {
  15. return this.initDB()
  16. }).then(res => {
  17. this.helpers = new Helpers;
  18. this.initUser();
  19. //client routes
  20. page('/', this.HandleIndex);
  21. page('/setup', this.HandleSetupIndex);
  22. page('/profile', this.HandleUserIndex);
  23. page('/worlds', this.HandleIndex);
  24. page('/:user/worlds', this.HandleUserWorlds);
  25. page('/:user/worlds/:type', this.HandleUserWorldsWithType);
  26. page('/:user/:type/:name/edit/:file', this.HandleFileEdit);
  27. page('/:user/:space', this.HandleParsableRequestGenID);
  28. page('/:user/:space/:id', this.HandleParsableRequestWithID);
  29. page('/:user/:space/index.vwf/:id', this.HandleParsableRequestWithID);
  30. page('/:user/:space/load/:savename', this.HandleParsableLoadRequest);
  31. page('/:user/:space/:id/load/:savename', this.HandleParsableRequestWithID);
  32. page('/:user/:space/load/:savename/:rev', this.HandleParsableLoadRequestWithRev);
  33. page('/:user/:space/:id/load/:savename/:rev', this.HandleParsableRequestWithID);
  34. page('*', this.HandleNoPage);
  35. page();
  36. })
  37. }
  38. initDB() {
  39. var config = JSON.parse(localStorage.getItem('lcs_config'));
  40. if (!config) {
  41. config = {
  42. 'dbhost': 'https://' + window.location.hostname + ':8080/gun', //'http://localhost:8080/gun',
  43. 'reflector': 'https://' + window.location.hostname + ':3002',
  44. 'language': 'en'
  45. }
  46. localStorage.setItem('lcs_config', JSON.stringify(config));
  47. }
  48. const dbConnection = new Promise((resolve, reject) => {
  49. this.db = Gun(this.dbHost);
  50. this.user = this.db.user();
  51. window._LCSDB = this.db;
  52. window._LCSUSER = this.user;
  53. window._LCS_SYS_USER = undefined;
  54. window._LCS_WORLD_USER = undefined;
  55. _LCSDB.get('lcs/app').get('pub').once(res => {
  56. if (res) {
  57. window._LCS_SYS_USER = this.db.user(res);
  58. }
  59. });
  60. _LCSDB.on('hi', function (peer) {
  61. let msg = 'Connected to ' + peer.url;
  62. let noty = new Noty({
  63. text: msg,
  64. timeout: 2000,
  65. theme: 'mint',
  66. layout: 'bottomRight',
  67. type: 'success'
  68. });
  69. noty.show();
  70. console.log(msg)
  71. })
  72. _LCSDB.on('bye', function (peer) {
  73. let msg = 'No connection to ' + peer.url;
  74. let noty = new Noty({
  75. text: msg,
  76. timeout: 1000,
  77. theme: 'mint',
  78. layout: 'bottomRight',
  79. type: 'error'
  80. });
  81. noty.show();
  82. console.log(msg)
  83. })
  84. resolve('ok');
  85. });
  86. return dbConnection
  87. }
  88. initUser() {
  89. _LCSUSER.recall({ sessionStorage: 1 });
  90. }
  91. get reflectorHost() {
  92. var res = "";
  93. let config = localStorage.getItem('lcs_config');
  94. if (config) {
  95. res = JSON.parse(config).reflector;
  96. }
  97. return res;
  98. }
  99. get dbHost() {
  100. var res = "";
  101. let config = localStorage.getItem('lcs_config');
  102. if (config) {
  103. res = JSON.parse(config).dbhost;
  104. }
  105. return res;
  106. }
  107. async loadProxyDefaults() {
  108. //load to DB default proxy files (VWF & A-Frame components)
  109. let proxyResponse = await fetch('/proxy-files', { method: 'get' });
  110. let proxyFiles = await proxyResponse.json();
  111. let filterProxyFiles = proxyFiles.filter(el => (el !== null));
  112. console.log(filterProxyFiles);
  113. var origin = window.location.origin;
  114. //var userPub = _LCSUSER.is.pub;
  115. let proxyObj = {};
  116. for (var index in filterProxyFiles) {
  117. let el = filterProxyFiles[index];
  118. if (el) {
  119. var url = origin + el;
  120. var entryName = url.replace(origin + '/defaults/', "").split(".").join("_");
  121. let proxyFile = await fetch(url, { method: 'get' });
  122. let responseText = await proxyFile.text();
  123. if (responseText) {
  124. let obj = {
  125. //'owner': userPub,
  126. 'file': responseText
  127. }
  128. proxyObj[entryName] = obj;
  129. }
  130. }
  131. }
  132. console.log(proxyObj);
  133. Object.keys(proxyObj).forEach(el => {
  134. _LCSDB.user().get('proxy').get(el).put(proxyObj[el]);
  135. })
  136. }
  137. async loadWorldsDefaults() {
  138. //load to DB default worlds
  139. let worldsResponse = await fetch('/world-files', { method: 'get' });
  140. let worldFiles = await worldsResponse.json();
  141. let filterworldFiles = worldFiles.filter(el => (el !== null));
  142. console.log(filterworldFiles);
  143. let worldsObj = {};
  144. for (var index in filterworldFiles) {
  145. let el = filterworldFiles[index];
  146. if (el) {
  147. let url = window.location.origin + el;
  148. var entryName = url.replace(window.location.origin + '/defaults/worlds/', "").split(".").join("_");
  149. let worldName = entryName.split("/")[0];
  150. let userPub = _LCSUSER.is.pub;
  151. let worldFile = await fetch(url, { method: 'get' });
  152. let worldSource = await worldFile.text();
  153. if (worldSource) {
  154. let modified = new Date().valueOf();
  155. let obj = {
  156. 'file': worldSource,
  157. 'modified': modified
  158. }
  159. if (!worldsObj[worldName]) {
  160. worldsObj[worldName] = {
  161. 'parent': '-',
  162. 'owner': userPub,
  163. 'featured': true,
  164. 'published': true
  165. }
  166. }
  167. let entry = entryName.replace(worldName + '/', "");
  168. worldsObj[worldName][entry] = obj;
  169. }
  170. }
  171. }
  172. console.log(worldsObj);
  173. Object.entries(worldsObj).forEach(el => {
  174. let worldName = el[0];
  175. let files = el[1];
  176. Object.entries(files).forEach(file => {
  177. _LCSDB.user().get('worlds').get(worldName).get(file[0]).put(file[1]);
  178. })
  179. })
  180. }
  181. async loadEmptyDefaultProto() {
  182. //empty proto world
  183. let userPub = _LCSUSER.is.pub;
  184. let worldsObj = {};
  185. let emptyWorld = {
  186. "index_vwf_yaml": YAML.stringify(
  187. {
  188. "extends": "http://vwf.example.com/aframe/ascene.vwf"
  189. }, 4),
  190. "index_vwf_config_yaml": YAML.stringify(
  191. {
  192. "info": {
  193. "title": "Empty World"
  194. },
  195. "model": {
  196. "vwf/model/aframe": null
  197. },
  198. "view": {
  199. "vwf/view/aframe": null,
  200. "vwf/view/editor-new": null
  201. }
  202. }, 4),
  203. "index_vwf_html": "",
  204. "appui_js": "",
  205. "info_json": JSON.stringify ({
  206. "info": {
  207. "en": {
  208. "title": "Empty World",
  209. "imgUrl": "",
  210. "text": "Empty World"
  211. },
  212. "ru": {
  213. "title": "Новый Мир",
  214. "imgUrl": "",
  215. "text": "Новый Мир"
  216. }
  217. }
  218. })
  219. }
  220. worldsObj['empty'] = {
  221. 'parent': '-',
  222. 'owner': userPub,
  223. 'featured': true,
  224. 'published': true
  225. }
  226. Object.keys(emptyWorld).forEach(el=>{
  227. let modified = new Date().valueOf();
  228. let obj = {
  229. 'file': emptyWorld[el],
  230. 'modified': modified
  231. }
  232. worldsObj['empty'][el] = obj;
  233. })
  234. console.log(worldsObj);
  235. Object.entries(worldsObj).forEach(el => {
  236. let worldName = el[0];
  237. let files = el[1];
  238. Object.entries(files).forEach(file => {
  239. _LCSDB.user().get('worlds').get(worldName).get(file[0]).put(file[1]);
  240. })
  241. })
  242. }
  243. //load defaults for first registered user running ./setup
  244. HandleSetupIndex() {
  245. window._app.hideProgressBar();
  246. window._app.hideUIControl();
  247. let el = document.createElement("div");
  248. el.setAttribute("id", "admin");
  249. document.body.appendChild(el);
  250. _LCSDB.on('auth',
  251. async function (ack) {
  252. if (_LCSUSER.is) {
  253. let setPubKey = {
  254. $cell: true,
  255. $components: [
  256. {
  257. $type: "p",
  258. class: "mdc-typography--headline5",
  259. $text: "1. Set app system user PUB key"
  260. },
  261. {
  262. $type: "button",
  263. class: "mdc-button mdc-button--raised",
  264. $text: "Set app PUB key",
  265. onclick: function (e) {
  266. console.log("admin action");
  267. _LCSDB.get('lcs/app').get('pub').put(_LCSUSER.is.pub);
  268. }
  269. }
  270. ]
  271. }
  272. let adminComponents = [];
  273. let defaultPub = await _LCSDB.get('lcs/app').get('pub').once().then();
  274. if (!defaultPub) {
  275. adminComponents.push(setPubKey);
  276. }
  277. if (_LCSUSER.is.pub == defaultPub) {
  278. let loadEmpty = {
  279. $cell: true,
  280. $components: [
  281. {
  282. $type: "p",
  283. class: "mdc-typography--headline5",
  284. $text: "3. Initialize empty World proto"
  285. },
  286. {
  287. $type: "button",
  288. id: "loadDefaults",
  289. class: "mdc-button mdc-button--raised",
  290. $text: "Init empty world",
  291. onclick: function (e) {
  292. console.log("admin action");
  293. window._app.loadEmptyDefaultProto();
  294. }
  295. }
  296. ]
  297. }
  298. let loadDefaults = {
  299. $cell: true,
  300. $components: [
  301. {
  302. $type: "p",
  303. class: "mdc-typography--headline5",
  304. $text: "4. Load Sample Worlds protos from server (optional)"
  305. },
  306. {
  307. $type: "button",
  308. id: "loadDefaults",
  309. class: "mdc-button mdc-button--raised",
  310. $text: "Load default worlds (from server)",
  311. onclick: function (e) {
  312. console.log("admin action");
  313. window._app.loadWorldsDefaults();
  314. }
  315. }
  316. ]
  317. }
  318. let loadDefaultsProxy = {
  319. $cell: true,
  320. $components: [
  321. {
  322. $type: "p",
  323. class: "mdc-typography--headline5",
  324. $text: "3. Load VWF & A-Frame default components"
  325. },
  326. {
  327. $type: "button",
  328. class: "mdc-button mdc-button--raised",
  329. $text: "Load defaults Proxy",
  330. onclick: function (e) {
  331. console.log("admin action");
  332. window._app.loadProxyDefaults();
  333. }
  334. }
  335. ]
  336. }
  337. adminComponents.push(setPubKey, loadDefaultsProxy, loadEmpty, loadDefaults);
  338. }
  339. document.querySelector("#admin").$cell({
  340. $cell: true,
  341. id: 'adminComponents',
  342. $type: "div",
  343. $components: adminComponents
  344. });
  345. }
  346. })
  347. }
  348. //TODO: profile
  349. HandleUserIndex(ctx) {
  350. console.log("USER INDEX");
  351. window._app.hideProgressBar();
  352. window._app.hideUIControl();
  353. _LCSDB.on('auth',
  354. async function (ack) {
  355. if(ack.pub){
  356. document.querySelector("#profile")._status = "User: " + _LCSUSER.is.alias //+' pub: ' + _LCSUSER.is.pub;
  357. document.querySelector("#profile").$update();
  358. }
  359. })
  360. let el = document.createElement("div");
  361. el.setAttribute("id", "userProfile");
  362. document.body.appendChild(el);
  363. let userProfile = {
  364. $type: 'div',
  365. id: "profile",
  366. _status: "",
  367. $init: function(){
  368. this._status = "user is not signed in..."
  369. },
  370. $update: function(){
  371. this.$components = [
  372. {
  373. $type: "h1",
  374. class: "mdc-typography--headline4",
  375. $text: this._status //"Profile for: " + _LCSUSER.is.alias
  376. }
  377. ]
  378. }
  379. }
  380. document.querySelector("#userProfile").$cell({
  381. $cell: true,
  382. $type: "div",
  383. $components: [userProfile]
  384. })
  385. }
  386. async HandleUserWorlds(ctx) {
  387. console.log("USER WORLDS INDEX");
  388. console.log(ctx.params);
  389. let user = ctx.params.user;
  390. page.redirect('/' + user + '/worlds/protos');
  391. }
  392. async HandleFileEdit(ctx) {
  393. console.log("USER WORLD FILE EDIT");
  394. let user = ctx.params.user;
  395. let worldName = ctx.params.name;
  396. let fileOriginal = ctx.params.file;
  397. let type = ctx.params.type;
  398. window._app.hideProgressBar();
  399. window._app.hideUIControl();
  400. _LCSDB.on('auth',
  401. async function (ack) {
  402. if (_LCSUSER.is) {
  403. if (_LCSUSER.is.alias == user) {
  404. var worldType = 'worlds';
  405. var file = fileOriginal;
  406. if (type == 'state') {
  407. worldType = 'documents';
  408. file = _app.helpers.replaceSubStringALL(fileOriginal, "~", '/');
  409. }
  410. let worldFile = await _LCSUSER.get(worldType).get(worldName).get(file).once().then();
  411. if (worldFile) {
  412. console.log(worldFile.file);
  413. let el = document.createElement("div");
  414. el.setAttribute("id", "worldFILE");
  415. document.body.appendChild(el);
  416. let aceEditorCell = {
  417. $type: "div",
  418. $components: [
  419. {
  420. class: "aceEditor",
  421. id: "aceEditor",
  422. //style: "width:1200px; height: 800px",
  423. $type: "div",
  424. $text: worldFile.file,
  425. $init: function () {
  426. var mode = "ace/mode/json";
  427. if (file.includes('_yaml'))
  428. mode = "ace/mode/yaml"
  429. if (file.includes('_js'))
  430. mode = "ace/mode/javascript"
  431. var editor = ace.edit("aceEditor");
  432. editor.setTheme("ace/theme/monokai");
  433. editor.setFontSize(16);
  434. editor.getSession().setMode(mode);
  435. editor.setOptions({
  436. maxLines: Infinity
  437. });
  438. }
  439. },
  440. {
  441. $type: "button",
  442. class: "mdc-button mdc-button--raised",
  443. $text: "Save",
  444. onclick: async function (e) {
  445. console.log("save new info");
  446. let editor = document.querySelector("#aceEditor").env.editor;
  447. let newInfo = editor.getValue();
  448. _LCSUSER.get(worldType).get(worldName).get(file).get('file').put(newInfo, res => {
  449. if (res) {
  450. let modified = new Date().valueOf();
  451. _LCSUSER.get(worldType).get(worldName).get(file).get('modified').put(modified);
  452. }
  453. })
  454. }
  455. },
  456. {
  457. $type: "button",
  458. class: "mdc-button mdc-button--raised",
  459. $text: "Close",
  460. onclick: function (e) {
  461. console.log("close");
  462. if (type == "proto")
  463. window.location.pathname = "/" + user + '/worlds/protos'
  464. if (type == "state")
  465. window.location.pathname = "/" + user + '/worlds/states'
  466. }
  467. }
  468. ]
  469. }
  470. document.querySelector("#worldFILE").$cell({
  471. $cell: true,
  472. $type: "div",
  473. $components: [aceEditorCell
  474. ]
  475. })
  476. }
  477. }
  478. }
  479. })
  480. }
  481. async HandleUserWorldsWithType(ctx) {
  482. console.log("USER WORLDS INDEX");
  483. console.log(ctx.params);
  484. let user = ctx.params.user;
  485. let type = ctx.params.type;
  486. window._app.hideProgressBar();
  487. window._app.hideUIControl();
  488. if (!_app.indexApp) {
  489. _app.indexApp = new IndexApp;
  490. document.querySelector('head').innerHTML += '<link rel="stylesheet" href="/web/index-app.css">';
  491. }
  492. if (!document.querySelector('#app')) {
  493. await _app.indexApp.initApp();
  494. }
  495. if (type == 'protos') {
  496. await _app.indexApp.getWorldsProtosFromUserDB(user);
  497. } else if (type == 'states') {
  498. await _app.indexApp.getWorldsFromUserDB(user);
  499. }
  500. }
  501. async HandleIndex() {
  502. console.log("INDEX");
  503. window._app.hideProgressBar();
  504. window._app.hideUIControl();
  505. _app.indexApp = new IndexApp;
  506. document.querySelector('head').innerHTML += '<link rel="stylesheet" href="/web/index-app.css">';
  507. await _app.indexApp.generateFrontPage();
  508. await _app.indexApp.initApp();
  509. await _app.indexApp.getAppDetailsFromDB();
  510. }
  511. HandleNoPage() {
  512. console.log("no such page")
  513. }
  514. //handle parcable requests
  515. HandleParsableLoadRequest(ctx) {
  516. let app = window._app;
  517. console.log(ctx.params);
  518. //var pathname = ctx.pathname;
  519. var spaceName = ctx.params.space;
  520. var saveName = ctx.params.savename;
  521. let user = ctx.params.user;
  522. page.redirect('/' + user + '/' + spaceName + '/' + app.helpers.GenerateInstanceID() + '/load/' + saveName);
  523. }
  524. HandleParsableLoadRequestWithRev(ctx) {
  525. let app = window._app;
  526. console.log(ctx.params);
  527. //var pathname = ctx.pathname;
  528. var spaceName = ctx.params.space;
  529. var saveName = ctx.params.savename;
  530. var rev = ctx.params.rev;
  531. let user = ctx.params.user;
  532. page.redirect('/' + user + '/' + spaceName + '/' + app.helpers.GenerateInstanceID() + '/load/' + saveName + '/' + rev);
  533. }
  534. async setUserPaths(user) {
  535. await _LCSDB.get('users').get(user).get('pub').once(res => {
  536. if (res)
  537. window._LCS_WORLD_USER = _LCSDB.user(res);
  538. }).then();
  539. }
  540. async HandleParsableRequestGenID(ctx) {
  541. let app = window._app;
  542. console.log(ctx.params);
  543. let user = ctx.params.user;
  544. var pathname = ctx.pathname;
  545. await app.setUserPaths(user);
  546. if (pathname[pathname.length - 1] == '/') {
  547. pathname = pathname.slice(0, -1)
  548. }
  549. let pathToParse = pathname.replace('/' + user, "");
  550. app.helpers.Process(pathToParse).then(parsedRequest => {
  551. localStorage.setItem('lcs_app', JSON.stringify({ path: parsedRequest }));
  552. console.log(parsedRequest);
  553. if ((parsedRequest['instance'] == undefined) && (parsedRequest['private_path'] == undefined) && (parsedRequest['public_path'] !== "/") && (parsedRequest['application'] !== undefined)) {
  554. page.redirect(pathname + '/' + app.helpers.GenerateInstanceID());
  555. }
  556. });
  557. }
  558. async HandleParsableRequestWithID(ctx) {
  559. let app = window._app;
  560. console.log(ctx.params);
  561. var pathname = ctx.pathname;
  562. let user = ctx.params.user;
  563. if (pathname[pathname.length - 1] == '/') {
  564. pathname = pathname.slice(0, -1)
  565. }
  566. await app.setUserPaths(user);
  567. let pathToParse = pathname.replace('/' + user, "");
  568. app.helpers.Process(pathToParse).then(parsedRequest => {
  569. localStorage.setItem('lcs_app', JSON.stringify({ path: parsedRequest }));
  570. console.log(parsedRequest);
  571. var userLibraries = { model: {}, view: {} };
  572. var application;
  573. vwf.loadConfiguration(application, userLibraries, compatibilityCheck);
  574. });
  575. }
  576. async HandleParsableRequest(ctx) {
  577. let app = window._app;
  578. console.log(ctx.params);
  579. var pathname = ctx.pathname;
  580. if (pathname[pathname.length - 1] == '/') {
  581. pathname = pathname.slice(0, -1)
  582. }
  583. var parsedRequest = await app.helpers.Process(pathname);
  584. localStorage.setItem('lcs_app', JSON.stringify({ path: parsedRequest }));
  585. console.log(parsedRequest);
  586. if ((parsedRequest['instance'] == undefined) && (parsedRequest['private_path'] == undefined) && (parsedRequest['public_path'] !== "/") && (parsedRequest['application'] !== undefined)) {
  587. // Redirect if the url request does not include an application/file && a default 'index.vwf.yaml' exists
  588. // page.redirect(pathname + '/' + app.helpers.GenerateInstanceID());
  589. window.location.pathname = pathname + '/' + app.helpers.GenerateInstanceID()
  590. //return true;
  591. } else {
  592. //return false;
  593. }
  594. var userLibraries = { model: {}, view: {} };
  595. var application;
  596. vwf.loadConfiguration(application, userLibraries, compatibilityCheck);
  597. }
  598. //get DB application state information for reflector (called from VWF)
  599. async getApplicationState() {
  600. let dataJson = JSON.parse(localStorage.getItem('lcs_app'));
  601. if (dataJson) {
  602. if (!dataJson.path['instance']) return undefined;
  603. }
  604. let userAlias = await _LCS_WORLD_USER.get('alias').once().then();
  605. let userPub = await _LCSDB.get('users').get(userAlias).get('pub').once().then();
  606. let loadInfo = await this.getLoadInformation(dataJson);
  607. let saveInfo = await this.loadSaveObject(loadInfo);
  608. let loadObj = {
  609. loadInfo: loadInfo,
  610. path: dataJson.path,
  611. saveObject: saveInfo,
  612. user: userAlias
  613. }
  614. console.log(loadObj);
  615. //temporary solution for syncing DB replicas using Gun.load()
  616. await _LCS_SYS_USER.get('proxy').load(res=>{}, {wait: 200}).then();
  617. await _LCSDB.user(userPub).get('worlds').get(loadObj.path.public_path.slice(1)).load(res=>{}, {wait: 200}).then();
  618. return loadObj
  619. }
  620. // LookupSaveRevisions takes the public path and the name of a save, and provides
  621. // an array of all revisions for that save. (If the save does not exist, this will be
  622. // an empty array).
  623. async lookupSaveRevisions(public_path, save_name) {
  624. var result = [];
  625. var states = [];
  626. let docName = 'savestate_/' + public_path + '/' + save_name + '_vwf_json';
  627. let revs = await _LCS_WORLD_USER.get('documents').get(public_path).get(docName).get('revs').once().then();
  628. if (revs) {
  629. for (const res of Object.keys(revs)) {
  630. if (res !== '_') {
  631. let el = await _LCS_WORLD_USER.get('documents').get(public_path).get(docName).get('revs').get(res).once().then();
  632. if (el)
  633. result.push(parseInt(el.revision));
  634. }
  635. }
  636. return result
  637. }
  638. }
  639. // GetLoadInformation receives a parsed request {private_path, public_path, instance, application} and returns the
  640. // details of the save that is designated by the initial request. The details are returned in an object
  641. // composed of: save_name (name of the save) save_revision (revision of the save), explicit_revision (boolean, true if the request
  642. // explicitly specified the revision, false if it did not), and application_path (the public_path of the application this is a save for).
  643. async getLoadInformation(response) {
  644. let parsedRequest = response.path;
  645. var result = { 'save_name': undefined, 'save_revision': undefined, 'explicit_revision': undefined, 'application_path': undefined };
  646. if (parsedRequest['private_path']) {
  647. var segments = this.helpers.GenerateSegments(parsedRequest['private_path']);
  648. if ((segments.length > 1) && (segments[0] == "load")) {
  649. var potentialRevisions = await this.lookupSaveRevisions((parsedRequest['public_path']).slice(1), segments[1]);
  650. console.log('!!!!! - ', potentialRevisions);
  651. if (potentialRevisions.length > 0) {
  652. result['save_name'] = segments[1];
  653. if (segments.length > 2) {
  654. var requestedRevision = parseInt(segments[2]);
  655. if (requestedRevision) {
  656. if (potentialRevisions.indexOf(requestedRevision) > -1) {
  657. result['save_revision'] = requestedRevision;
  658. result['explicit_revision'] = true;
  659. result['application_path'] = parsedRequest['public_path'];
  660. }
  661. }
  662. }
  663. if (result['explicit_revision'] == undefined) {
  664. result['explicit_revision'] = false;
  665. potentialRevisions.sort();
  666. result['save_revision'] = potentialRevisions.pop();
  667. result['application_path'] = parsedRequest['public_path'];
  668. }
  669. }
  670. }
  671. }
  672. return result;
  673. }
  674. async loadSaveObject(loadInfo) {
  675. //let objName = loadInfo[ 'save_name' ] +'/'+ "savestate_" + loadInfo[ 'save_revision' ];
  676. let objName = "savestate_" + loadInfo['application_path'] + '/' + loadInfo['save_name'] + '_vwf_json';
  677. let objNameRev = "savestate_" + loadInfo['save_revision'] + loadInfo['application_path'] + '/' + loadInfo['save_name'] + '_vwf_json';
  678. // if(loadInfo[ 'save_revision' ]){
  679. // }
  680. let worldName = this.helpers.appPath //loadInfo[ 'application_path' ].slice(1);
  681. let saveObject = await _LCS_WORLD_USER.get('documents').get(worldName).get(objName).get('revs').get(objNameRev).once().then();
  682. let saveInfo = saveObject ? JSON.parse(saveObject.jsonState) : saveObject;
  683. return saveInfo;
  684. }
  685. // GetSaveInformation is a helper function that takes the application_path (/path/to/application).
  686. // It returns an array of all saves found for that
  687. // application (including separate entries for individual revisions of saves ).
  688. async getSaveInformation(application_path, userPUB) {
  689. var result = [];
  690. let user = _LCSDB.user(userPUB);
  691. var docName = application_path.slice(1);
  692. let potentialSaveNames = await user.get('documents').get(docName).once().then();
  693. if (potentialSaveNames) {
  694. for (const res of Object.keys(potentialSaveNames)) {
  695. if (res !== '_') {
  696. let el = await user.get('documents').path(docName).get(res).once().then();
  697. let revisionList = await this.lookupSaveRevisions(application_path.slice(1), el.filename);
  698. var latestsave = true;
  699. revisionList.sort();
  700. while (revisionList.length > 0) {
  701. var newEntry = {};
  702. newEntry['applicationpath'] = application_path;
  703. newEntry['savename'] = el.filename;
  704. newEntry['revision'] = revisionList.pop().toString();
  705. newEntry['latestsave'] = latestsave;
  706. if (latestsave) {
  707. newEntry['url'] = this.helpers.JoinPath(window.location.origin, application_path, "load", el.filename + "/");
  708. }
  709. else {
  710. newEntry['url'] = this.helpers.JoinPath(window.location.origin, application_path, "load", el.filename + "/", newEntry['revision'] + "/");
  711. }
  712. latestsave = false;
  713. result.push(newEntry);
  714. }
  715. }
  716. }
  717. }
  718. return result;
  719. }
  720. async getProtoWorldFiles(userPub, worldName, date) {
  721. let fileNamesAll = await _LCSDB.user(userPub).get('worlds').get(worldName).once().then();
  722. let worldFileNames = Object.keys(fileNamesAll).filter(el => (el !== '_') && (el !== 'owner') && (el !== 'parent')
  723. && (el !== 'info_json'));
  724. let worldObj = {};
  725. for (var el in worldFileNames) {
  726. let fn = worldFileNames[el];
  727. let res = await _LCSDB.user(userPub).get('worlds').get(worldName).get(fn).once().then();
  728. var data = {
  729. 'file': res.file,
  730. 'modified': res.modified
  731. }
  732. if (!date) {
  733. data = {
  734. 'file': res.file
  735. }
  736. }
  737. worldObj[fn] = data;
  738. }
  739. console.log(worldObj);
  740. return worldObj
  741. }
  742. async cloneWorldPrototype(worldName, userName, newWorldName) {
  743. let userPub = await _LCSDB.get('users').get(userName).get('pub').once().then();
  744. //let worldProto = await _LCSDB.user(userPub).get('worlds').get(worldName).once().then();
  745. var worldID = window._app.helpers.GenerateInstanceID().toString();
  746. if (newWorldName) {
  747. worldID = newWorldName
  748. }
  749. //let modified = new Date().valueOf();
  750. console.log('clone: ' + worldName + 'to: ' + worldID);
  751. let newOwner = _LCSUSER.is.pub;
  752. let worldObj = {
  753. 'owner': newOwner,
  754. 'parent': userName + '/' + worldName
  755. };
  756. let fileNamesAll = await _LCSDB.user(userPub).get('worlds').get(worldName).once().then();
  757. let worldFileNames = Object.keys(fileNamesAll).filter(el => (el !== '_') && (el !== 'owner') && (el !== 'parent'));
  758. for (var el in worldFileNames) {
  759. let fn = worldFileNames[el];
  760. let res = await _LCSDB.user(userPub).get('worlds').get(worldName).get(fn).once().then();
  761. let data = {
  762. 'file': res.file,
  763. 'modified': res.modified
  764. }
  765. worldObj[fn] = data;
  766. }
  767. console.log(worldObj);
  768. Object.keys(worldObj).forEach(el => {
  769. _LCSUSER.get('worlds').get(worldID).get(el).put(worldObj[el]);
  770. })
  771. }
  772. async cloneWorldState(filename) {
  773. let myWorldProtos = await _LCSUSER.get('worlds').once().then();
  774. let userName = this.helpers.worldUser;
  775. let userPub = await _LCSDB.get('users').get(userName).get('pub').once().then();
  776. let protoUserRoot = this.helpers.getRoot(true).root;
  777. //let myName = _LCSUSER.is.alias;
  778. //let proto = Object.keys(myWorldProtos).filter(el => el == protoUserRoot);
  779. var protosKeys = [];
  780. if (myWorldProtos)
  781. protosKeys = Object.keys(myWorldProtos);
  782. if (protosKeys.includes(protoUserRoot)) {
  783. let userProtoFiles = await this.getProtoWorldFiles(userPub, protoUserRoot);
  784. let myProtoFiles = await this.getProtoWorldFiles(_LCSUSER.is.pub, protoUserRoot);
  785. let hashUP = await this.helpers.sha256(JSON.stringify(userProtoFiles));
  786. let hashMP = await this.helpers.sha256(JSON.stringify(myProtoFiles));
  787. if (hashUP == hashMP) {
  788. this.saveStateAsFile(filename);
  789. } else {
  790. let noty = new Noty({
  791. text: 'world prototype is modified.. could not clone world state',
  792. timeout: 2000,
  793. theme: 'mint',
  794. layout: 'bottomRight',
  795. type: 'error'
  796. });
  797. noty.show();
  798. }
  799. } else {
  800. await this.cloneWorldPrototype(protoUserRoot, userName, protoUserRoot);
  801. this.saveStateAsFile(filename);
  802. }
  803. }
  804. //TODO: refactor and config save
  805. saveStateAsFile(filename, otherProto) // invoke with the view as "this"
  806. {
  807. console.log("Saving: " + filename);
  808. //var clients = this.nodes["http://vwf.example.com/clients.vwf"];
  809. // Save State Information
  810. var state = vwf.getState();
  811. state.nodes[0].children = {};
  812. var timestamp = state["queue"].time;
  813. timestamp = Math.round(timestamp * 1000);
  814. var objectIsTypedArray = function (candidate) {
  815. var typedArrayTypes = [
  816. Int8Array,
  817. Uint8Array,
  818. // Uint8ClampedArray,
  819. Int16Array,
  820. Uint16Array,
  821. Int32Array,
  822. Uint32Array,
  823. Float32Array,
  824. Float64Array
  825. ];
  826. var isTypedArray = false;
  827. if (typeof candidate == "object" && candidate != null) {
  828. typedArrayTypes.forEach(function (typedArrayType) {
  829. isTypedArray = isTypedArray || candidate instanceof typedArrayType;
  830. });
  831. }
  832. return isTypedArray;
  833. };
  834. var transitTransformation = function (object) {
  835. return objectIsTypedArray(object) ?
  836. Array.prototype.slice.call(object) : object;
  837. };
  838. let jsonValuePure = require("vwf/utility").transform(
  839. state, transitTransformation
  840. );
  841. //remove all Ohm generated grammarsfrom state
  842. let jsonValue = _app.helpers.removeGrammarObj(jsonValuePure);
  843. var jsonState = JSON.stringify(jsonValue);
  844. let rootPath = this.helpers.getRoot(true);
  845. var inst = rootPath.inst;
  846. if (filename == '') filename = inst;
  847. //if (root.indexOf('.vwf') != -1) root = root.substring(0, root.lastIndexOf('/'));
  848. var root = rootPath.root;
  849. var json = jsonState;
  850. if (otherProto) {
  851. console.log('need to modify state...');
  852. json = this.helpers.replaceSubStringALL(jsonState, '/' + root + '/', '/' + otherProto + '/');//jsonState.replace(('/' + root + '/'), ('/' + otherProto +'/') );
  853. root = otherProto;
  854. console.log(json);
  855. }
  856. //var documents = _LCSUSER.get('documents');
  857. var saveRevision = new Date().valueOf();
  858. var stateForStore = {
  859. "root": root,
  860. "filename": filename,
  861. "inst": inst,
  862. "timestamp": timestamp,
  863. "extension": ".vwf.json",
  864. "jsonState": json,
  865. "publish": true
  866. };
  867. //let objName = loadInfo[ 'save_name' ] +'/'+ "savestate_" + loadInfo[ 'save_revision' ];
  868. // "savestate_" + loadInfo[ 'save_revision' ] + '/' + loadInfo[ 'save_name' ] + '_vwf_json'
  869. var docName = 'savestate_/' + root + '/' + filename + '_vwf_json';
  870. _LCSUSER.get('documents').get(root).get(docName).put(stateForStore, res => {
  871. if (res) {
  872. let noty = new Noty({
  873. text: 'Saved to ' + docName,
  874. timeout: 2000,
  875. theme: 'mint',
  876. layout: 'bottomRight',
  877. type: 'success'
  878. });
  879. noty.show();
  880. }
  881. });
  882. _LCSUSER.get('worlds').get(root).get('info_json').once(res => {
  883. if (res) {
  884. let modified = new Date().valueOf();
  885. let newOwner = _LCSUSER.is.pub;
  886. let userName = _LCSUSER.is.alias;
  887. let obj = {
  888. 'parent': userName + '/' + root,
  889. 'owner': newOwner,
  890. 'file': res.file,
  891. 'modified': modified
  892. }
  893. let docInfoName = 'savestate_/' + root + '/' + filename + '_info_vwf_json';
  894. _LCSUSER.get('documents').get(root).get(docInfoName).not(res => {
  895. _LCSUSER.get('documents').get(root).get(docInfoName).put(obj);
  896. });
  897. }
  898. });
  899. var docNameRev = 'savestate_' + saveRevision.toString() + '/' + root + '/' + filename + '_vwf_json';
  900. _LCSUSER.get('documents').get(root).get(docName).get('revs').get(docNameRev).put(stateForStore)
  901. .path("revision").put(saveRevision);
  902. // Save Config Information
  903. var config = { "info": {}, "model": {}, "view": {} };
  904. // Save browser title
  905. config["info"]["title"] = document.title//$('title').html();
  906. // Save model drivers
  907. Object.keys(vwf_view.kernel.kernel.models).forEach(function (modelDriver) {
  908. if (modelDriver.indexOf('vwf/model/') != -1) config["model"][modelDriver] = "";
  909. });
  910. // If neither glge or threejs model drivers are defined, specify nodriver
  911. if (config["model"]["vwf/model/glge"] === undefined && config["model"]["vwf/model/threejs"] === undefined) config["model"]["nodriver"] = "";
  912. // Save view drivers and associated parameters, if any
  913. Object.keys(vwf_view.kernel.kernel.views).forEach(function (viewDriver) {
  914. if (viewDriver.indexOf('vwf/view/') != -1) {
  915. if (vwf_view.kernel.kernel.views[viewDriver].parameters) {
  916. config["view"][viewDriver] = vwf_view.kernel.kernel.views[viewDriver].parameters;
  917. }
  918. else config["view"][viewDriver] = "";
  919. }
  920. });
  921. //var jsonConfig = $.encoder.encodeForURL(JSON.stringify(config));
  922. var jsonConfig = JSON.stringify(config);
  923. let configStateForStore = {
  924. "root": root,
  925. "filename": filename,
  926. "inst": inst,
  927. "timestamp": timestamp,
  928. "extension": "config.vwf.json",
  929. "jsonState": jsonConfig
  930. };
  931. //let objName = loadInfo[ 'save_name' ] +'/'+ "savestate_" + loadInfo[ 'save_revision' ];
  932. // "savestate_" + loadInfo[ 'save_revision' ] + '/' + loadInfo[ 'save_name' ] + '_vwf_json'
  933. // let configName = 'savestate_/' + root + '/' + filename + '_config_vwf_json';
  934. // let documentSaveConfigState = _LCSUSER.get(configName).put(configStateForStore);
  935. // //documents.path(root).set(documentSaveConfigState);
  936. // let configNameRev = 'savestate_' + saveRevision.toString() + '/' + root + '/' + filename + '_config_vwf_json';
  937. // _LCSUSER.get(configNameRev).put(configStateForStore);
  938. // _LCSUSER.get(configNameRev).path("revision").put(saveRevision);
  939. //documentSaveConfigState.path('revs').set(documentSaveStateRevision);
  940. // Save config file to server
  941. // var xhrConfig = new XMLHttpRequest();
  942. // xhrConfig.open("POST", "/" + root + "/save/" + filename, true);
  943. // xhrConfig.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  944. // xhrConfig.send("root=" + root + "/" + filename + "&filename=saveState&inst=" + inst + "&timestamp=" + timestamp + "&extension=.vwf.config.json" + "&jsonState=" + jsonConfig);
  945. }
  946. // LoadSavedState
  947. async loadSavedState(filename, applicationpath, revision) {
  948. console.log("Loading: " + filename);
  949. let userName = await _LCS_WORLD_USER.get('alias').once().then();
  950. if (revision) {
  951. window.location.pathname = '/' + userName + applicationpath + '/load/' + filename + '/' + revision + '/';
  952. }
  953. else { // applicationpath + "/" + inst + '/load/' + filename + '/';
  954. window.location.pathname = '/' + userName + applicationpath + '/load/' + filename + '/';
  955. }
  956. }
  957. hideUIControl() {
  958. var el = document.getElementById("ui-controls");
  959. if (el) {
  960. el.classList.remove("visible");
  961. el.classList.add("not-visible");
  962. }
  963. }
  964. showUIControl() {
  965. var el = document.getElementById("ui-controls");
  966. if (el) {
  967. el.classList.remove("not-visible");
  968. el.classList.add("visible");
  969. }
  970. }
  971. hideProgressBar() {
  972. var progressbar = document.getElementById("load-progressbar");
  973. if (progressbar) {
  974. progressbar.classList.remove("visible");
  975. progressbar.classList.add("not-visible");
  976. progressbar.classList.add("mdc-linear-progress--closed");
  977. }
  978. }
  979. showProgressBar() {
  980. let progressbar = document.getElementById("load-progressbar");
  981. if (progressbar) {
  982. progressbar.classList.add("visible");
  983. progressbar.classList.add("mdc-linear-progress--indeterminate");
  984. }
  985. }
  986. }
  987. export { App }