app.js 62 KB

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