app.js 55 KB

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