app.js 56 KB

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