app.js 66 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272
  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') && (typeof source !== 'object')) {
  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. await loadjs([
  828. '/vwf/model/aframe/aframe-master.min.js',
  829. '/vwf/model/aframe/extras/aframe-extras.loaders.js',
  830. '/vwf/model/aframe/extras/aframe-extras.controls.min.js',
  831. '/vwf/model/aframe/kframe/aframe-aabb-collider-component.min.js',
  832. '/vwf/model/aframe/addon/aframe-interpolation.js',
  833. '/vwf/model/aframe/addon/aframe-sun-sky.js',
  834. '/vwf/model/aframe/addon/SkyShader.js',
  835. '/vwf/model/aframe/addon/BVHLoader.js',
  836. '/vwf/model/aframe/addon/TransformControls.js',
  837. '/vwf/model/aframe/addon/THREE.MeshLine.js',
  838. '/vwf/model/aframe/addon/aframe-components.js',
  839. '/vwf/view/arjs/aframe-ar.js'
  840. ],{
  841. async: false,
  842. returnPromise: true
  843. });
  844. return loadjs([
  845. '/lib/compatibilitycheck.js',
  846. '/vwf/view/webrtc/adapter-latest.js',
  847. '/lib/draggabilly/draggabilly.pkgd.js',
  848. '/vwf/model/aframe/addon/virtualgc/nipplejs.js',
  849. '/lib/lively.vm_standalone.js',
  850. '/lib/require.js',
  851. '/lib/crypto.js',
  852. '/lib/md5.js',
  853. '/lib/alea.js',
  854. '/lib/mash.js',
  855. '/vwf.js'
  856. ], {
  857. async: false,
  858. returnPromise: true
  859. })
  860. }
  861. //get DB application state information for reflector (called from VWF)
  862. async getApplicationState() {
  863. let dataJson = JSON.parse(localStorage.getItem('lcs_app'));
  864. if (dataJson) {
  865. if (!dataJson.path['instance']) return undefined;
  866. }
  867. //let userAlias = await _LCS_WORLD_USER.get('alias').once().then();
  868. // let userPub = await _LCSDB.get('users').get(userAlias).get('pub').once().then();
  869. let userAlias = _LCS_WORLD_USER.alias;
  870. let userPub = _LCS_WORLD_USER.pub;
  871. let loadInfo = await this.getLoadInformation(dataJson);
  872. let saveInfo = await this.loadSaveObject(loadInfo);
  873. let loadObj = {
  874. loadInfo: loadInfo,
  875. path: dataJson.path,
  876. saveObject: saveInfo,
  877. user: userAlias
  878. }
  879. //dataJson.app = loadObj;
  880. localStorage.setItem('lcs_app', JSON.stringify(loadObj));
  881. console.log(loadObj);
  882. //temporary solution for syncing DB replicas using Gun.load()
  883. // _LCS_SYS_USER.get('proxy').load(res=>{
  884. // if (res)
  885. // {console.log('proxy loaded');
  886. // _LCSDB.user(userPub).get('worlds').get(loadObj.path.public_path.slice(1)).load(w=>{
  887. // if (w) {
  888. // console.log('world files loaded');
  889. // vwf.ready( vwf.application, loadObj)
  890. // }
  891. // });
  892. // }
  893. // });
  894. return loadObj
  895. }
  896. // LookupSaveRevisions takes the public path and the name of a save, and provides
  897. // an array of all revisions for that save. (If the save does not exist, this will be
  898. // an empty array).
  899. async lookupSaveRevisions(public_path, save_name, userPub) {
  900. var pub = "";
  901. if (!_LCS_WORLD_USER) {
  902. pub = userPub;
  903. } else {
  904. pub = _LCS_WORLD_USER.pub
  905. }
  906. let userDB = _LCSDB.user(pub);
  907. var result = [];
  908. var states = [];
  909. let docName = 'savestate_/' + public_path + '/' + save_name + '_vwf_json';
  910. let revs = await userDB.get('documents').get(public_path).get(docName).get('revs').promOnce();
  911. if (revs) {
  912. if(revs.data) {
  913. for (const res of Object.keys(revs.data)) {
  914. if (res !== '_') {
  915. let el = await userDB.get('documents').get(public_path).get(docName).get('revs').get(res).promOnce();
  916. if (el)
  917. result.push(parseInt(el.data.revision));
  918. }
  919. }
  920. return result
  921. }
  922. }
  923. }
  924. // GetLoadInformation receives a parsed request {private_path, public_path, instance, application} and returns the
  925. // details of the save that is designated by the initial request. The details are returned in an object
  926. // composed of: save_name (name of the save) save_revision (revision of the save), explicit_revision (boolean, true if the request
  927. // explicitly specified the revision, false if it did not), and application_path (the public_path of the application this is a save for).
  928. async getLoadInformation(response) {
  929. let parsedRequest = response.path;
  930. var result = { 'save_name': undefined, 'save_revision': undefined, 'explicit_revision': undefined, 'application_path': undefined };
  931. if (parsedRequest['private_path']) {
  932. var segments = this.helpers.GenerateSegments(parsedRequest['private_path']);
  933. if ((segments.length > 1) && (segments[0] == "load")) {
  934. var potentialRevisions = await this.lookupSaveRevisions((parsedRequest['public_path']).slice(1), segments[1]);
  935. console.log('!!!!! - ', potentialRevisions);
  936. if (potentialRevisions.length > 0) {
  937. result['save_name'] = segments[1];
  938. if (segments.length > 2) {
  939. var requestedRevision = parseInt(segments[2]);
  940. if (requestedRevision) {
  941. if (potentialRevisions.indexOf(requestedRevision) > -1) {
  942. result['save_revision'] = requestedRevision;
  943. result['explicit_revision'] = true;
  944. result['application_path'] = parsedRequest['public_path'];
  945. }
  946. }
  947. }
  948. if (result['explicit_revision'] == undefined) {
  949. result['explicit_revision'] = false;
  950. potentialRevisions.sort();
  951. result['save_revision'] = potentialRevisions.pop();
  952. result['application_path'] = parsedRequest['public_path'];
  953. }
  954. }
  955. }
  956. }
  957. return result;
  958. }
  959. async loadSaveObject(loadInfo) {
  960. //let objName = loadInfo[ 'save_name' ] +'/'+ "savestate_" + loadInfo[ 'save_revision' ];
  961. let userDB = _LCSDB.user(_LCS_WORLD_USER.pub);
  962. if (!loadInfo.save_name) {
  963. return undefined
  964. }
  965. let objName = "savestate_" + loadInfo['application_path'] + '/' + loadInfo['save_name'] + '_vwf_json';
  966. let objNameRev = "savestate_" + loadInfo['save_revision'] + loadInfo['application_path'] + '/' + loadInfo['save_name'] + '_vwf_json';
  967. // if(loadInfo[ 'save_revision' ]){
  968. // }
  969. let worldName = this.helpers.appPath //loadInfo[ 'application_path' ].slice(1);
  970. let saveObject = (await userDB.get('documents').get(worldName).get(objName).get('revs').get(objNameRev).promOnce()).data;
  971. var saveInfo = null;
  972. if (saveObject) {
  973. saveInfo = (typeof (saveObject.jsonState) == 'object') ? saveObject.jsonState : JSON.parse(saveObject.jsonState);
  974. }
  975. //typeof(saveObject == 'object')
  976. return saveInfo;
  977. }
  978. // GetSaveInformation is a helper function that takes the application_path (/path/to/application).
  979. // It returns an array of all saves found for that
  980. // application (including separate entries for individual revisions of saves ).
  981. async getSaveInformation(application_path, userPUB) {
  982. var result = [];
  983. let user = _LCSDB.user(userPUB);
  984. var docName = application_path.slice(1);
  985. let potentialSaveNames = (await user.get('documents').get(docName).promOnce()).data;
  986. if (potentialSaveNames) {
  987. for (const res of Object.keys(potentialSaveNames)) {
  988. if (res !== '_') {
  989. let el = (await user.get('documents').path(docName).get(res).promOnce()).data;
  990. let revisionList = await this.lookupSaveRevisions(application_path.slice(1), el.filename);
  991. var latestsave = true;
  992. revisionList.sort();
  993. while (revisionList.length > 0) {
  994. var newEntry = {};
  995. newEntry['applicationpath'] = application_path;
  996. newEntry['savename'] = el.filename;
  997. newEntry['revision'] = revisionList.pop().toString();
  998. newEntry['latestsave'] = latestsave;
  999. if (latestsave) {
  1000. newEntry['url'] = this.helpers.JoinPath(window.location.origin, application_path, "load", el.filename + "/");
  1001. }
  1002. else {
  1003. newEntry['url'] = this.helpers.JoinPath(window.location.origin, application_path, "load", el.filename + "/", newEntry['revision'] + "/");
  1004. }
  1005. latestsave = false;
  1006. result.push(newEntry);
  1007. }
  1008. }
  1009. }
  1010. }
  1011. return result;
  1012. }
  1013. async getProtoWorldFiles(userPub, worldName, date) {
  1014. let fileNamesAll = (await _LCSDB.user(userPub).get('worlds').get(worldName).promOnce()).data;
  1015. 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'));
  1016. let worldObj = {};
  1017. for (var doc in worldFileNames) {
  1018. let fn = worldFileNames[doc];
  1019. let res = (await _LCSDB.user(userPub).get('worlds').get(worldName).get(fn).promOnce()).data;
  1020. var data = {
  1021. 'file': res.file,
  1022. 'modified': res.modified,
  1023. 'created': res.created
  1024. }
  1025. if (!date) {
  1026. data = {
  1027. 'file': res.file
  1028. }
  1029. }
  1030. worldObj[fn] = data;
  1031. }
  1032. console.log(worldObj);
  1033. return worldObj
  1034. }
  1035. async cloneWorldPrototype(worldName, userName, newWorldName, stateFileName) {
  1036. let self = this;
  1037. _app.showProgressBar();
  1038. //let users = await _LCSDB.get('users').then();
  1039. let userPub = (await _LCSDB.get('users').get(userName).get('pub').promOnce()).data;
  1040. let newOwner = _LCSDB.user().is.pub;
  1041. let myWorlds = (await _LCSDB.user(newOwner).get('worlds').promOnce()).data;
  1042. //if (!myWorlds) _LCSDB.user(newOwner).get('worlds').put({});
  1043. _LCSDB.user(newOwner).get('worlds').not(res=>{
  1044. _LCSDB.user(newOwner).get('worlds').put({});
  1045. })
  1046. if(myWorlds) {
  1047. let checkExist = Object.keys(myWorlds).filter(el=> el == newWorldName);
  1048. if (newWorldName) {
  1049. //let worldProto = (await _LCSDB.user(newOwner).get('worlds').get(newWorldName).promOnce()).data;
  1050. if (checkExist.length > 0 && myWorlds[newWorldName]) {
  1051. console.log('already exist!');
  1052. return
  1053. }
  1054. }
  1055. }
  1056. var worldID = window._app.helpers.GenerateInstanceID().toString();
  1057. if (newWorldName) {
  1058. worldID = newWorldName
  1059. }
  1060. //let modified = new Date().valueOf();
  1061. console.log('clone: ' + worldName + 'to: ' + worldID);
  1062. let created = new Date().valueOf();
  1063. let worldObj = {
  1064. 'owner': newOwner,
  1065. 'parent': userName + '/' + worldName,
  1066. 'featured': true,
  1067. 'published': true
  1068. };
  1069. // let fileNamesAll =
  1070. await _LCSDB.user(userPub).get('worlds').get(worldName).load(all=> {
  1071. let worldFileNames = Object.keys(all).filter(el => (el !== '_') && (el !== 'owner') && (el !== 'parent') && (el !== 'featured') && (el !== 'published') && (el !== '_config_yaml') && (el !== '_yaml') && (el !== '_html'));
  1072. for (var doc in worldFileNames) {
  1073. let fn = worldFileNames[doc];
  1074. let res = all[fn]; //(await _LCSDB.user(userPub).get('worlds').get(worldName).get(fn).promOnce()).data;
  1075. let fileData = (typeof res.file == 'object')? JSON.stringify(res.file):res.file;
  1076. let data = {
  1077. 'file': fileData, //JSON.stringify(res.file),
  1078. 'modified': created
  1079. }
  1080. worldObj[fn] = data;
  1081. }
  1082. console.log(worldObj);
  1083. // for (const obj of Object.keys(worldObj)) {
  1084. // let myWorlds = _LCSDB.user().get('worlds');
  1085. // let myNewWorld = myWorlds.get(worldID);
  1086. // myNewWorld.get(obj).put(worldObj[obj]);
  1087. // }
  1088. //let myWorlds = await _LCSDB.user(newOwner).get('worlds').once().then();
  1089. let myWorld = _LCSDB.user(newOwner).get('worlds').get(worldID).put({});
  1090. myWorld.put(worldObj, function (res) {
  1091. if(stateFileName){
  1092. self.saveStateAsFile(stateFileName)
  1093. }
  1094. console.log(res)
  1095. }); //.get(worldID) let myWorld =
  1096. // let myWorld = _LCSDB.user().get(worldID).put(worldObj);
  1097. // _LCSDB.user().get('worlds').set(myWorld);
  1098. _app.hideProgressBar();
  1099. console.log('CLONED!!!');
  1100. let appEl = document.createElement("div");
  1101. appEl.setAttribute("id", 'cloneLink');
  1102. let entry = document.querySelector('#worldActionsGUI');
  1103. if (entry) {
  1104. entry.appendChild(appEl);
  1105. document.querySelector("#cloneLink").$cell({
  1106. id: 'cloneLink',
  1107. $cell: true,
  1108. $type: "div",
  1109. $components: [
  1110. {
  1111. $type: "a",
  1112. class: "mdc-button mdc-button--raised mdc-card__action",
  1113. $text: "Go to new cloned World!",
  1114. onclick: function (e) {
  1115. let myName = _LCSDB.user().is.alias;
  1116. window.location.pathname = '/' + myName + '/' + worldID + '/about'
  1117. }
  1118. }
  1119. ]
  1120. })
  1121. }
  1122. },{wait: 500}).then();
  1123. //window.location.pathname = '/' + userName + '/' + worldID + '/about'
  1124. //page()
  1125. // Object.keys(worldObj).forEach(el => {
  1126. // this.db.user().get('worlds').get(worldID).get(el).put(worldObj[el]);
  1127. // })
  1128. }
  1129. async cloneWorldState(filename) {
  1130. let myWorldProtos = (await _LCSDB.user().get('worlds').promOnce()).data;
  1131. let userName = this.helpers.worldUser;
  1132. // let users = await _LCSDB.get('users').then();
  1133. let userPub = (await _LCSDB.get('users').get(userName).get('pub').promOnce()).data;
  1134. let protoUserRoot = this.helpers.getRoot(true).root;
  1135. //let myName = this.db.user().is.alias;
  1136. //let proto = Object.keys(myWorldProtos).filter(el => el == protoUserRoot);
  1137. var protosKeys = [];
  1138. if (myWorldProtos)
  1139. protosKeys = Object.keys(myWorldProtos);
  1140. if (protosKeys.includes(protoUserRoot) && myWorldProtos[protoUserRoot]) {
  1141. let userProtoFiles = await this.getProtoWorldFiles(userPub, protoUserRoot);
  1142. let myProtoFiles = await this.getProtoWorldFiles(_LCSDB.user().is.pub, protoUserRoot);
  1143. let hashUP = await this.helpers.sha256(JSON.stringify(userProtoFiles));
  1144. let hashMP = await this.helpers.sha256(JSON.stringify(myProtoFiles));
  1145. if (hashUP == hashMP) {
  1146. this.saveStateAsFile(filename);
  1147. } else {
  1148. let noty = new Noty({
  1149. text: 'world prototype is modified.. could not clone world state',
  1150. timeout: 2000,
  1151. theme: 'mint',
  1152. layout: 'bottomRight',
  1153. type: 'error'
  1154. });
  1155. noty.show();
  1156. }
  1157. } else {
  1158. await this.cloneWorldPrototype(protoUserRoot, userName, protoUserRoot, filename);
  1159. //this.saveStateAsFile(filename);
  1160. }
  1161. }
  1162. //TODO: refactor and config save
  1163. async saveStateAsFile(filename, otherProto) // invoke with the view as "this"
  1164. {
  1165. console.log("Saving: " + filename);
  1166. //var clients = this.nodes["http://vwf.example.com/clients.vwf"];
  1167. // Save State Information
  1168. var state = vwf.getState();
  1169. state.nodes[0].children = {};
  1170. var timestamp = state["queue"].time;
  1171. timestamp = Math.round(timestamp * 1000);
  1172. let jsonValuePure = _app.helpers.replaceFloatArraysInNodeDef(state);
  1173. //remove all Ohm generated grammarsfrom state
  1174. let jsonValue = _app.helpers.removeGrammarObj(jsonValuePure);
  1175. var jsonState = JSON.stringify(jsonValue, null, '\t'); //JSON.stringify(jsonValue);
  1176. let rootPath = this.helpers.getRoot(true);
  1177. var inst = rootPath.inst;
  1178. if (filename == '') filename = inst;
  1179. //if (root.indexOf('.vwf') != -1) root = root.substring(0, root.lastIndexOf('/'));
  1180. var root = rootPath.root;
  1181. var json = jsonState;
  1182. if (otherProto) {
  1183. console.log('need to modify state...');
  1184. json = this.helpers.replaceSubStringALL(jsonState, '/' + root + '/', '/' + otherProto + '/');//jsonState.replace(('/' + root + '/'), ('/' + otherProto +'/') );
  1185. root = otherProto;
  1186. console.log(json);
  1187. }
  1188. //var documents = this.db.user().get('documents');
  1189. var saveRevision = new Date().valueOf();
  1190. var stateForStore = {
  1191. "root": root,
  1192. "filename": filename,
  1193. "inst": inst,
  1194. "timestamp": timestamp,
  1195. "extension": ".vwf.json",
  1196. "jsonState": json,
  1197. "publish": true
  1198. };
  1199. let rev = JSON.stringify(saveRevision);
  1200. var docNameRev = 'savestate_' + rev + '/' + root + '/' + filename + '_vwf_json';
  1201. let stateWithRev = Object.assign({}, stateForStore);
  1202. stateWithRev.revs = { [docNameRev]: stateForStore };
  1203. stateWithRev.revs[docNameRev].revision = saveRevision;
  1204. //let objName = loadInfo[ 'save_name' ] +'/'+ "savestate_" + loadInfo[ 'save_revision' ];
  1205. // "savestate_" + loadInfo[ 'save_revision' ] + '/' + loadInfo[ 'save_name' ] + '_vwf_json'
  1206. var docName = 'savestate_/' + root + '/' + filename + '_vwf_json';
  1207. let myNewWorldState = _LCSDB.user().get('documents').get(root).get(docName).put({});
  1208. //_LCSDB.user().get('documents').get(root).get(docName).put(stateWithRev, function(res) {
  1209. myNewWorldState.put(stateWithRev, function (res) {
  1210. if (res) {
  1211. let noty = new Noty({
  1212. text: 'Saved to ' + docName,
  1213. timeout: 2000,
  1214. theme: 'mint',
  1215. layout: 'bottomRight',
  1216. type: 'success'
  1217. });
  1218. noty.show();
  1219. }
  1220. });
  1221. // let docInfo = await _LCSDB.user().get('worlds').get(root).get('info_json').get('file').then();
  1222. _LCSDB.user().get('worlds').get(root).get('info_json').get('file').once(function (file) {
  1223. if (file) {
  1224. let modified = saveRevision;
  1225. let newOwner = _LCSDB.user().is.pub;
  1226. let userName = _LCSDB.user().is.alias;
  1227. let fileData = (typeof file == 'object')? JSON.stringify(file):file;
  1228. let obj = {
  1229. 'parent': userName + '/' + root,
  1230. 'owner': newOwner,
  1231. 'file': fileData, //file, //JSON.stringify(file),
  1232. //'modified': modified,
  1233. 'created': modified
  1234. }
  1235. let docInfoName = 'savestate_/' + root + '/' + filename + '_info_vwf_json';
  1236. _LCSDB.user().get('documents').get(root).get(docInfoName).get('file').not(function (res) {
  1237. _LCSDB.user().get('documents').get(root).get(docInfoName).put(obj);
  1238. });
  1239. _LCSDB.user().get('documents').get(root).get(docInfoName).get('created').not(function (res) {
  1240. _LCSDB.user().get('documents').get(root).get(docInfoName).get('created').put(modified);
  1241. });
  1242. _LCSDB.user().get('documents').get(root).get(docInfoName).get('modified').put(modified);
  1243. }
  1244. });
  1245. // Save Config Information
  1246. var config = { "info": {}, "model": {}, "view": {} };
  1247. // Save browser title
  1248. config["info"]["title"] = document.title//$('title').html();
  1249. // Save model drivers
  1250. Object.keys(vwf_view.kernel.kernel.models).forEach(function (modelDriver) {
  1251. if (modelDriver.indexOf('vwf/model/') != -1) config["model"][modelDriver] = "";
  1252. });
  1253. // If neither glge or threejs model drivers are defined, specify nodriver
  1254. if (config["model"]["vwf/model/glge"] === undefined && config["model"]["vwf/model/threejs"] === undefined) config["model"]["nodriver"] = "";
  1255. // Save view drivers and associated parameters, if any
  1256. Object.keys(vwf_view.kernel.kernel.views).forEach(function (viewDriver) {
  1257. if (viewDriver.indexOf('vwf/view/') != -1) {
  1258. if (vwf_view.kernel.kernel.views[viewDriver].parameters) {
  1259. config["view"][viewDriver] = vwf_view.kernel.kernel.views[viewDriver].parameters;
  1260. }
  1261. else config["view"][viewDriver] = "";
  1262. }
  1263. });
  1264. //var jsonConfig = $.encoder.encodeForURL(JSON.stringify(config));
  1265. var jsonConfig = JSON.stringify(config);
  1266. let configStateForStore = {
  1267. "root": root,
  1268. "filename": filename,
  1269. "inst": inst,
  1270. "timestamp": timestamp,
  1271. "extension": "config.vwf.json",
  1272. "jsonState": jsonConfig
  1273. };
  1274. //let objName = loadInfo[ 'save_name' ] +'/'+ "savestate_" + loadInfo[ 'save_revision' ];
  1275. // "savestate_" + loadInfo[ 'save_revision' ] + '/' + loadInfo[ 'save_name' ] + '_vwf_json'
  1276. // let configName = 'savestate_/' + root + '/' + filename + '_config_vwf_json';
  1277. // let documentSaveConfigState = this.db.user().get(configName).put(configStateForStore);
  1278. // //documents.path(root).set(documentSaveConfigState);
  1279. // let configNameRev = 'savestate_' + saveRevision.toString() + '/' + root + '/' + filename + '_config_vwf_json';
  1280. // this.db.user().get(configNameRev).put(configStateForStore);
  1281. // this.db.user().get(configNameRev).path("revision").put(saveRevision);
  1282. //documentSaveConfigState.path('revs').set(documentSaveStateRevision);
  1283. // Save config file to server
  1284. // var xhrConfig = new XMLHttpRequest();
  1285. // xhrConfig.open("POST", "/" + root + "/save/" + filename, true);
  1286. // xhrConfig.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  1287. // xhrConfig.send("root=" + root + "/" + filename + "&filename=saveState&inst=" + inst + "&timestamp=" + timestamp + "&extension=.vwf.config.json" + "&jsonState=" + jsonConfig);
  1288. }
  1289. fixSaveState(jsonState, otherProto, oldProtoName) {
  1290. console.log('fix proto in state...');
  1291. let json = this.helpers.replaceSubStringALL(jsonState, '/' + oldProtoName + '/', '/' + otherProto + '/');//jsonState.replace(('/' + root + '/'), ('/' + otherProto +'/') );
  1292. console.log(json);
  1293. return json
  1294. }
  1295. // LoadSavedState
  1296. async loadSavedState(filename, applicationpath, revision) {
  1297. console.log("Loading: " + filename);
  1298. let userDB = _LCSDB.user(_LCS_WORLD_USER.pub);
  1299. let userName = (await userDB.get('alias').promOnce()).data;
  1300. if (revision) {
  1301. window.location.pathname = '/' + userName + applicationpath + '/load/' + filename + '/' + revision + '/';
  1302. }
  1303. else { // applicationpath + "/" + inst + '/load/' + filename + '/';
  1304. window.location.pathname = '/' + userName + applicationpath + '/load/' + filename + '/';
  1305. }
  1306. }
  1307. hideUIControl() {
  1308. let el = document.getElementById("ui-controls");
  1309. if (el) {
  1310. el.classList.remove("visible");
  1311. el.classList.add("not-visible");
  1312. }
  1313. }
  1314. showUIControl() {
  1315. let el = document.getElementById("ui-controls");
  1316. if (el) {
  1317. el.classList.remove("not-visible");
  1318. el.classList.add("visible");
  1319. }
  1320. }
  1321. hideProgressBar() {
  1322. var progressbar = document.getElementById("load-progressbar");
  1323. if (progressbar) {
  1324. progressbar.classList.remove("visible");
  1325. progressbar.classList.remove("mdc-linear-progress--indeterminate");
  1326. progressbar.classList.add("not-visible");
  1327. progressbar.classList.add("mdc-linear-progress--closed");
  1328. }
  1329. }
  1330. showProgressBar() {
  1331. let progressbar = document.getElementById("load-progressbar");
  1332. if (progressbar) {
  1333. progressbar.classList.remove("not-visible");
  1334. progressbar.classList.remove("mdc-linear-progress--closed");
  1335. progressbar.classList.add("visible");
  1336. progressbar.classList.add("mdc-linear-progress--indeterminate");
  1337. }
  1338. }
  1339. // SUPPORT of DELETE USER WORLDS & SAVE STATES (experimental)
  1340. // TODO: manual garbage collection
  1341. async deleteWorldState(worldName, indexState) {
  1342. let revs = (await _LCSDB.user().get('documents').get(worldName).get(indexState).get('revs').promOnce()).data;
  1343. if (revs) {
  1344. for (const el of Object.keys(revs)) {
  1345. if (el !== '_') {
  1346. let doc = (await _LCSDB.user().get('documents').get(worldName).get(indexState).get('revs').get(el).promOnce()).data;
  1347. for (const rev of Object.keys(doc)) {
  1348. if (rev !== '_') {
  1349. await _LCSDB.user().get('documents').get(worldName).get(indexState).get('revs').get(el).get(rev).put(null).promOnce();
  1350. }
  1351. }
  1352. await _LCSDB.user().get('documents').get(worldName).get(indexState).get('revs').get(el).put(null).promOnce();
  1353. }
  1354. }
  1355. }
  1356. // clear all state params
  1357. let stateDoc = (await _LCSDB.user().get('documents').get(worldName).get(indexState).promOnce()).data;
  1358. for (const state of Object.keys(stateDoc)) {
  1359. if (state !== '_' && state !== 'revs') {
  1360. await _LCSDB.user().get('documents').get(worldName).get(indexState).get(state).put(null).promOnce();
  1361. }
  1362. }
  1363. await _LCSDB.user().get('documents').get(worldName).get(indexState).get('revs').put(null).promOnce();
  1364. await _LCSDB.user().get('documents').get(worldName).get(indexState).put(null).promOnce();
  1365. }
  1366. async deleteWorld(name, type) {
  1367. if (type == 'proto') {
  1368. let worldName = name;
  1369. //TODO check for states (ask for deleting all states first...)
  1370. //delete states
  1371. let documents = (await _LCSDB.user().get('documents').promOnce()).data;
  1372. if (documents) {
  1373. let states = (await _LCSDB.user().get('documents').get(worldName).promOnce()).data;
  1374. if (states) {
  1375. for (const st of Object.keys(states)) {
  1376. if (st !== '_') {
  1377. if (states[st]) {
  1378. await this.deleteWorldState(worldName, st);
  1379. }
  1380. }
  1381. }
  1382. }
  1383. }
  1384. let worldFiles = (await _LCSDB.user().get('worlds').get(worldName).promOnce()).data;
  1385. if (worldFiles) {
  1386. for (const el of Object.keys(worldFiles)) {
  1387. if (el !== '_') {
  1388. let doc = (await _LCSDB.user().get('worlds').get(worldName).get(el).promOnce()).data;
  1389. if (doc) {
  1390. if (doc.file) {
  1391. for (const fEl of Object.keys(doc)) {
  1392. if (fEl !== '_') {
  1393. await _LCSDB.user().get('worlds').get(worldName).get(el).get(fEl).put(null).promOnce();
  1394. }
  1395. }
  1396. await _LCSDB.user().get('worlds').get(worldName).get(el).put(null).promOnce();
  1397. } else {
  1398. await _LCSDB.user().get('worlds').get(worldName).get(el).put(null).promOnce()
  1399. }
  1400. }
  1401. }
  1402. }
  1403. }
  1404. // this.db.user().get('worlds').get(worldName).map((res, index) => {
  1405. // if(typeof res == 'object'){
  1406. // this.db.user().get('worlds').get(worldName).get(index)
  1407. // .get('file').put("null")
  1408. // .back(1)
  1409. // .get('modified').put("null")
  1410. // .back(1)
  1411. // .get('created').put("null")
  1412. // .back(1).put("null")
  1413. // } else {
  1414. // this.db.user().get('worlds').get(worldName).get(index).put("null")
  1415. // }
  1416. // })
  1417. await _LCSDB.user().get('worlds').get(worldName).put(null).promOnce();
  1418. } else if (type == 'state') {
  1419. let worldName = name.split('/')[0];
  1420. let stateName = name.split('/')[2];
  1421. let stateEntryInfo = 'savestate_/' + worldName + '/' + stateName + '_info_vwf_json';
  1422. let stateEntry = 'savestate_/' + worldName + '/' + stateName + '_vwf_json';
  1423. await this.deleteWorldState(worldName, stateEntryInfo);
  1424. await this.deleteWorldState(worldName, stateEntry);
  1425. }
  1426. let noty = new Noty({
  1427. text: "World Deleted!",
  1428. timeout: 2000,
  1429. theme: 'mint',
  1430. layout: 'bottomRight',
  1431. type: 'success'
  1432. });
  1433. noty.show();
  1434. }
  1435. parseAppInstancesData(data) {
  1436. let jsonObj = JSON.parse(data);
  1437. var parsed = {};
  1438. let listData = {};
  1439. for (var prop in jsonObj) {
  1440. var name = prop.split('/')[1];
  1441. if (parsed[name]) {
  1442. parsed[name][prop] = jsonObj[prop];
  1443. } else {
  1444. parsed[name] = {};
  1445. parsed[name][prop] = jsonObj[prop];
  1446. }
  1447. }
  1448. //console.log(parsed);
  1449. for (var prop in parsed) {
  1450. var name = prop;
  1451. let obj = Object.entries(parsed[prop]);
  1452. var lists = {};
  1453. obj.forEach(el => {
  1454. if (el[1].loadInfo['save_name']) {
  1455. let saveName = prop + '/load/' + el[1].loadInfo.save_name;
  1456. if (!lists[saveName])
  1457. lists[saveName] = {};
  1458. lists[saveName][el[0]] = el[1]
  1459. } else {
  1460. if (!lists[name])
  1461. lists[name] = {};
  1462. lists[name][el[0]] = el[1]
  1463. }
  1464. });
  1465. // console.log(lists);
  1466. Object.entries(lists).forEach(list => {
  1467. listData[list[0]] = list[1];
  1468. })
  1469. }
  1470. return listData
  1471. // console.log(data)
  1472. }
  1473. async getAllStateWorldsInfoForUser(userAlias, cb) {
  1474. //let users = await _LCSDB.get('users').then();
  1475. let userPub = (await _LCSDB.get('users').get(userAlias).get('pub').promOnce()).data;
  1476. var db = _LCSDB.user(userPub);
  1477. if (_LCSDB.user().is) {
  1478. if (_LCSDB.user().is.alias == userAlias)
  1479. db = _LCSDB.user();
  1480. }
  1481. //let myWorlds = (await db.get('documents').promOnce()).data;
  1482. db.get('documents').load(myWorlds => {
  1483. if (myWorlds) {
  1484. Object.keys(myWorlds).filter(el => el !== '_').forEach(w => {
  1485. db.get('documents').get(w).map(function (res, datI) {
  1486. var doc = {};
  1487. if (datI.includes('_info_vwf_json')) {
  1488. if (res && res !== 'null') {
  1489. if (res.file && res.file !== 'null') {
  1490. let saveName = datI.split('/')[2].replace('_info_vwf_json', "");
  1491. // let worldDesc = JSON.parse(res.file);
  1492. var worldDesc = {};
  1493. if (typeof (res.file) == 'object') {
  1494. worldDesc = res.file
  1495. } else {
  1496. worldDesc = JSON.parse(res.file)
  1497. }
  1498. let root = Object.keys(worldDesc)[0];
  1499. var appInfo = worldDesc[root]['en'];
  1500. let langID = localStorage.getItem('krestianstvo_locale');
  1501. if (langID) {
  1502. appInfo = worldDesc[root][langID]
  1503. }
  1504. doc = {
  1505. 'worldName': w + '/load/' + saveName,
  1506. 'created': res.created ? res.created : res.modified,
  1507. 'modified': res.modified,
  1508. 'type': 'saveState',
  1509. 'userAlias': userAlias,
  1510. 'info': appInfo
  1511. }
  1512. }
  1513. }
  1514. }
  1515. if (Object.keys(doc).length !== 0)
  1516. cb({ [doc.worldName]: doc })
  1517. })
  1518. })
  1519. }
  1520. })
  1521. //})
  1522. }
  1523. async getAllStateWorldsInfoForUserPromise(userAlias) {
  1524. //let users = await _LCSDB.get('users').then();
  1525. let userPub = (await _LCSDB.get('users').get(userAlias).get('pub').promOnce()).data;
  1526. var db = _LCSDB.user(userPub);
  1527. if (_LCSDB.user().is) {
  1528. if (_LCSDB.user().is.alias == userAlias)
  1529. db = _LCSDB.user();
  1530. }
  1531. var states = {};
  1532. let worldDocs = (await db.get('worlds').promOnce()).data;
  1533. if (worldDocs) {
  1534. let protos = Object.keys(worldDocs).filter(el => el !== '_');
  1535. if (protos) {
  1536. for (const el of protos) {
  1537. let info = await this.getSaveStates(userAlias, el);
  1538. if (Object.keys(info).length !== 0)
  1539. states[el] = info;
  1540. }
  1541. }
  1542. }
  1543. return states
  1544. }
  1545. async getAllProtoWorldsInfoForUser(userAlias, cb) {
  1546. //let users = await _LCSDB.get('users').then();
  1547. let userPub = (await _LCSDB.get('users').get(userAlias).get('pub').promOnce()).data;
  1548. var db = _LCSDB.user(userPub);
  1549. if (_LCSDB.user().is) {
  1550. if (_LCSDB.user().is.alias == userAlias)
  1551. db = _LCSDB.user();
  1552. }
  1553. db.get('worlds').once(res=>{
  1554. if (res) {
  1555. db.get('worlds').map(function (val, index) {
  1556. db.get('worlds').get(index).get('info_json').load(function (res) {
  1557. var doc = {};
  1558. if (res && res !== 'null') {
  1559. if (res.file && res.file !== 'null') {
  1560. //let worldDesc = JSON.parse(res.file);
  1561. var worldDesc = {};
  1562. if (typeof (res.file) == 'object') {
  1563. worldDesc = res.file
  1564. } else {
  1565. worldDesc = JSON.parse(res.file)
  1566. }
  1567. let root = Object.keys(worldDesc)[0];
  1568. var appInfo = worldDesc[root]['en'];
  1569. let langID = localStorage.getItem('krestianstvo_locale');
  1570. if (langID) {
  1571. appInfo = worldDesc[root][langID]
  1572. }
  1573. doc = {
  1574. 'worldName': index,
  1575. 'created': res.created ? res.created : res.modified,
  1576. 'modified': res.modified,
  1577. 'type': 'proto',
  1578. 'userAlias': userAlias,
  1579. 'info': appInfo
  1580. }
  1581. }
  1582. }
  1583. if (Object.keys(doc).length !== 0)
  1584. cb({ [index]: doc })
  1585. })
  1586. })
  1587. }
  1588. })
  1589. }
  1590. async getAllProtoWorldsInfoForUserPromise(userAlias) {
  1591. //let users = await _LCSDB.get('users').then();
  1592. let userPub = (await _LCSDB.get('users').get(userAlias).get('pub').promOnce()).data;
  1593. var db = _LCSDB.user(userPub);
  1594. if (_LCSDB.user().is) {
  1595. if (_LCSDB.user().is.alias == userAlias)
  1596. db = _LCSDB.user();
  1597. }
  1598. var worlds = {};
  1599. let worldDocs = (await db.get('worlds').promOnce()).data;
  1600. if (worldDocs) {
  1601. let protos = Object.keys(worldDocs).filter(el => el !== '_');
  1602. if (protos) {
  1603. for (const el of protos) {
  1604. let info = await this.getWorldInfo(userAlias, el);
  1605. if (Object.keys(info).length !== 0)
  1606. worlds[el] = info;
  1607. }
  1608. }
  1609. }
  1610. return worlds
  1611. }
  1612. async getSaveStates(userInfo, worldName) {
  1613. //let userPub = await _LCSDB.get('users').get(userAlias).get('pub').once().then();
  1614. let userPub = userInfo.pub;
  1615. let userAlias = userInfo.user;
  1616. var db = _LCSDB.user(userPub);
  1617. if (_LCSDB.user().is) {
  1618. if (_LCSDB.user().is.alias == userAlias)
  1619. db = _LCSDB.user();
  1620. }
  1621. var states = {};
  1622. let documents = (await db.get('documents').promOnce()).data;
  1623. if (documents) {
  1624. let docs = (await db.get('documents').get(worldName).promOnce()).data;
  1625. if (docs) {
  1626. let saves = Object.keys(docs).filter(el => el.includes('_info_vwf_json'));
  1627. if (saves) {
  1628. for (const el of saves) {
  1629. let stateName = el.split('/')[2].replace('_info_vwf_json', "");
  1630. let info = await this.getStateInfo(userInfo, worldName, stateName);
  1631. if (Object.keys(info).length !== 0) {
  1632. if (info.info)
  1633. states[stateName] = info;
  1634. }
  1635. }
  1636. }
  1637. }
  1638. }
  1639. return states
  1640. }
  1641. async getStateInfo(userInfo, space, saveName) {
  1642. //let userPub = await _LCSDB.get('users').get(user).get('pub').once().then();
  1643. let userPub = userInfo.pub;
  1644. let user = userInfo.user;
  1645. var db = _LCSDB.user(userPub);
  1646. if (_LCSDB.user().is) {
  1647. if (_LCSDB.user().is.alias == user)
  1648. db = _LCSDB.user();
  1649. }
  1650. var info = {};
  1651. //let worlds = await db.get('documents').then();
  1652. let docName = 'savestate_/' + space + '/' + saveName + '_info_vwf_json';
  1653. let world = (await db.get('documents').get(space).get(docName).promOnce()).data;
  1654. if (world) {
  1655. let file = (await db.get('documents').get(space).get(docName).get('file').promOnce()).data;
  1656. if (file && file !== 'null') {
  1657. // let worldDesc = JSON.parse(res.file);
  1658. var worldDesc = {};
  1659. if (typeof (file) == 'object') {
  1660. worldDesc = file
  1661. } else {
  1662. worldDesc = JSON.parse(file)
  1663. }
  1664. let root = Object.keys(worldDesc)[0];
  1665. var appInfo = worldDesc[root]['en'];
  1666. let langID = localStorage.getItem('krestianstvo_locale');
  1667. if (langID) {
  1668. appInfo = worldDesc[root][langID]
  1669. }
  1670. let created = (await db.get('documents').get(space).get(docName).get('created').promOnce()).data;
  1671. let modified = (await db.get('documents').get(space).get(docName).get('modified').promOnce()).data;
  1672. info = {
  1673. 'worldName': space + '/load/' + saveName,
  1674. 'created': created ? created : modified,
  1675. 'modified': modified,
  1676. 'type': 'saveState',
  1677. 'userAlias': user,
  1678. 'info': appInfo
  1679. }
  1680. }
  1681. }
  1682. return info
  1683. }
  1684. async getWorldInfo(userInfo, space) {
  1685. //get space for userA
  1686. let userPub = userInfo.pub;//await _LCSDB.get('users').get(user).get('pub').then();
  1687. let user = userInfo.user;
  1688. var userdb = _LCSDB.user(userPub);
  1689. if (_LCSDB.user().is) {
  1690. if (_LCSDB.user().is.alias == user)
  1691. userdb = _LCSDB.user();
  1692. }
  1693. var info = {};
  1694. //let worlds = await userdb.get('worlds').promOnce();
  1695. let world = (await userdb.get('worlds').get(space).promOnce()).data;
  1696. if (world) {
  1697. let file = (await userdb.get('worlds').get(space).get('info_json').get('file').promOnce()).data;
  1698. if (file && file !== 'null') {
  1699. var worldDesc = {};
  1700. if (typeof (file) == 'object') {
  1701. worldDesc = file
  1702. } else {
  1703. worldDesc = JSON.parse(file)
  1704. }
  1705. //let worldDesc = JSON.parse(res.file);
  1706. let root = Object.keys(worldDesc)[0];
  1707. var appInfo = worldDesc[root]['en'];
  1708. let settings = worldDesc[root].settings;
  1709. let langID = localStorage.getItem('krestianstvo_locale');
  1710. if (langID) {
  1711. appInfo = worldDesc[root][langID]
  1712. }
  1713. let created = (await userdb.get('worlds').get(space).get('info_json').get('created').promOnce()).data;
  1714. let modified = (await userdb.get('worlds').get(space).get('info_json').get('modified').promOnce()).data;
  1715. info = {
  1716. 'worldName': space,
  1717. 'created': created ? created : modified,
  1718. 'modified': modified,
  1719. 'type': 'proto',
  1720. 'userAlias': user,
  1721. 'info': appInfo,
  1722. 'settings': settings
  1723. }
  1724. }
  1725. }
  1726. return info
  1727. }
  1728. }
  1729. export { App }