app.js 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873
  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. })
  34. .then(res => {
  35. window._l = _LangManager.language;
  36. })
  37. .then(res => {
  38. return import('/web/index-app.js');
  39. }).then(res => {
  40. window.IndexApp = res.default;
  41. this.setPageRoutes();
  42. });
  43. }
  44. setPageRoutes() {
  45. //client routes
  46. page('/', this.HandleIndex);
  47. page('/setup', this.HandleSetupIndex);
  48. page('/debug', this.HandleDebugIndex);
  49. page('/settings', this.HandleSettingsIndex);
  50. page('/profile', this.HandleUserIndex);
  51. page('/worlds', this.HandleIndex);
  52. page('/:user/worlds', this.HandleUserWorlds);
  53. page('/:user/:type/:name/edit/:file', this.HandleFileEdit);
  54. page('/:user/:space', this.HandleParsableRequestGenID);
  55. page('/:user/:space/about', this.HandleWorldAbout);
  56. page('/:user/:space/:id', this.HandleParsableRequestWithID);
  57. page('/:user/:space/index.vwf/:id', this.HandleParsableRequestWithID);
  58. page('/:user/:space/load/:savename', this.HandleParsableLoadRequest);
  59. page('/:user/:space/:id/load/:savename', this.HandleParsableRequestWithID);
  60. page('/:user/:space/index.vwf/:id/load/:savename', this.HandleParsableRequestWithID);
  61. // page('/:user/worlds/:type', this.HandleUserWorldsWithType);
  62. // page('/:user/:space/load/:savename/about', this.HandleWorldAbout);
  63. // page('/:user/:space/load/:savename/:rev', this.HandleParsableLoadRequestWithRev);
  64. // page('/:user/:space/:id/load/:savename/:rev', this.HandleParsableRequestWithID);
  65. page('*', this.HandleNoPage);
  66. page();
  67. }
  68. initDB() {
  69. var config = JSON.parse(localStorage.getItem('lcs_config'));
  70. if (!config) {
  71. config = {
  72. 'luminary': false,
  73. 'luminaryPath': 'luminary',
  74. 'luminaryGlobalHBPath': 'server/heartbeat',
  75. 'luminaryGlobalHB': false,
  76. 'dbhost': window.location.origin + '/gun', // 'https://' + window.location.hostname + ':8080/gun', //'http://localhost:8080/gun',
  77. 'reflector': 'https://' + window.location.hostname + ':3002',
  78. 'webrtc': false,
  79. 'language': 'en',
  80. 'd3DoF': false,
  81. 'd6DoF': false
  82. }
  83. }
  84. //if old config on browser exists
  85. if (!config.luminaryPath) {
  86. config.luminaryPath = 'luminary';
  87. }
  88. if (!config.luminaryGlobalHBPath) {
  89. config.luminaryGlobalHBPath = 'server/heartbeat';
  90. }
  91. if (!config.luminaryGlobalHB) {
  92. config.luminaryGlobalHB = false;
  93. }
  94. if (!config.webrtc) {
  95. config.webrtc = false;
  96. }
  97. if (!config.d3DoF) {
  98. config.d3DoF = false;
  99. }
  100. if (!config.d6DoF) {
  101. config.d6DoF = false;
  102. }
  103. localStorage.setItem('lcs_config', JSON.stringify(config));
  104. this.config = config;
  105. let webrtcConnection = this.config.webrtc;
  106. const opt = { peers: this.dbHost, localStorage: false, RTCPeerConnection: webrtcConnection, axe: false } //localStorage: false,
  107. //const opt = { peers: this.dbHost, localStorage: false, until: 1000, chunk: 5, axe: false} //until: 5000, chunk: 5
  108. //opt.store = RindexedDB(opt);
  109. this.db = Gun(opt);
  110. //window._LCS_SYS_USER = undefined;
  111. window._LCSDB = this.db;
  112. window._LCS_WORLD_USER = undefined;
  113. _LCSDB.on('hi', function (peer) {
  114. let msg = peer.url ? 'Connected to DB at: ' + peer.url : 'Peer added!';
  115. let noty = new Noty({
  116. text: msg,
  117. timeout: 1000,
  118. theme: 'mint',
  119. layout: 'bottomRight',
  120. type: 'success'
  121. });
  122. if (peer.url) {
  123. noty.show();
  124. }
  125. console.log(msg)
  126. })
  127. _LCSDB.on('bye', function (peer) {
  128. let msg = 'No connection to ' + peer.url;
  129. let noty = new Noty({
  130. text: msg,
  131. timeout: 1000,
  132. theme: 'mint',
  133. layout: 'bottomRight',
  134. type: 'error'
  135. });
  136. noty.show();
  137. console.log(msg)
  138. })
  139. }
  140. clearLocalStorage() {
  141. let config = localStorage.getItem('lcs_config');
  142. let langConfig = localStorage.getItem('krestianstvo_locale');
  143. let manualConfig = localStorage.getItem('lcs_app_manual_settings');
  144. let lcsappConfig = localStorage.getItem('lcs_app');
  145. localStorage.clear();
  146. if (config)
  147. localStorage.setItem('lcs_config', config);
  148. if (langConfig)
  149. localStorage.setItem('krestianstvo_locale', langConfig);
  150. if (manualConfig)
  151. localStorage.setItem('lcs_app_manual_settings', manualConfig);
  152. if (lcsappConfig)
  153. localStorage.setItem('lcs_app', lcsappConfig);
  154. }
  155. initUser() {
  156. function recall() {
  157. _LCSDB.user().recall({ sessionStorage: 1 }, res => {
  158. console.log('User is: ', _LCSDB.user().is);
  159. if (_LCSDB.user().is)
  160. _app.helpers.checkUserCollision();
  161. });
  162. }
  163. setTimeout(
  164. recall, 1000)
  165. }
  166. async chooseConnection(data) {
  167. if (this.isLuminary) {
  168. return await _app.luminary.connect(data) //use Luminary
  169. } else {
  170. return data //use Reflector
  171. }
  172. }
  173. get isLuminary() {
  174. return this.config.luminary;
  175. }
  176. get isLuminaryGlobalHB() {
  177. return this.config.luminaryGlobalHB;
  178. }
  179. get isWebRTC() {
  180. return this.config.webrtc;
  181. }
  182. get luminaryGlobalHBPath() {
  183. var res = "";
  184. let config = localStorage.getItem('lcs_config');
  185. if (config) {
  186. res = JSON.parse(config).luminaryGlobalHBPath;
  187. }
  188. return res;
  189. }
  190. get luminaryPath() {
  191. var res = "";
  192. let config = localStorage.getItem('lcs_config');
  193. if (config) {
  194. res = JSON.parse(config).luminaryPath;
  195. }
  196. return res;
  197. }
  198. get reflectorHost() {
  199. var res = "";
  200. let config = localStorage.getItem('lcs_config');
  201. if (config) {
  202. res = JSON.parse(config).reflector;
  203. }
  204. return res;
  205. }
  206. get dbHost() {
  207. var res = "";
  208. let config = localStorage.getItem('lcs_config');
  209. if (config) {
  210. res = JSON.parse(config).dbhost;
  211. }
  212. return res;
  213. }
  214. async loadProxyDefaults() {
  215. // Optional req from server
  216. // load to DB default proxy files (VWF & A-Frame components)
  217. let proxyResponse = await fetch('/proxy-files', { method: 'get' });
  218. let proxyFiles = await proxyResponse.json();
  219. let filterProxyFiles = proxyFiles.filter(el => (el !== null));
  220. console.log(filterProxyFiles);
  221. var origin = window.location.origin;
  222. //var userPub = this.db.user().is.pub;
  223. let proxyObj = {};
  224. for (var index in filterProxyFiles) {
  225. let doc = filterProxyFiles[index];
  226. if (doc) {
  227. var url = origin + doc;
  228. var entryName = url.replace(origin + '/defaults/', "").split(".").join("_");
  229. let proxyFile = await fetch(url, { method: 'get' });
  230. let responseText = await proxyFile.text();
  231. if (responseText) {
  232. proxyObj[entryName] = responseText;
  233. }
  234. }
  235. }
  236. console.log(proxyObj);
  237. let proxy = _LCSDB.user().get('proxy');
  238. proxy.put(proxyObj);
  239. }
  240. async loadWorldsDefaults(replace) {
  241. // Optional req from server
  242. //load to DB default worlds
  243. let worldsResponse = await fetch('/world-files', { method: 'get' });
  244. let worldFiles = await worldsResponse.json();
  245. let filterworldFiles = worldFiles.filter(el => (el !== null));
  246. console.log(filterworldFiles);
  247. let worldsObj = {};
  248. for (var index in filterworldFiles) {
  249. let doc = filterworldFiles[index];
  250. if (doc) {
  251. let url = window.location.origin + doc;
  252. var entryName = url.replace(window.location.origin + '/defaults/worlds/', "").split(".").join("_");
  253. let worldName = entryName.split("/")[0];
  254. let userPub = _LCSDB.user().is.pub;
  255. let worldFile = await fetch(url, { method: 'get' });
  256. let worldSource = await worldFile.text();
  257. if (worldSource) {
  258. //let modified = new Date().valueOf();
  259. let created = new Date().valueOf();
  260. if (!worldsObj[worldName]) {
  261. worldsObj[worldName] = {
  262. 'parent': '-',
  263. 'owner': userPub,
  264. 'featured': true,
  265. 'published': true,
  266. 'proxy': userPub,
  267. 'created': created,
  268. 'modified': created
  269. }
  270. }
  271. let entry = entryName.replace(worldName + '/', "");
  272. worldsObj[worldName][entry] = worldSource
  273. }
  274. }
  275. }
  276. console.log(worldsObj);
  277. if (replace) {
  278. //force replace all default worlds
  279. let worlds = _LCSDB.user().get('worlds');
  280. worlds.put(worldsObj);
  281. } else {
  282. Object.entries(worldsObj).forEach(res => {
  283. let worldName = res[0];
  284. let files = res[1];
  285. Object.entries(files).forEach(file => {
  286. _LCSDB.user().get('worlds').get(worldName).get(file[0]).not(function (res) {
  287. _LCSDB.user().get('worlds').get(worldName).get(file[0]).put(file[1]);
  288. })
  289. })
  290. })
  291. }
  292. }
  293. async loadEmptyDefaultProto() {
  294. //empty proto world
  295. let userPub = _LCSDB.user().is.pub;
  296. let worldsObj = {};
  297. let emptyWorld = {
  298. "index_vwf_json": JSON.stringify(
  299. {
  300. "extends": "proxy/aframe/ascene.vwf"
  301. }, null, 4),
  302. "index_vwf_config_json": JSON.stringify(
  303. {
  304. "info": {
  305. "title": "Empty World"
  306. },
  307. "model": {
  308. "vwf/model/aframe": null
  309. },
  310. "view": {
  311. "vwf/view/aframe": null,
  312. "vwf/view/editor-new": null
  313. }
  314. }, null, 4),
  315. "assets_json": JSON.stringify({}),
  316. "index_vwf_html": JSON.stringify("<!-- DEFAULT HTML -->"),
  317. "appui_js": JSON.stringify("//appui in JS"),
  318. "info_json": JSON.stringify({
  319. "info": {
  320. "en": {
  321. "title": "Empty World",
  322. "imgUrl": "",
  323. "text": "Empty World"
  324. },
  325. "ru": {
  326. "title": "Новый Мир",
  327. "imgUrl": "",
  328. "text": "Новый Мир"
  329. }
  330. }
  331. }, null, 4)
  332. }
  333. let created = new Date().valueOf();
  334. worldsObj['empty'] = {
  335. 'parent': '-',
  336. 'owner': userPub,
  337. 'featured': true,
  338. 'published': true,
  339. 'proxy': userPub,
  340. 'created': created,
  341. 'modified': created
  342. }
  343. Object.keys(emptyWorld).forEach(el => {
  344. worldsObj['empty'][el] = emptyWorld[el];
  345. })
  346. console.log(worldsObj);
  347. Object.entries(worldsObj).forEach(el => {
  348. let worldName = el[0];
  349. let files = el[1];
  350. Object.entries(files).forEach(file => {
  351. _LCSDB.user().get('worlds').get(worldName).get(file[0]).put(file[1]);
  352. })
  353. })
  354. }
  355. HandleDebugIndex() {
  356. window._app.hideProgressBar();
  357. window._app.hideUIControl();
  358. let el = document.createElement("div");
  359. el.setAttribute("id", "appGUI");
  360. document.body.appendChild(el);
  361. _cellWidgets.debugGUI();
  362. }
  363. HandleSettingsIndex() {
  364. window._app.hideProgressBar();
  365. window._app.hideUIControl();
  366. let el = document.createElement("div");
  367. el.setAttribute("id", "appGUI");
  368. document.body.appendChild(el);
  369. _cellWidgets.reflectorGUI();
  370. }
  371. HandleWorldAbout(ctx) {
  372. console.log("about world");
  373. let userAlias = ctx.params.user;
  374. let worldName = ctx.params.space;
  375. let saveName = ctx.params.savename;
  376. window._app.hideProgressBar();
  377. window._app.hideUIControl();
  378. if (!_app.indexApp) {
  379. _app.indexApp = new IndexApp;
  380. }
  381. let worldApp = new WorldApp(userAlias, worldName, saveName);
  382. _app.helpers.getUserPub(userAlias).then(res => {
  383. worldApp.makeGUI(res)
  384. })
  385. }
  386. HandleSetupIndex() {
  387. window._app.hideProgressBar();
  388. window._app.hideUIControl();
  389. _LCSDB.on('auth',
  390. function (ack) {
  391. let el = document.createElement("div");
  392. el.setAttribute("id", "admin");
  393. document.body.appendChild(el);
  394. if (_LCSDB.user().is) {
  395. let adminComponents = [];
  396. document.querySelector("#admin").$cell({
  397. $cell: true,
  398. id: 'admin',
  399. $type: "div",
  400. $components: adminComponents,
  401. $update: function () {
  402. this.$components = adminComponents
  403. }
  404. });
  405. document.querySelector("#admin").$update();
  406. if (_LCSDB.user().is) {
  407. let loadEmpty = {
  408. $cell: true,
  409. $components: [
  410. {
  411. $type: "p",
  412. class: "mdc-typography--headline5",
  413. $text: "Initialize empty World proto"
  414. },
  415. {
  416. $type: "button",
  417. id: "loadDefaults",
  418. class: "mdc-button mdc-button--raised",
  419. $text: "Init empty world",
  420. onclick: function (e) {
  421. console.log("admin action");
  422. window._app.loadEmptyDefaultProto();
  423. }
  424. }
  425. ]
  426. }
  427. let loadDefaults = {
  428. $cell: true,
  429. _replaceSwitch: null,
  430. $components: [
  431. {
  432. $type: "p",
  433. class: "mdc-typography--headline5",
  434. $text: "Load Sample Worlds protos from server (optional)"
  435. },
  436. {
  437. $type: "button",
  438. id: "loadDefaults",
  439. class: "mdc-button mdc-button--raised",
  440. $text: "Load default worlds (from server)",
  441. onclick: function (e) {
  442. console.log("admin action");
  443. let forceReplace = this._replaceSwitch.checked;
  444. //console.log(forceReplace);
  445. window._app.loadWorldsDefaults(forceReplace);
  446. }
  447. },
  448. {
  449. $type: 'p'
  450. },
  451. _cellWidgets.switch({
  452. 'id': 'forceReplace',
  453. 'init': function () {
  454. this._switch = new mdc.switchControl.MDCSwitch(this);
  455. this._replaceSwitch = this._switch;
  456. this._switch.checked = false;
  457. }
  458. }
  459. ),
  460. {
  461. $type: 'label',
  462. for: 'input-forceReplace',
  463. $text: 'Force replace'
  464. }
  465. ]
  466. }
  467. let loadDefaultsProxy = {
  468. $cell: true,
  469. $components: [
  470. {
  471. $type: "p",
  472. class: "mdc-typography--headline5",
  473. $text: "Load VWF & A-Frame default components"
  474. },
  475. {
  476. $type: "button",
  477. class: "mdc-button mdc-button--raised",
  478. $text: "Load defaults Proxy",
  479. onclick: async function (e) {
  480. console.log("admin action");
  481. await window._app.loadProxyDefaults();
  482. }
  483. }
  484. ]
  485. }
  486. adminComponents.push(loadDefaultsProxy, loadEmpty, loadDefaults);
  487. document.querySelector("#admin").$update();
  488. }
  489. }
  490. })
  491. }
  492. //TODO: profile
  493. HandleUserIndex(ctx) {
  494. console.log("USER INDEX");
  495. window._app.hideProgressBar();
  496. window._app.hideUIControl();
  497. import('/web/header.js').then(res => {
  498. let gui = new res.Header();
  499. gui.init();
  500. })
  501. _LCSDB.on('auth',
  502. async function (ack) {
  503. if (ack.sea.pub) {
  504. _app.helpers.checkUserCollision();
  505. let alias = _LCSDB.user().is.alias;
  506. let pub = _LCSDB.user().is.pub;
  507. document.querySelector("#profile")._refresh(
  508. {
  509. user: {
  510. alias: alias,
  511. pub: pub
  512. }
  513. }
  514. );
  515. }
  516. })
  517. let el = document.createElement("div");
  518. el.setAttribute("id", "userProfile");
  519. document.body.appendChild(el);
  520. let dragDropWorldsArea = {
  521. $cell: true,
  522. $type: 'div',
  523. id: "ddWorlds",
  524. class: 'dragdropArea',
  525. _ddText: '',
  526. _refresh: function (aText) {
  527. this._ddText = aText;
  528. },
  529. $init: function () {
  530. console.log('init d&d area for worlds protos');
  531. this._refresh('Drag & Drop a folder with world files here...');
  532. let self = this;
  533. DragDrop("#ddWorlds",
  534. {
  535. onDrop: function (files, pos, fileList, directories) {
  536. console.log('onDrop: ' + files.length + ' files at ' + pos.x + ', ' + pos.y);
  537. //let worldsObj = {};
  538. let worlds = _LCSDB.user().get('worlds');
  539. files.forEach(function (file) {
  540. let world = {};
  541. if ((file.name.indexOf('.yaml') !== -1) ||
  542. (file.type == "text/javascript") ||
  543. (file.type == "text/html") ||
  544. (file.type == "application/json")) {
  545. console.log('- ' + file.name + ' (' + file.size + ') (' + file.type + ')');
  546. // convert the file to a Buffer that we can use!
  547. const reader = new FileReader()
  548. reader.addEventListener('load', e => {
  549. // e.target.result is an ArrayBuffer
  550. const arr = new Uint8Array(e.target.result)
  551. const fileBuffer = new buffer.Buffer(arr);
  552. const fileSource = fileBuffer.toString();
  553. // do something with the buffer!
  554. var entryName = file.fullPath.slice(1).split(".").join("_");
  555. let worldName = entryName.split("/")[0];
  556. let userPub = _LCSDB.user().is.pub;
  557. //let modified = new Date().valueOf();
  558. let created = new Date().valueOf();
  559. world[worldName] = {
  560. 'parent': '-',
  561. 'owner': userPub,
  562. 'featured': true,
  563. 'published': true,
  564. 'proxy': userPub,
  565. 'created': created,
  566. 'modified': created
  567. }
  568. let entry = entryName.replace(worldName + '/', "");
  569. world[worldName][entry] = fileSource;
  570. console.log(world);
  571. worlds.put(world);
  572. })
  573. reader.addEventListener('error', err => {
  574. console.error('FileReader error' + err)
  575. })
  576. reader.readAsArrayBuffer(file)
  577. }
  578. })
  579. //console.log('Worlds', worldsObj);
  580. console.log('files array', files)
  581. console.log('FileList object', fileList)
  582. console.log('directories array', directories)
  583. self._refresh(directories.map(el => { return el.name }).toString());
  584. },
  585. onDropText: function (text, pos) {
  586. console.log('onDropText: ' + text + ' at ' + pos.x + ', ' + pos.y)
  587. }
  588. }
  589. )
  590. },
  591. $update: function () {
  592. this.$components = [
  593. {
  594. $type: "h5",
  595. class: "mdc-typography--headline5",
  596. $text: this._ddText
  597. }
  598. ]
  599. }
  600. }
  601. let dragDropProxyArea = {
  602. $cell: true,
  603. $type: 'div',
  604. id: "ddProxy",
  605. class: 'dragdropArea',
  606. _ddText: '',
  607. _refresh: function (aText) {
  608. this._ddText = aText;
  609. },
  610. $init: function () {
  611. console.log('init d&d area for proxy files');
  612. this._refresh('Drag & Drop a folder with proxy files here...');
  613. let self = this;
  614. DragDrop("#ddProxy",
  615. {
  616. onDrop: function (files, pos, fileList, directories) {
  617. console.log('onDrop: ' + files.length + ' files at ' + pos.x + ', ' + pos.y);
  618. //let worldsObj = {};
  619. let proxy = _LCSDB.user().get('proxy').put({ id: 'proxy' });
  620. files.forEach(function (file) {
  621. let proxyObj = {};
  622. if ((file.name.indexOf('.yaml') !== -1) ||
  623. (file.type == "text/javascript") ||
  624. (file.type == "text/html") ||
  625. (file.type == "application/json")) {
  626. console.log('- ' + file.name + ' (' + file.size + ') (' + file.type + ')');
  627. // convert the file to a Buffer that we can use!
  628. const reader = new FileReader()
  629. reader.addEventListener('load', e => {
  630. // e.target.result is an ArrayBuffer
  631. const arr = new Uint8Array(e.target.result)
  632. const fileBuffer = new buffer.Buffer(arr);
  633. const fileSource = fileBuffer.toString();
  634. // do something with the buffer!
  635. var entryName = file.fullPath.slice(1).split(".").join("_");
  636. if (entryName.slice(0, 6) !== 'proxy/') {
  637. entryName = 'proxy/' + entryName
  638. }
  639. // let userPub = _LCSDB.user().is.pub;
  640. // let created = new Date().valueOf();
  641. // let obj = {
  642. // 'owner': userPub,
  643. // 'file': fileSource,
  644. // 'modified': created,
  645. // 'created': created
  646. // }
  647. proxyObj[entryName] = fileSource;
  648. console.log(proxyObj);
  649. proxy.put(proxyObj);
  650. })
  651. reader.addEventListener('error', err => {
  652. console.error('FileReader error' + err)
  653. })
  654. reader.readAsArrayBuffer(file)
  655. }
  656. })
  657. console.log('files array', files)
  658. console.log('FileList object', fileList)
  659. console.log('directories array', directories)
  660. self._refresh(directories.map(el => { return el.name }).toString());
  661. },
  662. onDropText: function (text, pos) {
  663. console.log('onDropText: ' + text + ' at ' + pos.x + ', ' + pos.y)
  664. }
  665. }
  666. )
  667. },
  668. $update: function () {
  669. this.$components = [
  670. {
  671. $type: "h5",
  672. class: "mdc-typography--headline5",
  673. $text: this._ddText
  674. }
  675. ]
  676. }
  677. }
  678. let loadDefaultsProxy = {
  679. $type: 'div',
  680. $components: [
  681. {
  682. $type: "button",
  683. class: "mdc-button mdc-button--raised",
  684. $text: "Load default Proxy from LiveCoding.space server",
  685. onclick: async function (e) {
  686. console.log("user action");
  687. await window._app.loadProxyDefaults();
  688. }
  689. }
  690. ]
  691. }
  692. let loadEmpty = {
  693. $type: 'div',
  694. $components: [
  695. {
  696. $type: "button",
  697. id: "loadDefaults",
  698. class: "mdc-button mdc-button--raised",
  699. $text: "Init empty world",
  700. onclick: function (e) {
  701. console.log("user action");
  702. window._app.loadEmptyDefaultProto();
  703. }
  704. }
  705. ]
  706. }
  707. let proxySource =
  708. {
  709. $type: "div",
  710. id: "tree_proxy",
  711. _tree: [],
  712. _treeComp: {},
  713. $init: function () {
  714. let selfComp = this;
  715. _LCSDB.user().get('proxy').load(res => {
  716. // console.log(res);
  717. if (res) {
  718. selfComp._tree = [{
  719. name: 'Proxy sources: ',
  720. children: []
  721. }];
  722. Object.keys(res).filter(el => el.includes('_js') || el.includes('_json')).forEach(el => {
  723. selfComp._tree[0].children.push({
  724. name: el
  725. })
  726. })
  727. selfComp._treeComp = new TreeView(selfComp._tree, 'tree_proxy');
  728. selfComp._treeComp.on('select', function (evt) {
  729. console.log(evt);
  730. //window.location.pathname = "/" + desc.userAlias + '/proto/' + desc.worldName + '/edit/' + evt.data.name
  731. });
  732. }
  733. })
  734. },
  735. $components: [
  736. ]
  737. }
  738. let userProfile = {
  739. $type: 'div',
  740. id: "profile",
  741. _user: {},
  742. _refresh: function (data) {
  743. this._user = data.user;
  744. },
  745. $init: function () {
  746. this._user = { alias: "", pub: "" }
  747. },
  748. $update: function () {
  749. if (_LCSDB.user().is) {
  750. this.$components = [
  751. {
  752. $type: "div",
  753. class: "mdc-layout-grid",
  754. $components: [
  755. {
  756. $type: "div",
  757. class: "mdc-layout-grid__inner",
  758. $components: [
  759. {
  760. $type: "div",
  761. class: "mdc-layout-grid__cell mdc-layout-grid__cell--span-12",
  762. $components: [
  763. {
  764. $type: "h5",
  765. class: "mdc-typography--headline4 unselectable",
  766. $text: "User alias: " + this._user.alias //"Profile for: " + this.db.user().is.alias
  767. },
  768. {
  769. $type: "h5",
  770. class: "mdc-typography--headline5 unselectable",
  771. $text: "User public key: " + this._user.pub//"Profile for: " + this.db.user().is.alias
  772. },
  773. ]
  774. },
  775. {
  776. $type: "div",
  777. class: "mdc-layout-grid__cell mdc-layout-grid__cell--span-12",
  778. $components: [
  779. {
  780. $type: "h3",
  781. class: "mdc-typography",
  782. $text: 'Load my world\'s protos:' //"Profile for: " + this.db.user().is.alias
  783. },
  784. dragDropWorldsArea, _app.widgets.emptyDiv,
  785. {
  786. $text: 'or'
  787. },
  788. _app.widgets.p,
  789. loadEmpty
  790. ]
  791. },
  792. {
  793. $type: "div",
  794. class: "mdc-layout-grid__cell mdc-layout-grid__cell--span-12",
  795. $components: [
  796. {
  797. $type: "h3",
  798. class: "mdc-typography",
  799. $text: 'Load proxy files:' //"Profile for: " + this.db.user().is.alias
  800. },
  801. dragDropProxyArea,
  802. _app.widgets.emptyDiv,
  803. {
  804. $text: 'or'
  805. },
  806. _app.widgets.p,
  807. loadDefaultsProxy,
  808. _app.widgets.p,
  809. _app.widgets.divider,
  810. proxySource
  811. ]
  812. }
  813. ]
  814. }
  815. ]
  816. }
  817. ]
  818. } else {
  819. this.$components = [
  820. {
  821. $type: "h3",
  822. class: "mdc-typography--headline3",
  823. $text: "user is not signed in..." //"Profile for: " + this.db.user().is.alias
  824. },
  825. _app.widgets.divider
  826. ]
  827. }
  828. }
  829. }
  830. document.querySelector("#userProfile").$cell({
  831. $cell: true,
  832. $type: "div",
  833. $components: [userProfile]
  834. })
  835. }
  836. HandleUserWorlds(ctx) {
  837. console.log("USER WORLDS INDEX");
  838. console.log(ctx.params);
  839. let user = ctx.params.user;
  840. let type = ctx.params.type;
  841. window._app.hideProgressBar();
  842. window._app.hideUIControl();
  843. if (!_app.indexApp) {
  844. _app.indexApp = new IndexApp;
  845. }
  846. _app.indexApp.allWorldsForUser(user)
  847. }
  848. HandleFileEdit(ctx) {
  849. console.log("USER WORLD FILE EDIT");
  850. let user = ctx.params.user;
  851. let worldName = ctx.params.name;
  852. let fileOriginal = ctx.params.file;
  853. let type = ctx.params.type;
  854. window._app.hideProgressBar();
  855. window._app.hideUIControl();
  856. _LCSDB.on('auth',
  857. async function (ack) {
  858. if (_LCSDB.user().is) {
  859. _app.helpers.checkUserCollision();
  860. if (_LCSDB.user().is.alias == user) {
  861. var worldType = 'worlds';
  862. var file = fileOriginal;
  863. if (type == 'state') {
  864. worldType = 'documents';
  865. file = _app.helpers.replaceSubStringALL(fileOriginal, "~", '/');
  866. }
  867. _LCSDB.user().get(worldType).get(worldName).get(file).load(worldFile => {
  868. if (worldFile) {
  869. var source = worldFile;
  870. if (type == 'state') {
  871. if (!file.includes('_info_vwf_json')) {
  872. source = worldFile.jsonState;
  873. var saveName = worldFile.filename;
  874. }
  875. }
  876. //console.log(source);
  877. source = _app.helpers.convertFileSource(file, source);
  878. let el = document.createElement("div");
  879. el.setAttribute("id", "worldFILE");
  880. document.body.appendChild(el);
  881. var saveGUI = {};
  882. if (type == 'proto' || file.includes('_info_vwf_json')) {
  883. saveGUI = {
  884. $type: "button",
  885. class: "mdc-button mdc-button--raised",
  886. $text: "Save",
  887. onclick: async function (e) {
  888. console.log("save new info");
  889. let editor = document.querySelector("#aceEditor").env.editor;
  890. let newInfo = editor.getValue();
  891. _LCSDB.user().get(worldType).get(worldName).get(file).put(newInfo, function (res) {
  892. if (res) {
  893. _app.helpers.notyOK('Saved!');
  894. // let modified = new Date().valueOf();
  895. // _LCSDB.user().get(worldType).get(worldName).get(file).get('modified').put(modified);
  896. }
  897. })
  898. }
  899. }
  900. }
  901. let aceEditorCell = {
  902. $type: "div",
  903. $components: [
  904. {
  905. class: "aceEditor",
  906. id: "aceEditor",
  907. //style: "width:1200px; height: 800px",
  908. $type: "div",
  909. $text: source,
  910. $init: function () {
  911. var mode = "ace/mode/json";
  912. if (file.includes('_yaml'))
  913. mode = "ace/mode/yaml"
  914. if (file.includes('_js'))
  915. mode = "ace/mode/javascript"
  916. var editor = ace.edit("aceEditor");
  917. editor.setTheme("ace/theme/monokai");
  918. editor.setFontSize(16);
  919. editor.getSession().setMode(mode);
  920. editor.setOptions({
  921. maxLines: Infinity
  922. });
  923. editor.session.setUseWrapMode(true);
  924. }
  925. },
  926. saveGUI,
  927. {
  928. $type: "button",
  929. class: "mdc-button mdc-button--raised",
  930. $text: "Close",
  931. onclick: function (e) {
  932. console.log("close");
  933. //window.location.pathname = "/" + user + '/' + worldName + '/about'
  934. window.history.back();
  935. // if (type == "proto")
  936. // window.location.pathname = "/" + user + '/' + worldName + '/about'
  937. // if (type == "state")
  938. // window.location.pathname = "/" + user + '/' + worldName + '/about'
  939. }
  940. }
  941. ]
  942. }
  943. document.querySelector("#worldFILE").$cell({
  944. $cell: true,
  945. $type: "div",
  946. $components: [aceEditorCell
  947. ]
  948. })
  949. }
  950. });
  951. }
  952. }
  953. })
  954. }
  955. async generateFrontPage() {
  956. let infoEl = document.createElement("div");
  957. infoEl.setAttribute("id", "indexPage");
  958. let lang = _LangManager.locale;
  959. let infoElHTML = await _app.helpers.getHtmlText('/web/locale/' + lang + '/index.html');
  960. infoEl.innerHTML = infoElHTML;
  961. document.body.appendChild(infoEl);
  962. }
  963. HandleIndex() {
  964. console.log("INDEX");
  965. window._app.hideProgressBar();
  966. window._app.hideUIControl();
  967. (new Promise(res => res(_app.generateFrontPage()))).then(res => {
  968. if (!_app.indexApp) {
  969. _app.indexApp = new IndexApp('index');
  970. }
  971. })
  972. }
  973. HandleNoPage() {
  974. console.log("no such page")
  975. }
  976. //handle parcable requests
  977. HandleParsableLoadRequest(ctx) {
  978. let app = window._app;
  979. console.log(ctx.params);
  980. //var pathname = ctx.pathname;
  981. var spaceName = ctx.params.space;
  982. var saveName = ctx.params.savename;
  983. let user = ctx.params.user;
  984. page.redirect('/' + user + '/' + spaceName + '/' + app.helpers.GenerateInstanceID() + '/load/' + saveName);
  985. }
  986. HandleParsableLoadRequestWithRev(ctx) {
  987. let app = window._app;
  988. console.log(ctx.params);
  989. //var pathname = ctx.pathname;
  990. var spaceName = ctx.params.space;
  991. var saveName = ctx.params.savename;
  992. var rev = ctx.params.rev;
  993. let user = ctx.params.user;
  994. page.redirect('/' + user + '/' + spaceName + '/' + app.helpers.GenerateInstanceID() + '/load/' + saveName + '/' + rev);
  995. }
  996. HandleParsableRequestGenID(ctx) {
  997. let app = window._app;
  998. console.log(ctx.params);
  999. let user = ctx.params.user;
  1000. let space = ctx.params.space;
  1001. var pathname = ctx.pathname;
  1002. //await app.setUserPaths(user);
  1003. _app.helpers.getUserPub(user).then(function (res) {
  1004. if (res)
  1005. window._LCS_WORLD_USER = {
  1006. alias: user,
  1007. pub: res
  1008. }
  1009. if (pathname[pathname.length - 1] == '/') {
  1010. pathname = pathname.slice(0, -1)
  1011. }
  1012. let pathToParse = '/' + space; // pathname.replace('/' + user, "");
  1013. let parsedRequest = {
  1014. application: "index.vwf",
  1015. instance: undefined,
  1016. private_path: undefined,
  1017. public_path: pathToParse
  1018. }
  1019. localStorage.setItem('lcs_app', JSON.stringify({ path: parsedRequest }));
  1020. console.log(parsedRequest);
  1021. if ((parsedRequest['instance'] == undefined) && (parsedRequest['private_path'] == undefined) && (parsedRequest['public_path'] !== "/") && (parsedRequest['application'] !== undefined)) {
  1022. //page.redirect(pathname + '/' + app.helpers.GenerateInstanceID());
  1023. window.location.pathname = pathname + '/' + app.helpers.GenerateInstanceID()
  1024. }
  1025. })
  1026. }
  1027. HandleParsableRequestWithID(ctx) {
  1028. let app = window._app;
  1029. console.log(ctx.params);
  1030. var pathname = ctx.pathname;
  1031. let user = ctx.params.user;
  1032. let genID = ctx.params.id;
  1033. let space = ctx.params.space;
  1034. let savename = ctx.params.savename;
  1035. if (pathname[pathname.length - 1] == '/') {
  1036. pathname = pathname.slice(0, -1)
  1037. }
  1038. let vwfApp = {}
  1039. //await app.setUserPaths(user);
  1040. _app.helpers.getUserPub(user).then(function (res) {
  1041. if (res)
  1042. window._LCS_WORLD_USER = {
  1043. alias: user,
  1044. pub: res
  1045. }
  1046. }).then(res => {
  1047. let pathToParse = '/' + space; //pathname.replace('/' + user, "");
  1048. let parsedRequest = {
  1049. application: "index.vwf",
  1050. instance: genID,
  1051. private_path: undefined,
  1052. public_path: pathToParse
  1053. }
  1054. if (savename) {
  1055. parsedRequest.private_path = 'load/' + savename;
  1056. }
  1057. localStorage.setItem('lcs_app', JSON.stringify({ path: parsedRequest }));
  1058. return parsedRequest
  1059. }).then(pr => {
  1060. let cpath = pr.public_path;
  1061. return new Promise(res => _LCSDB.user(_LCS_WORLD_USER.pub).get('worlds').get(cpath.slice(1)).load(res)) //, { wait: 400 }
  1062. }).then(val => {
  1063. let fileConf = val['index_vwf_config_json'];
  1064. vwfApp.conf = {};
  1065. if (fileConf) {
  1066. let config = JSON.parse(fileConf);
  1067. vwfApp.conf = config
  1068. }
  1069. let manualSettings = localStorage.getItem('lcs_app_manual_settings');
  1070. if (manualSettings) {
  1071. let manualConf = JSON.parse(manualSettings);
  1072. vwfApp.conf.model = manualConf.model;
  1073. vwfApp.conf.view = manualConf.view;
  1074. }
  1075. //check & set default proxy for world
  1076. vwfApp.proxy = val.proxy ? val.proxy : _LCS_WORLD_USER.pub
  1077. // Try to load all required docs from Gun DB...
  1078. let promises = []
  1079. let worldPromise = new Promise(res => _LCSDB.user(_LCS_WORLD_USER.pub).get('worlds').get(space).load(res));
  1080. promises.push(worldPromise);
  1081. if (savename) {
  1082. let entryPath = 'savestate_/' + space + '/' + savename + '_vwf_json';
  1083. let savePromise = new Promise(res => _LCSDB.user(_LCS_WORLD_USER.pub).get('documents').get(space).path(entryPath).load(res, { wait: 400 }));
  1084. promises.push(savePromise);
  1085. }
  1086. let proxyPromise = new Promise(res => _LCSDB.user(vwfApp.proxy).get('proxy').load(res, { wait: 400 }));
  1087. promises.push(proxyPromise);
  1088. return Promise.all(promises)
  1089. }).then(res => {
  1090. //TODO: load libs for selected config drivers
  1091. return app.loadAppLibs()
  1092. }).then(res => {
  1093. return app.loadVWF()
  1094. }).then(res => {
  1095. var userLibraries = { model: {}, view: {} };
  1096. var application;
  1097. vwf.conf = vwfApp.conf;
  1098. vwf.proxy = vwfApp.proxy;
  1099. vwf.loadConfiguration(application, userLibraries, vwf.conf, compatibilityCheck);
  1100. })
  1101. }
  1102. async loadVWF() {
  1103. return loadjs([
  1104. '/lib/compatibilitycheck.js',
  1105. '/lib/lively.vm_standalone.js',
  1106. '/lib/require.js',
  1107. '/lib/crypto.js',
  1108. '/lib/md5.js',
  1109. '/lib/alea.js',
  1110. '/lib/mash.js',
  1111. '/vwf.js'
  1112. ], {
  1113. async: false,
  1114. returnPromise: true
  1115. })
  1116. }
  1117. async loadAppLibs() {
  1118. //by default AFrame & WebRTC driver libs loaded
  1119. return loadjs([
  1120. '/vwf/model/aframe/aframe-master.js',
  1121. '/vwf/model/aframe/addon/SkyShader.js',
  1122. '/vwf/model/aframe/addon/BVHLoader.js',
  1123. '/vwf/model/aframe/addon/TransformControls.js',
  1124. '/vwf/model/aframe/addon/THREE.MeshLine.js',
  1125. '/vwf/model/aframe/addon/three/BufferGeometryUtils.js',
  1126. '/vwf/model/aframe/addon/virtualgc/nipplejs.js',
  1127. '/vwf/model/aframe/addon/aframe-sun-sky.min.js',
  1128. '/vwf/model/aframe/extras/aframe-extras.loaders.min.js',
  1129. '/vwf/model/aframe/extras/aframe-extras.controls.min.js',
  1130. '/vwf/model/aframe/addon/aframe-teleport-controls.js',
  1131. '/vwf/model/aframe/kframe/aframe-aabb-collider-component.min.js',
  1132. '/vwf/model/aframe/addon/aframe-interpolation.js',
  1133. '/vwf/model/aframe/addon/aframe-components.js',
  1134. '/vwf/view/webrtc/adapter-latest.js',
  1135. '/lib/draggabilly/draggabilly.pkgd.js'
  1136. //'/vwf/view/arjs/aframe-ar.js' //load in aframe-ar-driver
  1137. ], {
  1138. async: false,
  1139. returnPromise: true
  1140. });
  1141. }
  1142. //get DB application state information for reflector (called from VWF)
  1143. async getApplicationState() {
  1144. let dataJson = JSON.parse(localStorage.getItem('lcs_app'));
  1145. if (dataJson) {
  1146. if (!dataJson.path['instance']) return undefined;
  1147. }
  1148. let userAlias = _LCS_WORLD_USER.alias;
  1149. let parsedRequest = dataJson.path;
  1150. if (parsedRequest['private_path']) {
  1151. var loadInfo = {
  1152. application_path: parsedRequest.public_path,
  1153. save_name: parsedRequest.private_path.split('/')[1]
  1154. }
  1155. var saveInfo = await this.loadSaveObject(loadInfo);
  1156. }
  1157. let loadObj = {
  1158. loadInfo: loadInfo ? loadInfo : {},
  1159. path: dataJson.path,
  1160. saveObject: saveInfo,
  1161. user: userAlias
  1162. }
  1163. localStorage.setItem('lcs_app', JSON.stringify(loadObj));
  1164. console.log(loadObj);
  1165. return loadObj
  1166. }
  1167. async loadSaveObject(loadInfo) {
  1168. if (!loadInfo.save_name) {
  1169. return undefined
  1170. }
  1171. let objName = "savestate_" + loadInfo['application_path'] + '/' + loadInfo['save_name'] + '_vwf_json';
  1172. let worldName = this.helpers.appPath;
  1173. let dbNode = _LCSDB.user(_LCS_WORLD_USER.pub).get('documents').get(worldName).get(objName);
  1174. let saveObject = await new Promise(res => dbNode.load(res, { wait: 300 }));
  1175. if (saveObject) {
  1176. let saveInfo = (typeof (saveObject.jsonState) == 'object') ? saveObject.jsonState : JSON.parse(saveObject.jsonState);
  1177. return saveInfo;
  1178. }
  1179. return undefined
  1180. }
  1181. async getProtoWorldFiles(userPub, worldName, date) {
  1182. return (new Promise(res => _LCSDB.user(userPub).get('worlds').get(worldName).once(res))).then(res => {
  1183. let worldFiles = Object.entries(res).filter(el => (el[0].includes('_json')) || (el[0].includes('_yaml')) || (el[0].includes('_html')) || (el[0].includes('_js')))
  1184. .filter(el => (el[0] !== 'info_json'));
  1185. console.log(worldFiles);
  1186. return worldFiles
  1187. });
  1188. }
  1189. get worldName() {
  1190. return vwf.application().split('/')[1];
  1191. }
  1192. async cloneWorld(worldName, userName, name, currentState) {
  1193. //if(worldName == name && userName == _LCSDB.user().is.alias
  1194. var userPub = _LCSDB.user().is.pub;
  1195. if (userName !== _LCSDB.user().is.alias) {
  1196. userPub = await _app.helpers.getUserPub(userName);
  1197. }
  1198. let newOwner = _LCSDB.user().is.pub;
  1199. let db = _LCSDB.user();
  1200. let newWorldName = name ? name : 'world' + this.helpers.randId();
  1201. let myWorlds = await (new Promise(res => db.get('worlds').load(res, { wait: 400 })));
  1202. if (myWorlds) {
  1203. let checkExist = Object.keys(myWorlds).filter(el => el == newWorldName);
  1204. if (checkExist.length > 0 && myWorlds[newWorldName]) {
  1205. _app.helpers.notyOK('World already exists!')
  1206. return
  1207. }
  1208. }
  1209. let created = new Date().valueOf();
  1210. await _LCSDB.user(userPub).get('worlds').get(worldName).load(all => {
  1211. let worldObj = Object.assign({}, all);
  1212. worldObj.owner = newOwner;
  1213. worldObj.parent = userName + '/' + worldName;
  1214. worldObj.featured = true
  1215. worldObj.published = true
  1216. worldObj.created = created
  1217. if (!all.proxy) {
  1218. worldObj.proxy = userPub;
  1219. } else {
  1220. worldObj.proxy = all.proxy;
  1221. }
  1222. console.log(worldObj);
  1223. let myWorld = _LCSDB.user().get('worlds').get(newWorldName).put({ id: newWorldName });
  1224. myWorld.put(worldObj, function (res) {
  1225. if (currentState) {
  1226. _app.saveWorld(newWorldName);
  1227. }
  1228. _app.helpers.notyOK('World cloned!')
  1229. });
  1230. })
  1231. }
  1232. async saveWorld(wn) {
  1233. let name = wn ? wn : this.worldName;
  1234. let proto = this.helpers.getWorldProto();
  1235. _LCSDB.user().get('worlds').get(name).get('index_vwf_json').put(JSON.stringify(proto), res => {
  1236. _app.helpers.notyOK('World current saved!')
  1237. });
  1238. }
  1239. async saveState(filename) // invoke with the view as "this"
  1240. {
  1241. //var clients = this.nodes["http://vwf.example.com/clients.vwf"];
  1242. // Save State Information
  1243. //let filename = self.helpers.appPath;
  1244. console.log("Saving: " + filename);
  1245. var state = vwf.getState();
  1246. state.nodes[0].children = {};
  1247. var timestamp = state["queue"].time;
  1248. timestamp = Math.round(timestamp * 1000);
  1249. let jsonValuePure = _app.helpers.replaceFloatArraysInNodeDef(state);
  1250. //remove all Ohm generated grammarsfrom state
  1251. let jsonValue = _app.helpers.removeGrammarObj(jsonValuePure);
  1252. var jsonState = JSON.stringify(jsonValue, null, '\t'); //JSON.stringify(jsonValue);
  1253. let rootPath = this.helpers.getRoot();
  1254. var inst = rootPath.inst;
  1255. var root = rootPath.root;
  1256. var json = jsonState;
  1257. //var documents = this.db.user().get('documents');
  1258. _LCSDB.user().get('documents').not(res => {
  1259. _LCSDB.user().get('documents').put({ id: 'documents' })
  1260. })
  1261. var saveRevision = new Date().valueOf();
  1262. var stateForStore = {
  1263. "root": root,
  1264. "filename": filename,
  1265. "inst": inst,
  1266. "timestamp": timestamp,
  1267. "extension": ".vwf.json",
  1268. "jsonState": json,
  1269. "publish": true,
  1270. "saveRevision": saveRevision
  1271. };
  1272. let stateObj = Object.assign({}, stateForStore);
  1273. var docName = 'savestate_/' + root + '/' + filename + '_vwf_json';
  1274. let myNewWorldState = _LCSDB.user().get('documents').get(root).get(docName).put({ 'id': docName });
  1275. //_LCSDB.user().get('documents').get(root).get(docName).put(stateWithRev, function(res) {
  1276. myNewWorldState.put(stateObj, function (res) {
  1277. if (res) {
  1278. _app.helpers.notyOK('Saved to ' + docName);
  1279. }
  1280. });
  1281. }
  1282. hideUIControl() {
  1283. let el = document.getElementById("ui-controls");
  1284. if (el) {
  1285. el.classList.remove("visible");
  1286. el.classList.add("not-visible");
  1287. }
  1288. }
  1289. showUIControl() {
  1290. let el = document.getElementById("ui-controls");
  1291. if (el) {
  1292. el.classList.remove("not-visible");
  1293. el.classList.add("visible");
  1294. }
  1295. }
  1296. hideProgressBar() {
  1297. var progressbar = document.getElementById("load-progressbar");
  1298. if (progressbar) {
  1299. progressbar.classList.remove("visible");
  1300. progressbar.classList.remove("mdc-linear-progress--indeterminate");
  1301. progressbar.classList.add("not-visible");
  1302. progressbar.classList.add("mdc-linear-progress--closed");
  1303. }
  1304. }
  1305. showProgressBar() {
  1306. let progressbar = document.getElementById("load-progressbar");
  1307. if (progressbar) {
  1308. progressbar.classList.remove("not-visible");
  1309. progressbar.classList.remove("mdc-linear-progress--closed");
  1310. progressbar.classList.add("visible");
  1311. progressbar.classList.add("mdc-linear-progress--indeterminate");
  1312. }
  1313. }
  1314. // SUPPORT of DELETE USER WORLDS & SAVE STATES (experimental)
  1315. // TODO: manual garbage collection
  1316. async deleteWorldState(worldName, stateName) {
  1317. let db = _LCSDB.user();
  1318. let stateEntry = 'savestate_/' + worldName + '/' + stateName + '_vwf_json';
  1319. db.get('documents').get(worldName).get(stateEntry).put(null, res => { });
  1320. }
  1321. async deleteWorld(name, type) {
  1322. let self = this;
  1323. if (type == 'proto') {
  1324. let worldName = name;
  1325. //TODO check for states (ask for deleting all states first...)
  1326. //delete states
  1327. let db = _LCSDB.user();
  1328. db.get('documents').once().map((res, k) => { if (k == worldName) return res }).once((res, k) => {
  1329. if (res) {
  1330. let worldStatesInfo = Object.entries(res).filter(el => el[0].includes('_info_vwf_json'));
  1331. worldStatesInfo.map(el => {
  1332. let saveName = el[0].split('/')[2].replace('_info_vwf_json', "");
  1333. console.log(saveName);
  1334. self.deleteWorldState(worldName, saveName)
  1335. //let stateEntry = 'savestate_/' + k + '/' + saveName + '_vwf_json';
  1336. })
  1337. }
  1338. })
  1339. db.get('worlds').get(worldName).put(null, res => {
  1340. let id = 'worldCard_' + _LCSDB.user().is.alias + '_' + worldName + '_';
  1341. let doc = document.querySelector('#' + id);
  1342. if (doc)
  1343. doc._refresh({})
  1344. })
  1345. } else if (type == 'state') {
  1346. let worldName = name.split('/')[0];
  1347. let stateName = name.split('/')[2];
  1348. await this.deleteWorldState(worldName, stateName);
  1349. }
  1350. app.helpers.notyOK("World Deleted!");
  1351. }
  1352. parseAppInstancesData(data) {
  1353. let jsonObj = JSON.parse(data);
  1354. var parsed = {};
  1355. let listData = {};
  1356. for (var prop in jsonObj) {
  1357. var name = prop.split('/')[1];
  1358. if (parsed[name]) {
  1359. parsed[name][prop] = jsonObj[prop];
  1360. } else {
  1361. parsed[name] = {};
  1362. parsed[name][prop] = jsonObj[prop];
  1363. }
  1364. }
  1365. //console.log(parsed);
  1366. for (var prop in parsed) {
  1367. var name = prop;
  1368. let obj = Object.entries(parsed[prop]);
  1369. var lists = {};
  1370. obj.forEach(el => {
  1371. if (!lists[name])
  1372. lists[name] = {};
  1373. lists[name][el[0]] = el[1]
  1374. });
  1375. // console.log(lists);
  1376. Object.entries(lists).forEach(list => {
  1377. listData[list[0]] = list[1];
  1378. })
  1379. }
  1380. return listData
  1381. // console.log(data)
  1382. }
  1383. async getAllProtoWorldsInfoForUser(userAlias, worldName) {
  1384. //let userPub = await new Promise(res => _LCSDB.get('users').get(userAlias).get('pub').once(res));
  1385. let userPub = await _app.helpers.getUserPub(userAlias);
  1386. var db = _LCSDB.user(userPub);
  1387. if (_LCSDB.user().is) {
  1388. if (_LCSDB.user().is.alias == userAlias)
  1389. db = _LCSDB.user();
  1390. }
  1391. let list = await (new Promise(res => db.get('worlds').load(res, { wait: 400 })))
  1392. .then(r => {
  1393. if (!worldName) {
  1394. return Promise.all(Object.keys(r).map(k => db.get('worlds').get(k).then(res => { return [k, res] })))
  1395. } else {
  1396. return Promise.all([db.get('worlds').get(worldName).then(res => { return [worldName, res] })])
  1397. }
  1398. }
  1399. )
  1400. .then(r => Promise.all(Object.keys(r).map(k => {
  1401. let objEl = r[k][1];
  1402. if (objEl) {
  1403. let obj = objEl.info_json;
  1404. if (obj) {
  1405. return _LCSDB.get(obj["#"]).then(res => { return { world: r[k], info: res } })
  1406. }
  1407. }
  1408. }))).then(r => { return r })
  1409. //console.log(list);
  1410. let docs = {};
  1411. list.forEach(el => {
  1412. if (el) {
  1413. let doc = {}
  1414. let res = el.info;
  1415. let index = el.world[0];
  1416. let proxy = el.world[1].proxy;
  1417. if (res && res !== 'null') {
  1418. //if (res.file && res.file !== 'null') {
  1419. //let worldDesc = JSON.parse(res.file);
  1420. var worldDesc = {};
  1421. if (typeof (res) == 'object') {
  1422. worldDesc = res
  1423. } else {
  1424. worldDesc = JSON.parse(res)
  1425. }
  1426. let root = Object.keys(worldDesc)[0];
  1427. var appInfo = worldDesc[root]['en'];
  1428. let langID = localStorage.getItem('krestianstvo_locale');
  1429. if (langID) {
  1430. appInfo = worldDesc[root][langID]
  1431. }
  1432. let settings = worldDesc[root]['settings'];
  1433. doc = {
  1434. 'worldName': index,
  1435. 'created': res.created ? res.created : res.modified,
  1436. 'modified': res.modified,
  1437. 'proxy': proxy,
  1438. 'type': 'proto',
  1439. 'userAlias': userAlias,
  1440. 'info': appInfo,
  1441. 'settings': settings
  1442. }
  1443. //}
  1444. }
  1445. if (Object.keys(doc).length !== 0)
  1446. docs[index] = doc;
  1447. }
  1448. })
  1449. if (worldName) {
  1450. return docs[worldName]
  1451. }
  1452. return docs
  1453. }
  1454. async setNewProxyForWorld(worldName, proxyName) {
  1455. if (_LCSDB.user().is) {
  1456. let newProxy = await _app.helpers.getUserPub(proxyName)
  1457. if (newProxy)
  1458. _LCSDB.user().get('worlds').get(worldName).put({ 'proxy': newProxy })
  1459. }
  1460. }
  1461. }
  1462. export { App }