app.js 62 KB

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