app.js 70 KB

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