app.js 56 KB

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