app.js 56 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060
  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-fonts.css',
  1007. '/lib/ui/mdc.css',
  1008. '/lib/ui/ace/ace.js',
  1009. '/lib/ui/drag-drop.js',
  1010. '/lib/buffer5.6.0.min.js',
  1011. ], {
  1012. async: false,
  1013. returnPromise: true
  1014. })
  1015. }
  1016. generalIndex() {
  1017. let p = new Promise(res => res())
  1018. .then(res=>{
  1019. return _app.loadIndexLibs();
  1020. })
  1021. .then(res=>{
  1022. document.querySelector('body').classList.add("mdc-typography");
  1023. mdc.autoInit();
  1024. })
  1025. return p
  1026. }
  1027. ////////HANDLERS//////
  1028. HandleQuery(ctx, next) {
  1029. ctx.query = qs.parse(location.search.slice(1));
  1030. next();
  1031. }
  1032. HandleIndex() {
  1033. console.log("INDEX");
  1034. //window._app.hideUIControl();
  1035. _app.generateFrontPage();
  1036. _app.generalIndex().then(res=>{
  1037. if (!_app.indexApp) {
  1038. _app.indexApp = new IndexApp('index');
  1039. _app.hideProgressBar();
  1040. }
  1041. })
  1042. }
  1043. HandleNoPage() {
  1044. console.log("no such page");
  1045. _app.hideProgressBar();
  1046. let t404 = `
  1047. <h1>404 no page...</h1>
  1048. `;
  1049. let el = document.getElementById("loadscreen");
  1050. el.innerHTML = t404;
  1051. }
  1052. //handle parcable requests
  1053. HandleParsableLoadRequest(ctx) {
  1054. let app = window._app;
  1055. console.log(ctx.params);
  1056. //var pathname = ctx.pathname;
  1057. var spaceName = ctx.params.space;
  1058. var saveName = ctx.params.savename;
  1059. let user = ctx.params.user;
  1060. page.redirect('/' + user + '/' + spaceName + '/' + app.helpers.GenerateInstanceID() + '/load/' + saveName);
  1061. }
  1062. HandleParsableLoadRequestWithRev(ctx) {
  1063. let app = window._app;
  1064. console.log(ctx.params);
  1065. //var pathname = ctx.pathname;
  1066. var spaceName = ctx.params.space;
  1067. var saveName = ctx.params.savename;
  1068. var rev = ctx.params.rev;
  1069. let user = ctx.params.user;
  1070. page.redirect('/' + user + '/' + spaceName + '/' + app.helpers.GenerateInstanceID() + '/load/' + saveName + '/' + rev);
  1071. }
  1072. HandleParsableRequestGenID(ctx) {
  1073. let app = window._app;
  1074. console.log(ctx.params);
  1075. let user = ctx.params.user;
  1076. let space = ctx.params.space;
  1077. var pathname = ctx.pathname;
  1078. //await app.setUserPaths(user);
  1079. _app.helpers.getUserPub(user).then(function (res) {
  1080. if (res)
  1081. window._LCS_WORLD_USER = {
  1082. alias: user,
  1083. pub: res
  1084. }
  1085. if (pathname[pathname.length - 1] == '/') {
  1086. pathname = pathname.slice(0, -1)
  1087. }
  1088. let pathToParse = '/' + space; // pathname.replace('/' + user, "");
  1089. let parsedRequest = {
  1090. application: "index.vwf",
  1091. instance: undefined,
  1092. private_path: undefined,
  1093. public_path: pathToParse
  1094. }
  1095. localStorage.setItem('lcs_app', JSON.stringify({ path: parsedRequest }));
  1096. console.log(parsedRequest);
  1097. if ((parsedRequest['instance'] == undefined) && (parsedRequest['private_path'] == undefined) && (parsedRequest['public_path'] !== "/") && (parsedRequest['application'] !== undefined)) {
  1098. //page.redirect(pathname + '/' + app.helpers.GenerateInstanceID());
  1099. window.location.pathname = pathname + '/' + app.helpers.GenerateInstanceID()
  1100. }
  1101. })
  1102. }
  1103. generateInstanceID(){
  1104. window.location.pathname = pathname + '/' + app.helpers.GenerateInstanceID()
  1105. }
  1106. HandleParsableRequestWithID(ctx) {
  1107. let app = window._app;
  1108. console.log(ctx.params);
  1109. var pathname = ctx.pathname;
  1110. let user = ctx.params.user;
  1111. let space = ctx.params.space;
  1112. let savename = ctx.params.savename;
  1113. //let genID = ctx.params.id;
  1114. let query = ctx.query;
  1115. var genID = undefined;
  1116. if(Object.keys(query).length > 0){
  1117. if(query.k){
  1118. genID = query.k
  1119. }
  1120. }
  1121. if (!genID){
  1122. genID = app.helpers.GenerateInstanceID();
  1123. let urlAddon = '?k=' + genID;
  1124. let state = {
  1125. path: ctx.pathname + urlAddon
  1126. }
  1127. window.history.replaceState(state, space, window.location.href + urlAddon);
  1128. }
  1129. if (pathname[pathname.length - 1] == '/') {
  1130. pathname = pathname.slice(0, -1)
  1131. }
  1132. let vwfApp = {}
  1133. //await app.setUserPaths(user);
  1134. _app.helpers.getUserPub(user).then(function (res) {
  1135. if (res)
  1136. window._LCS_WORLD_USER = {
  1137. alias: user,
  1138. pub: res
  1139. }
  1140. }).then(res => {
  1141. let pathToParse = '/' + space; //pathname.replace('/' + user, "");
  1142. let parsedRequest = {
  1143. application: "index.vwf",
  1144. instance: genID,
  1145. private_path: undefined,
  1146. public_path: pathToParse
  1147. }
  1148. if (savename) {
  1149. parsedRequest.private_path = 'load/' + savename;
  1150. }
  1151. localStorage.setItem('lcs_app', JSON.stringify({ path: parsedRequest }));
  1152. return parsedRequest
  1153. }).then(pr => {
  1154. let cpath = pr.public_path;
  1155. return new Promise(res => _LCSDB.user(_LCS_WORLD_USER.pub).get('worlds').get(cpath.slice(1)).load(res)) //, { wait: 400 }
  1156. }).then(val => {
  1157. let fileConf = val['index_vwf_config_json'];
  1158. vwfApp.conf = {};
  1159. if (fileConf) {
  1160. let config = JSON.parse(fileConf);
  1161. vwfApp.conf = config
  1162. }
  1163. let infoFile = val['info_json'];
  1164. let infoSettings = infoFile ? JSON.parse(infoFile).info.settings: null;
  1165. if(infoSettings){
  1166. let manualSettings = localStorage.getItem('lcs_app_manual_settings');
  1167. if (manualSettings) {
  1168. let manualConf = JSON.parse(manualSettings);
  1169. vwfApp.conf.model = manualConf.model;
  1170. vwfApp.conf.view = manualConf.view;
  1171. }
  1172. }
  1173. //check & set default proxy for world
  1174. vwfApp.proxy = val.proxy ? val.proxy : _LCS_WORLD_USER.pub
  1175. // Try to load all required docs from Gun DB...
  1176. let promises = []
  1177. let worldPromise = new Promise(res => _LCSDB.user(_LCS_WORLD_USER.pub).get('worlds').get(space).load(res));
  1178. promises.push(worldPromise);
  1179. if (savename) {
  1180. let entryPath = 'savestate_/' + space + '/' + savename + '_vwf_json';
  1181. let savePromise = new Promise(res => _LCSDB.user(_LCS_WORLD_USER.pub).get('documents').get(space).path(entryPath).load(res, { wait: 400 }));
  1182. promises.push(savePromise);
  1183. }
  1184. let proxyPromise = new Promise(res => _LCSDB.user(vwfApp.proxy).get('proxy').load(res, { wait: 400 }));
  1185. promises.push(proxyPromise);
  1186. return Promise.all(promises)
  1187. }).then(res => {
  1188. //Load vwf_view Document
  1189. let dbPath = _app.helpers.appName + '_js';
  1190. vwfApp.doc = res[0][dbPath];
  1191. //Load libs for selected config drivers
  1192. let libs = app.getLibsForConfig(vwfApp.conf);
  1193. if(libs.length !== 0)
  1194. return app.loadAppLibs(libs);
  1195. return 'nodriver'
  1196. })
  1197. .then(res => {
  1198. //Load VWF libs
  1199. return app.loadVWF();
  1200. }).then(res => {
  1201. let connectionConf = {
  1202. luminary: _app.isLuminary,
  1203. luminaryGlobalHB: _app.isLuminaryGlobalHB,
  1204. luminaryGlobalHBPath: _app.luminaryGlobalHBPath
  1205. }
  1206. //Load main VWF app
  1207. window.vwf = new VWF(vwfApp.conf, vwfApp.proxy, vwfApp.doc, connectionConf)
  1208. let userLibraries = { model: {}, view: {} };
  1209. let application = undefined;
  1210. vwf.loadConfiguration(application, userLibraries, null);
  1211. })
  1212. }
  1213. getLibsForConfig(conf){
  1214. //Load not ES6 standard libs before driver loads
  1215. //Use import in drivers by default
  1216. const confLibsDefaults = {
  1217. '/drivers/model/aframe':[
  1218. '/drivers/model/aframe/aframe-master.js',
  1219. '/drivers/model/aframe/addon/SkyShader.js',
  1220. '/drivers/model/aframe/addon/BVHLoader.js',
  1221. '/drivers/model/aframe/addon/TransformControls.js',
  1222. '/drivers/model/aframe/addon/THREE.MeshLine.js',
  1223. '/drivers/model/aframe/addon/three/BufferGeometryUtils.js',
  1224. '/drivers/model/aframe/addon/virtualgc/virtual-gamepad-controls.css',
  1225. '/drivers/model/aframe/addon/virtualgc/nipplejs.js',
  1226. '/drivers/model/aframe/addon/aframe-sun-sky.min.js',
  1227. '/drivers/model/aframe/extras/aframe-extras.loaders.min.js',
  1228. '/drivers/model/aframe/extras/aframe-extras.controls.min.js',
  1229. '/drivers/model/aframe/addon/aframe-teleport-controls.js',
  1230. '/drivers/model/aframe/kframe/aframe-aabb-collider-component.min.js',
  1231. '/drivers/model/aframe/addon/aframe-interpolation.js',
  1232. '/drivers/model/aframe/addon/aframe-components.js'
  1233. ],
  1234. '/drivers/view/webrtc': [
  1235. '/drivers/view/webrtc/adapter-latest.js'
  1236. ],
  1237. '/drivers/view/editor': [
  1238. '/lib/ui/cell.js',
  1239. '/lib/ui/treeview/treeview.min.css',
  1240. '/lib/ui/treeview/treeview.min.js',
  1241. '/lib/ui/mdc/dist/material-components-web.min.css',
  1242. '/lib/ui/mdc/dist/material-components-web.min.js',
  1243. '/lib/ui/mdc-fonts.css',
  1244. '/lib/ui/mdc.css',
  1245. '/lib/ui/ace/ace.js',
  1246. '/lib/ui/screenfull/screenfull.min.js',
  1247. '/lib/ui/drag-drop.js',
  1248. '/lib/buffer5.6.0.min.js',
  1249. '/lib/ui/qrcode.min.js',
  1250. '/drivers/view/editor/draggabilly/draggabilly.pkgd.js',
  1251. '/drivers/view/editor/colorpicker/colorpicker.min.js',
  1252. '/drivers/view/editor/colorpicker/themes.css',
  1253. '/drivers/view/editor/editorLive.css'
  1254. ],
  1255. '/drivers/view/aframe-ar-driver':[
  1256. '/drivers/view/arjs/aframe-ar.js'
  1257. ],
  1258. '/drivers/view/lego-boost':[
  1259. '/drivers/view/lego-boost/bundle.js'
  1260. ],
  1261. '/drivers/view/osc':[
  1262. '/drivers/view/oscjs/osc-browser.min.js'
  1263. ]
  1264. }
  1265. var appLibs = [];
  1266. Object.keys(conf.model).concat(Object.keys(conf.view)).forEach(el => {
  1267. let driver = confLibsDefaults[el];
  1268. if(driver)
  1269. appLibs = appLibs.concat(confLibsDefaults[el])
  1270. });
  1271. return appLibs
  1272. }
  1273. async loadVWF() {
  1274. return loadjs([
  1275. '/lib/async.min.js',
  1276. '/lib/qheap.js',
  1277. '/lib/lively.vm_standalone.js',
  1278. '/lib/crypto.js',
  1279. '/lib/md5.js',
  1280. '/lib/alea.js',
  1281. '/lib/mash.js'
  1282. ], {
  1283. async: false,
  1284. returnPromise: true
  1285. })
  1286. }
  1287. async loadAppLibs(libs) {
  1288. return loadjs(libs, {
  1289. async: false,
  1290. returnPromise: true
  1291. });
  1292. }
  1293. //get DB application state information for reflector (called from VWF)
  1294. async getApplicationState() {
  1295. let dataJson = JSON.parse(localStorage.getItem('lcs_app'));
  1296. if (dataJson) {
  1297. if (!dataJson.path['instance']) return undefined;
  1298. }
  1299. let userAlias = _LCS_WORLD_USER.alias;
  1300. let parsedRequest = dataJson.path;
  1301. if (parsedRequest['private_path']) {
  1302. var loadInfo = {
  1303. application_path: parsedRequest.public_path,
  1304. save_name: parsedRequest.private_path.split('/')[1]
  1305. }
  1306. var saveInfo = await this.loadSaveObject(loadInfo);
  1307. }
  1308. let loadObj = {
  1309. loadInfo: loadInfo ? loadInfo : {},
  1310. path: dataJson.path,
  1311. saveObject: saveInfo,
  1312. user: userAlias
  1313. }
  1314. localStorage.setItem('lcs_app', JSON.stringify(loadObj));
  1315. console.log(loadObj);
  1316. return loadObj
  1317. }
  1318. async loadSaveObject(loadInfo) {
  1319. if (!loadInfo.save_name) {
  1320. return undefined
  1321. }
  1322. let objName = "savestate_" + loadInfo['application_path'] + '/' + loadInfo['save_name'] + '_vwf_json';
  1323. let worldName = this.helpers.appPath;
  1324. let dbNode = _LCSDB.user(_LCS_WORLD_USER.pub).get('documents').get(worldName).get(objName);
  1325. let saveObject = await new Promise(res => dbNode.load(res, { wait: 300 }));
  1326. if (saveObject) {
  1327. let saveInfo = (typeof (saveObject.jsonState) == 'object') ? saveObject.jsonState : JSON.parse(saveObject.jsonState);
  1328. return saveInfo;
  1329. }
  1330. return undefined
  1331. }
  1332. async getProtoWorldFiles(userPub, worldName, date) {
  1333. return (new Promise(res => _LCSDB.user(userPub).get('worlds').get(worldName).once(res))).then(res => {
  1334. let worldFiles = Object.entries(res).filter(el => (el[0].includes('_json')) || (el[0].includes('_yaml')) || (el[0].includes('_html')) || (el[0].includes('_js')))
  1335. .filter(el => (el[0] !== 'info_json'));
  1336. console.log(worldFiles);
  1337. return worldFiles
  1338. });
  1339. }
  1340. get worldName() {
  1341. return vwf.application().split('/')[1];
  1342. }
  1343. async cloneWorld(worldName, userName, name, currentState) {
  1344. //if(worldName == name && userName == _LCSDB.user().is.alias
  1345. var userPub = _LCSDB.user().is.pub;
  1346. if (userName !== _LCSDB.user().is.alias) {
  1347. userPub = await _app.helpers.getUserPub(userName);
  1348. }
  1349. let newOwner = _LCSDB.user().is.pub;
  1350. let db = _LCSDB.user();
  1351. let newWorldName = name ? name : 'world' + this.helpers.randId();
  1352. let myWorlds = await (new Promise(res => db.get('worlds').load(res, { wait: 400 })));
  1353. if (myWorlds) {
  1354. let checkExist = Object.keys(myWorlds).filter(el => el == newWorldName);
  1355. if (checkExist.length > 0 && myWorlds[newWorldName]) {
  1356. _app.helpers.notyOK('World already exists!')
  1357. return
  1358. }
  1359. }
  1360. let created = new Date().valueOf();
  1361. await _LCSDB.user(userPub).get('worlds').get(worldName).load(all => {
  1362. let worldObj = Object.assign({}, all);
  1363. worldObj.owner = newOwner;
  1364. worldObj.parent = userName + '/' + worldName;
  1365. worldObj.featured = true
  1366. worldObj.published = true
  1367. worldObj.created = created
  1368. if (!all.proxy) {
  1369. worldObj.proxy = userPub;
  1370. } else {
  1371. worldObj.proxy = all.proxy;
  1372. }
  1373. console.log(worldObj);
  1374. let myWorld = _LCSDB.user().get('worlds').get(newWorldName).put({ id: newWorldName });
  1375. myWorld.put(worldObj, function (res) {
  1376. if (currentState) {
  1377. _app.saveWorld(newWorldName);
  1378. }
  1379. _app.helpers.notyOK('World cloned!')
  1380. });
  1381. })
  1382. }
  1383. async saveWorld(wn) {
  1384. let name = wn ? wn : _app.helpers.appPath;
  1385. let proto = this.helpers.getWorldProto();
  1386. _LCSDB.user().get('worlds').get(name).get('index_vwf_json').put(JSON.stringify(proto), res => {
  1387. _app.helpers.notyOK('World current saved!')
  1388. });
  1389. }
  1390. async saveState(filename) // invoke with the view as "this"
  1391. {
  1392. //var clients = this.nodes["http://vwf.example.com/clients.vwf"];
  1393. // Save State Information
  1394. //let filename = self.helpers.appPath;
  1395. console.log("Saving: " + filename);
  1396. var state = vwf.getState();
  1397. state.nodes[0].children = {};
  1398. var timestamp = state["queue"].time;
  1399. timestamp = Math.round(timestamp * 1000);
  1400. let jsonValuePure = _app.helpers.replaceFloatArraysInNodeDef(state);
  1401. //remove all Ohm generated grammarsfrom state
  1402. let jsonValue = _app.helpers.removeGrammarObj(jsonValuePure);
  1403. var jsonState = JSON.stringify(jsonValue, null, '\t'); //JSON.stringify(jsonValue);
  1404. let rootPath = this.helpers.getRoot();
  1405. var inst = rootPath.inst;
  1406. var root = rootPath.root;
  1407. var json = jsonState;
  1408. //var documents = this.db.user().get('documents');
  1409. _LCSDB.user().get('documents').not(res => {
  1410. _LCSDB.user().get('documents').put({ id: 'documents' })
  1411. })
  1412. var saveRevision = new Date().valueOf();
  1413. var stateForStore = {
  1414. "root": root,
  1415. "filename": filename,
  1416. "inst": inst,
  1417. "timestamp": timestamp,
  1418. "extension": ".vwf.json",
  1419. "jsonState": json,
  1420. "publish": true,
  1421. "saveRevision": saveRevision
  1422. };
  1423. let stateObj = Object.assign({}, stateForStore);
  1424. var docName = 'savestate_/' + root + '/' + filename + '_vwf_json';
  1425. let myNewWorldState = _LCSDB.user().get('documents').get(root).get(docName).put({ 'id': docName });
  1426. //_LCSDB.user().get('documents').get(root).get(docName).put(stateWithRev, function(res) {
  1427. myNewWorldState.put(stateObj, function (res) {
  1428. if (res) {
  1429. _app.helpers.notyOK('Saved to ' + docName);
  1430. }
  1431. });
  1432. }
  1433. hideUIControl() {
  1434. let el = document.getElementById("ui-controls");
  1435. if (el) {
  1436. el.classList.remove("visible");
  1437. el.classList.add("not-visible");
  1438. }
  1439. }
  1440. showUIControl() {
  1441. let el = document.getElementById("ui-controls");
  1442. if (el) {
  1443. el.classList.remove("not-visible");
  1444. el.classList.add("visible");
  1445. }
  1446. }
  1447. hideProgressBar() {
  1448. let el = document.getElementById('loadscreen');
  1449. if(el){
  1450. el.getElementsByClassName('spinner')[0].remove();
  1451. //window._spinner.stop(false);
  1452. }
  1453. }
  1454. showProgressBar() {
  1455. let el = document.getElementById('loadscreen');
  1456. _app.spinner.spin(el);
  1457. }
  1458. // SUPPORT of DELETE USER WORLDS & SAVE STATES (experimental)
  1459. // TODO: manual garbage collection
  1460. async deleteWorldState(worldName, stateName) {
  1461. let db = _LCSDB.user();
  1462. let stateEntry = 'savestate_/' + worldName + '/' + stateName + '_vwf_json';
  1463. db.get('documents').get(worldName).get(stateEntry).put(null, res => { });
  1464. }
  1465. async deleteWorld(name, type) {
  1466. let self = this;
  1467. if (type == 'proto') {
  1468. let worldName = name;
  1469. //TODO check for states (ask for deleting all states first...)
  1470. //delete states
  1471. let db = _LCSDB.user();
  1472. db.get('documents').once().map((res, k) => { if (k == worldName) return res }).once((res, k) => {
  1473. if (res) {
  1474. let worldStatesInfo = Object.entries(res).filter(el => el[0].includes('_info_vwf_json'));
  1475. worldStatesInfo.map(el => {
  1476. let saveName = el[0].split('/')[2].replace('_info_vwf_json', "");
  1477. console.log(saveName);
  1478. self.deleteWorldState(worldName, saveName)
  1479. //let stateEntry = 'savestate_/' + k + '/' + saveName + '_vwf_json';
  1480. })
  1481. }
  1482. })
  1483. db.get('worlds').get(worldName).put(null, res => {
  1484. let id = 'worldCard_' + _LCSDB.user().is.alias + '_' + worldName + '_';
  1485. let doc = document.querySelector('#' + id);
  1486. if (doc)
  1487. doc._refresh({})
  1488. })
  1489. } else if (type == 'state') {
  1490. let worldName = name.split('/')[0];
  1491. let stateName = name.split('/')[2];
  1492. await this.deleteWorldState(worldName, stateName);
  1493. }
  1494. app.helpers.notyOK("World Deleted!");
  1495. }
  1496. parseAppInstancesData(data) {
  1497. let jsonObj = JSON.parse(data);
  1498. var parsed = {};
  1499. let listData = {};
  1500. for (var prop in jsonObj) {
  1501. var name = prop.split('/')[1];
  1502. if (parsed[name]) {
  1503. parsed[name][prop] = jsonObj[prop];
  1504. } else {
  1505. parsed[name] = {};
  1506. parsed[name][prop] = jsonObj[prop];
  1507. }
  1508. }
  1509. //console.log(parsed);
  1510. for (var prop in parsed) {
  1511. var name = prop;
  1512. let obj = Object.entries(parsed[prop]);
  1513. var lists = {};
  1514. obj.forEach(el => {
  1515. if (!lists[name])
  1516. lists[name] = {};
  1517. lists[name][el[0]] = el[1]
  1518. });
  1519. // console.log(lists);
  1520. Object.entries(lists).forEach(list => {
  1521. listData[list[0]] = list[1];
  1522. })
  1523. }
  1524. return listData
  1525. // console.log(data)
  1526. }
  1527. async getAllProtoWorldsInfoForUser(userAlias, worldName) {
  1528. //let userPub = await new Promise(res => _LCSDB.get('users').get(userAlias).get('pub').once(res));
  1529. let userPub = await _app.helpers.getUserPub(userAlias);
  1530. var db = _LCSDB.user(userPub);
  1531. if (_LCSDB.user().is) {
  1532. if (_LCSDB.user().is.alias == userAlias)
  1533. db = _LCSDB.user();
  1534. }
  1535. let list = await (new Promise(res => db.get('worlds').load(res, { wait: 400 })))
  1536. .then(r => {
  1537. if (!worldName) {
  1538. return Promise.all(Object.keys(r).map(k => db.get('worlds').get(k).then(res => { return [k, res] })))
  1539. } else {
  1540. return Promise.all([db.get('worlds').get(worldName).then(res => { return [worldName, res] })])
  1541. }
  1542. }
  1543. )
  1544. .then(r => Promise.all(Object.keys(r).map(k => {
  1545. let objEl = r[k][1];
  1546. if (objEl) {
  1547. let obj = objEl.info_json;
  1548. if (obj) {
  1549. return _LCSDB.get(obj["#"]).then(res => { return { world: r[k], info: res } })
  1550. }
  1551. }
  1552. }))).then(r => { return r })
  1553. //console.log(list);
  1554. let docs = {};
  1555. list.forEach(el => {
  1556. if (el) {
  1557. let doc = {}
  1558. let res = el.info;
  1559. let index = el.world[0];
  1560. let proxy = el.world[1].proxy;
  1561. if (res && res !== 'null') {
  1562. //if (res.file && res.file !== 'null') {
  1563. //let worldDesc = JSON.parse(res.file);
  1564. var worldDesc = {};
  1565. if (typeof (res) == 'object') {
  1566. worldDesc = res
  1567. } else {
  1568. worldDesc = JSON.parse(res)
  1569. }
  1570. let root = Object.keys(worldDesc)[0];
  1571. var appInfo = worldDesc[root]['en'];
  1572. let langID = localStorage.getItem('krestianstvo_locale');
  1573. if (langID) {
  1574. appInfo = worldDesc[root][langID]
  1575. }
  1576. let settings = worldDesc[root]['settings'];
  1577. doc = {
  1578. 'worldName': index,
  1579. 'created': res.created ? res.created : res.modified,
  1580. 'modified': res.modified,
  1581. 'proxy': proxy,
  1582. 'type': 'proto',
  1583. 'userAlias': userAlias,
  1584. 'info': appInfo,
  1585. 'settings': settings
  1586. }
  1587. //}
  1588. }
  1589. if (Object.keys(doc).length !== 0)
  1590. docs[index] = doc;
  1591. }
  1592. })
  1593. if (worldName) {
  1594. return docs[worldName]
  1595. }
  1596. return docs
  1597. }
  1598. async setNewProxyForWorld(worldName, proxyName) {
  1599. if (_LCSDB.user().is) {
  1600. let newProxy = await _app.helpers.getUserPub(proxyName)
  1601. if (newProxy)
  1602. _LCSDB.user().get('worlds').get(worldName).put({ 'proxy': newProxy })
  1603. }
  1604. }
  1605. }
  1606. export { App }