app.js 55 KB

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