app.js 69 KB

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