app.js 56 KB

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