app.js 65 KB

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