app.js 58 KB

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