app.js 57 KB

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