app.js 56 KB

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