app.js 70 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401
  1. /*
  2. The MIT License (MIT)
  3. Copyright (c) 2014-2018 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 { log } from '/lib/utils/log.js';
  8. import { Helpers } from '/helpers.js';
  9. import { WorldApp } from '/web/world-app.js';
  10. import { Widgets } from '/lib/widgets.js';
  11. import { ReflectorClient } from './reflector-client.js';
  12. import { Luminary } from '/luminary.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. window._noty = new Noty;
  21. this.helpers = new Helpers;
  22. this.log = log;
  23. this.hashids = new Hashids.default();
  24. this.clearLocalStorage();
  25. this.luminary = new Luminary;
  26. this.reflectorClient = new ReflectorClient;
  27. this.config = {};
  28. this.initDB()
  29. new Promise(res => { this.initUser(); res });
  30. import('/lib/polyglot/language.js').then(res => {
  31. window._LangManager = new res.default;
  32. return new Promise(r=>r(_LangManager.setLanguage()))})
  33. .then(res=>{
  34. window._l = _LangManager.language;
  35. })
  36. .then(res => {
  37. return import('/web/index-app.js');
  38. }).then(res => {
  39. window.IndexApp = res.default;
  40. this.setPageRoutes();
  41. });
  42. }
  43. setPageRoutes() {
  44. //client routes
  45. page('/', this.HandleIndex);
  46. page('/setup', this.HandleSetupIndex);
  47. page('/debug', this.HandleDebugIndex);
  48. page('/settings', this.HandleSettingsIndex);
  49. page('/profile', this.HandleUserIndex);
  50. page('/worlds', this.HandleIndex);
  51. page('/:user/worlds', this.HandleUserWorlds);
  52. page('/:user/worlds/:type', this.HandleUserWorldsWithType);
  53. page('/:user/:type/:name/edit/:file', this.HandleFileEdit);
  54. page('/:user/:space', this.HandleParsableRequestGenID);
  55. page('/:user/:space/about', this.HandleWorldAbout);
  56. page('/:user/:space/:id', this.HandleParsableRequestWithID);
  57. page('/:user/:space/index.vwf/:id', this.HandleParsableRequestWithID);
  58. page('/:user/:space/load/:savename', this.HandleParsableLoadRequest);
  59. page('/:user/:space/load/:savename/about', this.HandleWorldAbout);
  60. page('/:user/:space/:id/load/:savename', this.HandleParsableRequestWithID);
  61. page('/:user/:space/load/:savename/:rev', this.HandleParsableLoadRequestWithRev);
  62. page('/:user/:space/:id/load/:savename/:rev', this.HandleParsableRequestWithID);
  63. page('*', this.HandleNoPage);
  64. page();
  65. }
  66. initDB() {
  67. var config = JSON.parse(localStorage.getItem('lcs_config'));
  68. if (!config) {
  69. config = {
  70. 'luminary': false,
  71. 'luminaryPath': 'luminary',
  72. 'luminaryGlobalHBPath': 'server/heartbeat',
  73. 'luminaryGlobalHB': false,
  74. 'dbhost': window.location.origin + '/gun', // 'https://' + window.location.hostname + ':8080/gun', //'http://localhost:8080/gun',
  75. 'reflector': 'https://' + window.location.hostname + ':3002',
  76. 'webrtc': false,
  77. 'language': 'en',
  78. 'd3DoF': false,
  79. 'd6DoF': false
  80. }
  81. localStorage.setItem('lcs_config', JSON.stringify(config));
  82. }
  83. if (!config.luminaryPath) {
  84. config.luminaryPath = 'luminary';
  85. localStorage.setItem('lcs_config', JSON.stringify(config));
  86. }
  87. if (!config.luminaryGlobalHBPath) {
  88. config.luminaryGlobalHBPath = 'server/heartbeat';
  89. localStorage.setItem('lcs_config', JSON.stringify(config));
  90. }
  91. if (!config.luminaryGlobalHB) {
  92. config.luminaryGlobalHB = false;
  93. localStorage.setItem('lcs_config', JSON.stringify(config));
  94. }
  95. if (!config.webrtc) {
  96. config.webrtc = false;
  97. localStorage.setItem('lcs_config', JSON.stringify(config));
  98. }
  99. if (!config.d3DoF) {
  100. config.d3DoF = false;
  101. localStorage.setItem('lcs_config', JSON.stringify(config));
  102. }
  103. if (!config.d6DoF) {
  104. config.d6DoF = false;
  105. localStorage.setItem('lcs_config', JSON.stringify(config));
  106. }
  107. this.config = config;
  108. let webrtcConnection = this.config.webrtc;
  109. const opt = { peers: this.dbHost, localStorage: false, RTCPeerConnection: webrtcConnection, axe: false } //localStorage: false,
  110. //const opt = { peers: this.dbHost, localStorage: false, until: 1000, chunk: 5, axe: false} //until: 5000, chunk: 5
  111. //opt.store = RindexedDB(opt);
  112. this.db = Gun(opt);
  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: 1000,
  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: 1000,
  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. initUser() {
  159. function recall() {
  160. _LCSDB.user().recall({ sessionStorage: 1 }, res => {
  161. console.log('User is: ', _LCSDB.user().is);
  162. if (_LCSDB.user().is)
  163. _app.helpers.checkUserCollision();
  164. });
  165. }
  166. setTimeout(
  167. recall, 1000)
  168. }
  169. async chooseConnection(data) {
  170. if (this.isLuminary) {
  171. return await _app.luminary.connect(data) //use Luminary
  172. } else {
  173. return data //use Reflector
  174. }
  175. }
  176. get isLuminary() {
  177. return this.config.luminary;
  178. }
  179. get isLuminaryGlobalHB() {
  180. return this.config.luminaryGlobalHB;
  181. }
  182. get isWebRTC() {
  183. return this.config.webrtc;
  184. }
  185. get luminaryGlobalHBPath() {
  186. var res = "";
  187. let config = localStorage.getItem('lcs_config');
  188. if (config) {
  189. res = JSON.parse(config).luminaryGlobalHBPath;
  190. }
  191. return res;
  192. }
  193. get luminaryPath() {
  194. var res = "";
  195. let config = localStorage.getItem('lcs_config');
  196. if (config) {
  197. res = JSON.parse(config).luminaryPath;
  198. }
  199. return res;
  200. }
  201. get reflectorHost() {
  202. var res = "";
  203. let config = localStorage.getItem('lcs_config');
  204. if (config) {
  205. res = JSON.parse(config).reflector;
  206. }
  207. return res;
  208. }
  209. get dbHost() {
  210. var res = "";
  211. let config = localStorage.getItem('lcs_config');
  212. if (config) {
  213. res = JSON.parse(config).dbhost;
  214. }
  215. return res;
  216. }
  217. async loadProxyDefaults() {
  218. // Optional req from server
  219. // load to DB default proxy files (VWF & A-Frame components)
  220. let proxyResponse = await fetch('/proxy-files', { method: 'get' });
  221. let proxyFiles = await proxyResponse.json();
  222. let filterProxyFiles = proxyFiles.filter(el => (el !== null));
  223. console.log(filterProxyFiles);
  224. var origin = window.location.origin;
  225. //var userPub = this.db.user().is.pub;
  226. let proxyObj = {};
  227. for (var index in filterProxyFiles) {
  228. let doc = filterProxyFiles[index];
  229. if (doc) {
  230. var url = origin + doc;
  231. var entryName = url.replace(origin + '/defaults/', "").split(".").join("_");
  232. let proxyFile = await fetch(url, { method: 'get' });
  233. let responseText = await proxyFile.text();
  234. if (responseText) {
  235. proxyObj[entryName] = responseText;
  236. }
  237. }
  238. }
  239. console.log(proxyObj);
  240. let proxy = _LCSDB.user().get('proxy');
  241. proxy.put(proxyObj);
  242. }
  243. async loadWorldsDefaults(replace) {
  244. // Optional req from server
  245. //load to DB default worlds
  246. let worldsResponse = await fetch('/world-files', { method: 'get' });
  247. let worldFiles = await worldsResponse.json();
  248. let filterworldFiles = worldFiles.filter(el => (el !== null));
  249. console.log(filterworldFiles);
  250. let worldsObj = {};
  251. for (var index in filterworldFiles) {
  252. let doc = filterworldFiles[index];
  253. if (doc) {
  254. let url = window.location.origin + doc;
  255. var entryName = url.replace(window.location.origin + '/defaults/worlds/', "").split(".").join("_");
  256. let worldName = entryName.split("/")[0];
  257. let userPub = _LCSDB.user().is.pub;
  258. let worldFile = await fetch(url, { method: 'get' });
  259. let worldSource = await worldFile.text();
  260. if (worldSource) {
  261. //let modified = new Date().valueOf();
  262. let created = new Date().valueOf();
  263. if (!worldsObj[worldName]) {
  264. worldsObj[worldName] = {
  265. 'parent': '-',
  266. 'owner': userPub,
  267. 'featured': true,
  268. 'published': true,
  269. 'proxy': userPub,
  270. 'created': created,
  271. 'modified': created
  272. }
  273. }
  274. let entry = entryName.replace(worldName + '/', "");
  275. worldsObj[worldName][entry] = worldSource
  276. }
  277. }
  278. }
  279. console.log(worldsObj);
  280. if (replace) {
  281. //force replace all default worlds
  282. let worlds = _LCSDB.user().get('worlds');
  283. worlds.put(worldsObj);
  284. } else {
  285. Object.entries(worldsObj).forEach(res => {
  286. let worldName = res[0];
  287. let files = res[1];
  288. Object.entries(files).forEach(file => {
  289. _LCSDB.user().get('worlds').get(worldName).get(file[0]).not(function (res) {
  290. _LCSDB.user().get('worlds').get(worldName).get(file[0]).put(file[1]);
  291. })
  292. })
  293. })
  294. }
  295. }
  296. async loadEmptyDefaultProto() {
  297. //empty proto world
  298. let userPub = _LCSDB.user().is.pub;
  299. let worldsObj = {};
  300. let emptyWorld = {
  301. "index_vwf_yaml": YAML.stringify(
  302. {
  303. "extends": "http://vwf.example.com/aframe/ascene.vwf"
  304. }, 4),
  305. "index_vwf_config_yaml": YAML.stringify(
  306. {
  307. "info": {
  308. "title": "Empty World"
  309. },
  310. "model": {
  311. "vwf/model/aframe": null
  312. },
  313. "view": {
  314. "vwf/view/aframe": null,
  315. "vwf/view/editor-new": null
  316. }
  317. }, 4),
  318. "assets_json": JSON.stringify({}),
  319. "index_vwf_html": JSON.stringify("<!-- DEFAULT HTML -->"),
  320. "appui_js": JSON.stringify("//appui in JS"),
  321. "info_json": JSON.stringify({
  322. "info": {
  323. "en": {
  324. "title": "Empty World",
  325. "imgUrl": "",
  326. "text": "Empty World"
  327. },
  328. "ru": {
  329. "title": "Новый Мир",
  330. "imgUrl": "",
  331. "text": "Новый Мир"
  332. }
  333. }
  334. }, null, 4)
  335. }
  336. let created = new Date().valueOf();
  337. worldsObj['empty'] = {
  338. 'parent': '-',
  339. 'owner': userPub,
  340. 'featured': true,
  341. 'published': true,
  342. 'proxy': userPub,
  343. 'created': created,
  344. 'modified': created
  345. }
  346. Object.keys(emptyWorld).forEach(el => {
  347. worldsObj['empty'][el] = emptyWorld[el];
  348. })
  349. console.log(worldsObj);
  350. Object.entries(worldsObj).forEach(el => {
  351. let worldName = el[0];
  352. let files = el[1];
  353. Object.entries(files).forEach(file => {
  354. _LCSDB.user().get('worlds').get(worldName).get(file[0]).put(file[1]);
  355. })
  356. })
  357. }
  358. HandleDebugIndex() {
  359. window._app.hideProgressBar();
  360. window._app.hideUIControl();
  361. let el = document.createElement("div");
  362. el.setAttribute("id", "appGUI");
  363. document.body.appendChild(el);
  364. _cellWidgets.debugGUI();
  365. }
  366. HandleSettingsIndex() {
  367. window._app.hideProgressBar();
  368. window._app.hideUIControl();
  369. let el = document.createElement("div");
  370. el.setAttribute("id", "appGUI");
  371. document.body.appendChild(el);
  372. _cellWidgets.reflectorGUI();
  373. }
  374. HandleWorldAbout(ctx) {
  375. console.log("about world");
  376. let userAlias = ctx.params.user;
  377. let worldName = ctx.params.space;
  378. let saveName = ctx.params.savename;
  379. window._app.hideProgressBar();
  380. window._app.hideUIControl();
  381. if (!_app.indexApp) {
  382. _app.indexApp = new IndexApp;
  383. }
  384. let worldApp = new WorldApp(userAlias, worldName, saveName);
  385. _app.helpers.getUserPub(userAlias).then(res => {
  386. worldApp.makeGUI(res)
  387. })
  388. }
  389. HandleSetupIndex() {
  390. window._app.hideProgressBar();
  391. window._app.hideUIControl();
  392. _LCSDB.on('auth',
  393. function (ack) {
  394. let el = document.createElement("div");
  395. el.setAttribute("id", "admin");
  396. document.body.appendChild(el);
  397. if (_LCSDB.user().is) {
  398. let adminComponents = [];
  399. document.querySelector("#admin").$cell({
  400. $cell: true,
  401. id: 'admin',
  402. $type: "div",
  403. $components: adminComponents,
  404. $update: function () {
  405. this.$components = adminComponents
  406. }
  407. });
  408. document.querySelector("#admin").$update();
  409. if (_LCSDB.user().is) {
  410. let loadEmpty = {
  411. $cell: true,
  412. $components: [
  413. {
  414. $type: "p",
  415. class: "mdc-typography--headline5",
  416. $text: "Initialize empty World proto"
  417. },
  418. {
  419. $type: "button",
  420. id: "loadDefaults",
  421. class: "mdc-button mdc-button--raised",
  422. $text: "Init empty world",
  423. onclick: function (e) {
  424. console.log("admin action");
  425. window._app.loadEmptyDefaultProto();
  426. }
  427. }
  428. ]
  429. }
  430. let loadDefaults = {
  431. $cell: true,
  432. _replaceSwitch: null,
  433. $components: [
  434. {
  435. $type: "p",
  436. class: "mdc-typography--headline5",
  437. $text: "Load Sample Worlds protos from server (optional)"
  438. },
  439. {
  440. $type: "button",
  441. id: "loadDefaults",
  442. class: "mdc-button mdc-button--raised",
  443. $text: "Load default worlds (from server)",
  444. onclick: function (e) {
  445. console.log("admin action");
  446. let forceReplace = this._replaceSwitch.checked;
  447. //console.log(forceReplace);
  448. window._app.loadWorldsDefaults(forceReplace);
  449. }
  450. },
  451. {
  452. $type: 'p'
  453. },
  454. _cellWidgets.switch({
  455. 'id': 'forceReplace',
  456. 'init': function () {
  457. this._switch = new mdc.switchControl.MDCSwitch(this);
  458. this._replaceSwitch = this._switch;
  459. this._switch.checked = false;
  460. }
  461. }
  462. ),
  463. {
  464. $type: 'label',
  465. for: 'input-forceReplace',
  466. $text: 'Force replace'
  467. }
  468. ]
  469. }
  470. let loadDefaultsProxy = {
  471. $cell: true,
  472. $components: [
  473. {
  474. $type: "p",
  475. class: "mdc-typography--headline5",
  476. $text: "Load VWF & A-Frame default components"
  477. },
  478. {
  479. $type: "button",
  480. class: "mdc-button mdc-button--raised",
  481. $text: "Load defaults Proxy",
  482. onclick: async function (e) {
  483. console.log("admin action");
  484. await window._app.loadProxyDefaults();
  485. }
  486. }
  487. ]
  488. }
  489. adminComponents.push(loadDefaultsProxy, loadEmpty, loadDefaults);
  490. document.querySelector("#admin").$update();
  491. }
  492. }
  493. })
  494. }
  495. //TODO: profile
  496. HandleUserIndex(ctx) {
  497. console.log("USER INDEX");
  498. window._app.hideProgressBar();
  499. window._app.hideUIControl();
  500. import('/web/header.js').then(res => {
  501. let gui = new res.Header();
  502. gui.init();
  503. })
  504. _LCSDB.on('auth',
  505. async function (ack) {
  506. if (ack.sea.pub) {
  507. _app.helpers.checkUserCollision();
  508. let alias = _LCSDB.user().is.alias;
  509. let pub = _LCSDB.user().is.pub;
  510. document.querySelector("#profile")._refresh(
  511. {
  512. user: {
  513. alias: alias,
  514. pub: pub
  515. }
  516. }
  517. );
  518. }
  519. })
  520. let el = document.createElement("div");
  521. el.setAttribute("id", "userProfile");
  522. document.body.appendChild(el);
  523. let dragDropWorldsArea = {
  524. $cell: true,
  525. $type: 'div',
  526. id: "ddWorlds",
  527. class: 'dragdropArea',
  528. _ddText: '',
  529. _refresh: function (aText) {
  530. this._ddText = aText;
  531. },
  532. $init: function () {
  533. console.log('init d&d area for worlds protos');
  534. this._refresh('Drag & Drop a folder with world files here...');
  535. let self = this;
  536. DragDrop("#ddWorlds",
  537. {
  538. onDrop: function (files, pos, fileList, directories) {
  539. console.log('onDrop: ' + files.length + ' files at ' + pos.x + ', ' + pos.y);
  540. //let worldsObj = {};
  541. let worlds = _LCSDB.user().get('worlds');
  542. files.forEach(function (file) {
  543. let world = {};
  544. if ((file.name.indexOf('.yaml') !== -1) ||
  545. (file.type == "text/javascript") ||
  546. (file.type == "text/html") ||
  547. (file.type == "application/json")) {
  548. console.log('- ' + file.name + ' (' + file.size + ') (' + file.type + ')');
  549. // convert the file to a Buffer that we can use!
  550. const reader = new FileReader()
  551. reader.addEventListener('load', e => {
  552. // e.target.result is an ArrayBuffer
  553. const arr = new Uint8Array(e.target.result)
  554. const fileBuffer = new buffer.Buffer(arr);
  555. const fileSource = fileBuffer.toString();
  556. // do something with the buffer!
  557. var entryName = file.fullPath.slice(1).split(".").join("_");
  558. let worldName = entryName.split("/")[0];
  559. let userPub = _LCSDB.user().is.pub;
  560. //let modified = new Date().valueOf();
  561. let created = new Date().valueOf();
  562. world[worldName] = {
  563. 'parent': '-',
  564. 'owner': userPub,
  565. 'featured': true,
  566. 'published': true,
  567. 'proxy': userPub,
  568. 'created': created,
  569. 'modified': created
  570. }
  571. let entry = entryName.replace(worldName + '/', "");
  572. world[worldName][entry] = fileSource;
  573. console.log(world);
  574. worlds.put(world);
  575. })
  576. reader.addEventListener('error', err => {
  577. console.error('FileReader error' + err)
  578. })
  579. reader.readAsArrayBuffer(file)
  580. }
  581. })
  582. //console.log('Worlds', worldsObj);
  583. console.log('files array', files)
  584. console.log('FileList object', fileList)
  585. console.log('directories array', directories)
  586. self._refresh(directories.map(el => { return el.name }).toString());
  587. },
  588. onDropText: function (text, pos) {
  589. console.log('onDropText: ' + text + ' at ' + pos.x + ', ' + pos.y)
  590. }
  591. }
  592. )
  593. },
  594. $update: function () {
  595. this.$components = [
  596. {
  597. $type: "h5",
  598. class: "mdc-typography--headline5",
  599. $text: this._ddText
  600. }
  601. ]
  602. }
  603. }
  604. let dragDropProxyArea = {
  605. $cell: true,
  606. $type: 'div',
  607. id: "ddProxy",
  608. class: 'dragdropArea',
  609. _ddText: '',
  610. _refresh: function (aText) {
  611. this._ddText = aText;
  612. },
  613. $init: function () {
  614. console.log('init d&d area for proxy files');
  615. this._refresh('Drag & Drop a folder with proxy files here...');
  616. let self = this;
  617. DragDrop("#ddProxy",
  618. {
  619. onDrop: function (files, pos, fileList, directories) {
  620. console.log('onDrop: ' + files.length + ' files at ' + pos.x + ', ' + pos.y);
  621. //let worldsObj = {};
  622. let proxy = _LCSDB.user().get('proxy').put({ id: 'proxy' });
  623. files.forEach(function (file) {
  624. let proxyObj = {};
  625. if ((file.name.indexOf('.yaml') !== -1) ||
  626. (file.type == "text/javascript") ||
  627. (file.type == "text/html") ||
  628. (file.type == "application/json")) {
  629. console.log('- ' + file.name + ' (' + file.size + ') (' + file.type + ')');
  630. // convert the file to a Buffer that we can use!
  631. const reader = new FileReader()
  632. reader.addEventListener('load', e => {
  633. // e.target.result is an ArrayBuffer
  634. const arr = new Uint8Array(e.target.result)
  635. const fileBuffer = new buffer.Buffer(arr);
  636. const fileSource = fileBuffer.toString();
  637. // do something with the buffer!
  638. var entryName = file.fullPath.slice(1).split(".").join("_");
  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 userProfile = {
  708. $type: 'div',
  709. id: "profile",
  710. _user: {},
  711. _refresh: function (data) {
  712. this._user = data.user;
  713. },
  714. $init: function () {
  715. this._user = { alias: "", pub: "" }
  716. },
  717. $update: function () {
  718. if (_LCSDB.user().is) {
  719. this.$components = [
  720. {
  721. $type: "div",
  722. class: "mdc-layout-grid",
  723. $components: [
  724. {
  725. $type: "div",
  726. class: "mdc-layout-grid__inner",
  727. $components: [
  728. {
  729. $type: "div",
  730. class: "mdc-layout-grid__cell mdc-layout-grid__cell--span-12",
  731. $components: [
  732. {
  733. $type: "h5",
  734. class: "mdc-typography--headline4 unselectable",
  735. $text: "User alias: " + this._user.alias //"Profile for: " + this.db.user().is.alias
  736. },
  737. {
  738. $type: "h5",
  739. class: "mdc-typography--headline5 unselectable",
  740. $text: "User public key: " + this._user.pub//"Profile for: " + this.db.user().is.alias
  741. },
  742. ]
  743. },
  744. {
  745. $type: "div",
  746. class: "mdc-layout-grid__cell mdc-layout-grid__cell--span-12",
  747. $components: [
  748. {
  749. $type: "h3",
  750. class: "mdc-typography",
  751. $text: 'Load my world\'s protos:' //"Profile for: " + this.db.user().is.alias
  752. },
  753. dragDropWorldsArea, _app.widgets.emptyDiv,
  754. {
  755. $text: 'or'
  756. },
  757. _app.widgets.p,
  758. loadEmpty
  759. ]
  760. },
  761. {
  762. $type: "div",
  763. class: "mdc-layout-grid__cell mdc-layout-grid__cell--span-12",
  764. $components: [
  765. {
  766. $type: "h3",
  767. class: "mdc-typography",
  768. $text: 'Load proxy files:' //"Profile for: " + this.db.user().is.alias
  769. },
  770. dragDropProxyArea,
  771. _app.widgets.emptyDiv,
  772. {
  773. $text: 'or'
  774. },
  775. _app.widgets.p,
  776. loadDefaultsProxy
  777. ]
  778. }
  779. ]
  780. }
  781. ]
  782. }
  783. ]
  784. } else {
  785. this.$components = [
  786. {
  787. $type: "h3",
  788. class: "mdc-typography--headline3",
  789. $text: "user is not signed in..." //"Profile for: " + this.db.user().is.alias
  790. },
  791. _app.widgets.divider
  792. ]
  793. }
  794. }
  795. }
  796. document.querySelector("#userProfile").$cell({
  797. $cell: true,
  798. $type: "div",
  799. $components: [userProfile]
  800. })
  801. }
  802. HandleUserWorlds(ctx) {
  803. console.log("USER WORLDS INDEX");
  804. console.log(ctx.params);
  805. let user = ctx.params.user;
  806. page.redirect('/' + user + '/worlds/protos');
  807. }
  808. HandleFileEdit(ctx) {
  809. console.log("USER WORLD FILE EDIT");
  810. let user = ctx.params.user;
  811. let worldName = ctx.params.name;
  812. let fileOriginal = ctx.params.file;
  813. let type = ctx.params.type;
  814. window._app.hideProgressBar();
  815. window._app.hideUIControl();
  816. _LCSDB.on('auth',
  817. async function (ack) {
  818. if (_LCSDB.user().is) {
  819. _app.helpers.checkUserCollision();
  820. if (_LCSDB.user().is.alias == user) {
  821. var worldType = 'worlds';
  822. var file = fileOriginal;
  823. if (type == 'state') {
  824. worldType = 'documents';
  825. file = _app.helpers.replaceSubStringALL(fileOriginal, "~", '/');
  826. }
  827. _LCSDB.user().get(worldType).get(worldName).get(file).load(worldFile => {
  828. if (worldFile) {
  829. var source = worldFile;
  830. if (type == 'state') {
  831. if (!file.includes('_info_vwf_json')) {
  832. source = worldFile.jsonState;
  833. var saveName = worldFile.filename;
  834. }
  835. }
  836. //console.log(source);
  837. //var source = (typeof(sourceToEdit) =="object") ? JSON.stringify(sourceToEdit): sourceToEdit;
  838. if (file.includes('_json') && (typeof source !== 'object')) {
  839. source = (typeof JSON.parse(source) == 'object') ? JSON.stringify(JSON.parse(source), null, '\t') : source
  840. //source = source;//JSON.stringify(source, null, '\t');
  841. } else if (typeof source == 'object') {
  842. source = JSON.stringify(source, null, '\t')
  843. }
  844. let el = document.createElement("div");
  845. el.setAttribute("id", "worldFILE");
  846. document.body.appendChild(el);
  847. var saveGUI = {};
  848. if (type == 'proto' || file.includes('_info_vwf_json')) {
  849. saveGUI = {
  850. $type: "button",
  851. class: "mdc-button mdc-button--raised",
  852. $text: "Save",
  853. onclick: async function (e) {
  854. console.log("save new info");
  855. let editor = document.querySelector("#aceEditor").env.editor;
  856. let newInfo = editor.getValue();
  857. _LCSDB.user().get(worldType).get(worldName).get(file).put(newInfo, function (res) {
  858. if (res) {
  859. let noty = new Noty({
  860. text: 'Saved!',
  861. timeout: 2000,
  862. theme: 'mint',
  863. layout: 'bottomRight',
  864. type: 'success'
  865. });
  866. noty.show();
  867. // let modified = new Date().valueOf();
  868. // _LCSDB.user().get(worldType).get(worldName).get(file).get('modified').put(modified);
  869. }
  870. })
  871. }
  872. }
  873. }
  874. if (type == 'state' && !file.includes('_info_vwf_json')) {
  875. saveGUI =
  876. {
  877. $type: "div",
  878. class: "",
  879. $components: [
  880. {
  881. $type: "button",
  882. class: "mdc-button mdc-button--raised",
  883. $text: "Replace state",
  884. onclick: async function (e) {
  885. console.log("fix state");
  886. let editor = document.querySelector("#aceEditor").env.editor;
  887. let newInfo = editor.getValue();
  888. let fixedState = newInfo; //_app.fixSaveState(newInfo, worldName, oldProtoName);
  889. //let userPub = (await _LCSDB.get('users').get(user).get('pub').promOnce()).data;
  890. let userPub = await _app.helpers.getUserPub(user);
  891. let revs = await _app.lookupSaveRevisions(worldName, saveName, userPub);
  892. let lastRevision = revs.sort()[0];
  893. var newFile = file.replace('savestate_', 'savestate_' + lastRevision.toString());
  894. _LCSDB.user().get(worldType).get(worldName).get(file).get('revs').get(newFile).get('jsonState').put(fixedState);
  895. _LCSDB.user().get(worldType).get(worldName).get(file).get('jsonState').put(fixedState, function (res) {
  896. if (res) {
  897. let noty = new Noty({
  898. text: 'Repalced!',
  899. timeout: 2000,
  900. theme: 'mint',
  901. layout: 'bottomRight',
  902. type: 'success'
  903. });
  904. noty.show();
  905. // let modified = new Date().valueOf();
  906. // _LCSDB.user().get(worldType).get(worldName).get(file).get('modified').put(modified);
  907. }
  908. })
  909. }
  910. }
  911. ]
  912. }
  913. }
  914. let aceEditorCell = {
  915. $type: "div",
  916. $components: [
  917. {
  918. class: "aceEditor",
  919. id: "aceEditor",
  920. //style: "width:1200px; height: 800px",
  921. $type: "div",
  922. $text: source,
  923. $init: function () {
  924. var mode = "ace/mode/json";
  925. if (file.includes('_yaml'))
  926. mode = "ace/mode/yaml"
  927. if (file.includes('_js'))
  928. mode = "ace/mode/javascript"
  929. var editor = ace.edit("aceEditor");
  930. editor.setTheme("ace/theme/monokai");
  931. editor.setFontSize(16);
  932. editor.getSession().setMode(mode);
  933. editor.setOptions({
  934. maxLines: Infinity
  935. });
  936. editor.session.setUseWrapMode(true);
  937. }
  938. },
  939. saveGUI,
  940. {
  941. $type: "button",
  942. class: "mdc-button mdc-button--raised",
  943. $text: "Close",
  944. onclick: function (e) {
  945. console.log("close");
  946. //window.location.pathname = "/" + user + '/' + worldName + '/about'
  947. window.history.back();
  948. // if (type == "proto")
  949. // window.location.pathname = "/" + user + '/' + worldName + '/about'
  950. // if (type == "state")
  951. // window.location.pathname = "/" + user + '/' + worldName + '/about'
  952. }
  953. }
  954. ]
  955. }
  956. document.querySelector("#worldFILE").$cell({
  957. $cell: true,
  958. $type: "div",
  959. $components: [aceEditorCell
  960. ]
  961. })
  962. }
  963. });
  964. }
  965. }
  966. })
  967. }
  968. HandleUserWorldsWithType(ctx) {
  969. console.log("USER WORLDS INDEX");
  970. console.log(ctx.params);
  971. let user = ctx.params.user;
  972. let type = ctx.params.type;
  973. window._app.hideProgressBar();
  974. window._app.hideUIControl();
  975. if (!_app.indexApp) {
  976. _app.indexApp = new IndexApp;
  977. }
  978. if (type == 'protos') {
  979. _app.indexApp.allWorldsProtosForUser(user)
  980. } else if (type == 'states') {
  981. _app.indexApp.allWorldsStatesForUser(user)
  982. }
  983. }
  984. async generateFrontPage() {
  985. let infoEl = document.createElement("div");
  986. infoEl.setAttribute("id", "indexPage");
  987. let lang = _LangManager.locale;
  988. let infoElHTML = await _app.helpers.getHtmlText('/web/locale/' + lang + '/index.html');
  989. infoEl.innerHTML = infoElHTML;
  990. document.body.appendChild(infoEl);
  991. }
  992. HandleIndex() {
  993. console.log("INDEX");
  994. window._app.hideProgressBar();
  995. window._app.hideUIControl();
  996. (new Promise(res => res(_app.generateFrontPage()))).then(res => {
  997. if (!_app.indexApp) {
  998. _app.indexApp = new IndexApp('index');
  999. }
  1000. })
  1001. // _LCSDB.get('~@app').once(res=>{
  1002. // if (res){
  1003. // _app.indexApp.initWorldsProtosListForUser('app');
  1004. // }
  1005. // })
  1006. //await _app.indexApp.getAppDetailsFromDB();
  1007. }
  1008. HandleNoPage() {
  1009. console.log("no such page")
  1010. }
  1011. //handle parcable requests
  1012. HandleParsableLoadRequest(ctx) {
  1013. let app = window._app;
  1014. console.log(ctx.params);
  1015. //var pathname = ctx.pathname;
  1016. var spaceName = ctx.params.space;
  1017. var saveName = ctx.params.savename;
  1018. let user = ctx.params.user;
  1019. page.redirect('/' + user + '/' + spaceName + '/' + app.helpers.GenerateInstanceID() + '/load/' + saveName);
  1020. }
  1021. HandleParsableLoadRequestWithRev(ctx) {
  1022. let app = window._app;
  1023. console.log(ctx.params);
  1024. //var pathname = ctx.pathname;
  1025. var spaceName = ctx.params.space;
  1026. var saveName = ctx.params.savename;
  1027. var rev = ctx.params.rev;
  1028. let user = ctx.params.user;
  1029. page.redirect('/' + user + '/' + spaceName + '/' + app.helpers.GenerateInstanceID() + '/load/' + saveName + '/' + rev);
  1030. }
  1031. HandleParsableRequestGenID(ctx) {
  1032. let app = window._app;
  1033. console.log(ctx.params);
  1034. let user = ctx.params.user;
  1035. let space = ctx.params.space;
  1036. var pathname = ctx.pathname;
  1037. //await app.setUserPaths(user);
  1038. _app.helpers.getUserPub(user).then(function (res) {
  1039. if (res)
  1040. window._LCS_WORLD_USER = {
  1041. alias: user,
  1042. pub: res
  1043. }
  1044. if (pathname[pathname.length - 1] == '/') {
  1045. pathname = pathname.slice(0, -1)
  1046. }
  1047. let pathToParse = '/' + space; // pathname.replace('/' + user, "");
  1048. let parsedRequest = {
  1049. application: "index.vwf",
  1050. instance: undefined,
  1051. private_path: undefined,
  1052. public_path: pathToParse
  1053. }
  1054. localStorage.setItem('lcs_app', JSON.stringify({ path: parsedRequest }));
  1055. console.log(parsedRequest);
  1056. if ((parsedRequest['instance'] == undefined) && (parsedRequest['private_path'] == undefined) && (parsedRequest['public_path'] !== "/") && (parsedRequest['application'] !== undefined)) {
  1057. //page.redirect(pathname + '/' + app.helpers.GenerateInstanceID());
  1058. window.location.pathname = pathname + '/' + app.helpers.GenerateInstanceID()
  1059. }
  1060. })
  1061. }
  1062. HandleParsableRequestWithID(ctx) {
  1063. let app = window._app;
  1064. console.log(ctx.params);
  1065. var pathname = ctx.pathname;
  1066. let user = ctx.params.user;
  1067. let genID = ctx.params.id;
  1068. let space = ctx.params.space;
  1069. let savename = ctx.params.savename;
  1070. if (pathname[pathname.length - 1] == '/') {
  1071. pathname = pathname.slice(0, -1)
  1072. }
  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. return app.loadAppLibs()
  1082. }).then(res => {
  1083. let pathToParse = '/' + space; //pathname.replace('/' + user, "");
  1084. let parsedRequest = {
  1085. application: "index.vwf",
  1086. instance: genID,
  1087. private_path: undefined,
  1088. public_path: pathToParse
  1089. }
  1090. if (savename) {
  1091. parsedRequest.private_path = 'load/' + savename;
  1092. }
  1093. localStorage.setItem('lcs_app', JSON.stringify({ path: parsedRequest }));
  1094. return parsedRequest
  1095. }).then(pr => {
  1096. let cpath = pr.public_path;
  1097. return new Promise(res => _LCSDB.user(_LCS_WORLD_USER.pub).get('worlds').get(cpath.slice(1)).load(res)) //, { wait: 400 }
  1098. }).then(val => {
  1099. let fileConf = val['index_vwf_config_yaml'];
  1100. vwf.conf = {};
  1101. if (fileConf) {
  1102. let config = YAML.parse(fileConf);
  1103. vwf.conf = config
  1104. }
  1105. let manualSettings = localStorage.getItem('lcs_app_manual_settings');
  1106. if (manualSettings) {
  1107. let manualConf = JSON.parse(manualSettings);
  1108. vwf.conf.model = manualConf.model;
  1109. vwf.conf.view = manualConf.view;
  1110. }
  1111. //check & set default proxy for world
  1112. vwf.proxy = val.proxy ? val.proxy : _LCS_WORLD_USER.pub
  1113. // Try to load all required docs from Gun DB...
  1114. let promises = []
  1115. let worldPromise = new Promise(res => _LCSDB.user(_LCS_WORLD_USER.pub).get('worlds').get(space).load(res));
  1116. promises.push(worldPromise);
  1117. if (savename) {
  1118. let entryPath = 'savestate_/' + space + '/' + savename + '_vwf_json';
  1119. let savePromise = new Promise(res => _LCSDB.user(_LCS_WORLD_USER.pub).get('documents').get(space).path(entryPath).load(res, { wait: 400 }));
  1120. promises.push(savePromise);
  1121. }
  1122. let proxyPromise = new Promise(res => _LCSDB.user(vwf.proxy).get('proxy').load(res, { wait: 400 }));
  1123. promises.push(proxyPromise);
  1124. return Promise.all(promises)
  1125. }).then(res => {
  1126. var userLibraries = { model: {}, view: {} };
  1127. var application;
  1128. vwf.loadConfiguration(application, userLibraries, vwf.conf, compatibilityCheck);
  1129. })
  1130. }
  1131. async loadAppLibs() {
  1132. await loadjs([
  1133. '/vwf/model/aframe/aframe-master.js',
  1134. '/vwf/model/aframe/addon/SkyShader.js',
  1135. '/vwf/model/aframe/addon/BVHLoader.js',
  1136. '/vwf/model/aframe/addon/TransformControls.js',
  1137. '/vwf/model/aframe/addon/THREE.MeshLine.js',
  1138. '/vwf/model/aframe/addon/three/BufferGeometryUtils.js',
  1139. '/vwf/model/aframe/addon/aframe-sun-sky.min.js',
  1140. '/vwf/model/aframe/extras/aframe-extras.loaders.min.js',
  1141. '/vwf/model/aframe/extras/aframe-extras.controls.min.js',
  1142. '/vwf/model/aframe/addon/aframe-teleport-controls.js',
  1143. '/vwf/model/aframe/kframe/aframe-aabb-collider-component.min.js',
  1144. '/vwf/model/aframe/addon/aframe-interpolation.js',
  1145. '/vwf/model/aframe/addon/aframe-components.js'
  1146. //'/vwf/view/arjs/aframe-ar.js' //load in aframe-ar-driver
  1147. ], {
  1148. async: false,
  1149. returnPromise: true
  1150. });
  1151. return loadjs([
  1152. '/lib/compatibilitycheck.js',
  1153. '/vwf/view/webrtc/adapter-latest.js',
  1154. '/lib/draggabilly/draggabilly.pkgd.js',
  1155. '/vwf/model/aframe/addon/virtualgc/nipplejs.js',
  1156. '/lib/lively.vm_standalone.js',
  1157. '/lib/require.js',
  1158. '/lib/crypto.js',
  1159. '/lib/md5.js',
  1160. '/lib/alea.js',
  1161. '/lib/mash.js',
  1162. '/vwf.js'
  1163. ], {
  1164. async: false,
  1165. returnPromise: true
  1166. })
  1167. }
  1168. //get DB application state information for reflector (called from VWF)
  1169. async getApplicationState() {
  1170. let dataJson = JSON.parse(localStorage.getItem('lcs_app'));
  1171. if (dataJson) {
  1172. if (!dataJson.path['instance']) return undefined;
  1173. }
  1174. //let userAlias = await _LCS_WORLD_USER.get('alias').once().then();
  1175. // let userPub = await _LCSDB.get('users').get(userAlias).get('pub').once().then();
  1176. //let userPub = _LCS_WORLD_USER.pub;
  1177. let userAlias = _LCS_WORLD_USER.alias;
  1178. let parsedRequest = dataJson.path;
  1179. if (parsedRequest['private_path']) {
  1180. var segments = this.helpers.GenerateSegments(parsedRequest['private_path']);
  1181. if ((segments.length > 1) && (segments[0] == "load")) {
  1182. var potentialRevs = await this.lookupSaveRevisions((parsedRequest['public_path']).slice(1), segments[1]);
  1183. }
  1184. var loadInfo = this.getLoadInformation(dataJson, potentialRevs);
  1185. var saveInfo = await this.loadSaveObject(loadInfo);
  1186. }
  1187. let loadObj = {
  1188. loadInfo: loadInfo ? loadInfo : {},
  1189. path: dataJson.path,
  1190. saveObject: saveInfo,
  1191. user: userAlias
  1192. }
  1193. //dataJson.app = loadObj;
  1194. localStorage.setItem('lcs_app', JSON.stringify(loadObj));
  1195. console.log(loadObj);
  1196. return loadObj
  1197. }
  1198. // LookupSaveRevisions takes the public path and the name of a save, and provides
  1199. // an array of all revisions for that save. (If the save does not exist, this will be
  1200. // an empty array).
  1201. async lookupSaveRevisions(public_path, save_name, userPub) {
  1202. var pub = "";
  1203. if (!_LCS_WORLD_USER) {
  1204. pub = userPub;
  1205. } else {
  1206. pub = _LCS_WORLD_USER.pub
  1207. }
  1208. //let userDB = _LCSDB.user(pub);
  1209. var result = [];
  1210. let docName = 'savestate_/' + public_path + '/' + save_name + '_vwf_json';
  1211. let node = _LCSDB.user(pub).get('documents').get(public_path).get(docName).get('revs');
  1212. let revs = await new Promise(res => node.load(res, { wait: 400 }));
  1213. if (revs) {
  1214. for (const res of Object.values(revs)) {
  1215. if (res)
  1216. result.push(parseInt(res.revision));
  1217. }
  1218. return result
  1219. }
  1220. }
  1221. // GetLoadInformation receives a parsed request {private_path, public_path, instance, application} and returns the
  1222. // details of the save that is designated by the initial request. The details are returned in an object
  1223. // composed of: save_name (name of the save) save_revision (revision of the save), explicit_revision (boolean, true if the request
  1224. // explicitly specified the revision, false if it did not), and application_path (the public_path of the application this is a save for).
  1225. getLoadInformation(response, potentialRevisions) {
  1226. let parsedRequest = response.path;
  1227. let segments = this.helpers.GenerateSegments(parsedRequest['private_path']);
  1228. let result = { 'save_name': undefined, 'save_revision': undefined, 'explicit_revision': undefined, 'application_path': undefined };
  1229. if (potentialRevisions.length > 0) {
  1230. result['save_name'] = segments[1];
  1231. if (segments.length > 2) {
  1232. var requestedRevision = parseInt(segments[2]);
  1233. if (requestedRevision) {
  1234. if (potentialRevisions.indexOf(requestedRevision) > -1) {
  1235. result['save_revision'] = requestedRevision;
  1236. result['explicit_revision'] = true;
  1237. result['application_path'] = parsedRequest['public_path'];
  1238. }
  1239. }
  1240. }
  1241. if (result['explicit_revision'] == undefined) {
  1242. result['explicit_revision'] = false;
  1243. potentialRevisions.sort();
  1244. result['save_revision'] = potentialRevisions.pop();
  1245. result['application_path'] = parsedRequest['public_path'];
  1246. }
  1247. }
  1248. return result;
  1249. }
  1250. async loadSaveObject(loadInfo) {
  1251. //let objName = loadInfo[ 'save_name' ] +'/'+ "savestate_" + loadInfo[ 'save_revision' ];
  1252. //let userDB = _LCSDB.user(_LCS_WORLD_USER.pub);
  1253. if (!loadInfo.save_name) {
  1254. return undefined
  1255. }
  1256. let objName = "savestate_" + loadInfo['application_path'] + '/' + loadInfo['save_name'] + '_vwf_json';
  1257. let objNameRev = "savestate_" + loadInfo['save_revision'] + loadInfo['application_path'] + '/' + loadInfo['save_name'] + '_vwf_json';
  1258. // if(loadInfo[ 'save_revision' ]){
  1259. // }
  1260. let worldName = this.helpers.appPath //loadInfo[ 'application_path' ].slice(1);
  1261. let dbNode = _LCSDB.user(_LCS_WORLD_USER.pub).get('documents').get(worldName).get(objName).get('revs').get(objNameRev);
  1262. let saveObject = await new Promise(res => dbNode.load(res, { wait: 300 }));
  1263. //(await userDB.get('documents').get(worldName).get(objName).get('revs').get(objNameRev).promOnce()).data;
  1264. var saveInfo = null;
  1265. if (saveObject) {
  1266. saveInfo = (typeof (saveObject.jsonState) == 'object') ? saveObject.jsonState : JSON.parse(saveObject.jsonState);
  1267. }
  1268. //typeof(saveObject == 'object')
  1269. return saveInfo;
  1270. }
  1271. // GetSaveInformation is a helper function that takes the application_path (/path/to/application).
  1272. // It returns an array of all saves found for that
  1273. // application (including separate entries for individual revisions of saves ).
  1274. async getSaveInformation(application_path, userPUB) {
  1275. var result = [];
  1276. let user = _LCSDB.user(userPUB);
  1277. var docName = application_path.slice(1);
  1278. let potentialSaveNames = (await user.get('documents').get(docName).promOnce()).data;
  1279. if (potentialSaveNames) {
  1280. for (const res of Object.keys(potentialSaveNames)) {
  1281. if (res !== '_') {
  1282. let el = (await user.get('documents').path(docName).get(res).promOnce()).data;
  1283. let revisionList = await this.lookupSaveRevisions(application_path.slice(1), el.filename);
  1284. var latestsave = true;
  1285. revisionList.sort();
  1286. while (revisionList.length > 0) {
  1287. var newEntry = {};
  1288. newEntry['applicationpath'] = application_path;
  1289. newEntry['savename'] = el.filename;
  1290. newEntry['revision'] = revisionList.pop().toString();
  1291. newEntry['latestsave'] = latestsave;
  1292. if (latestsave) {
  1293. newEntry['url'] = this.helpers.JoinPath(window.location.origin, application_path, "load", el.filename + "/");
  1294. }
  1295. else {
  1296. newEntry['url'] = this.helpers.JoinPath(window.location.origin, application_path, "load", el.filename + "/", newEntry['revision'] + "/");
  1297. }
  1298. latestsave = false;
  1299. result.push(newEntry);
  1300. }
  1301. }
  1302. }
  1303. }
  1304. return result;
  1305. }
  1306. async getProtoWorldFiles(userPub, worldName, date) {
  1307. return (new Promise(res => _LCSDB.user(userPub).get('worlds').get(worldName).once(res))).then(res => {
  1308. let worldFiles = Object.entries(res).filter(el => (el[0].includes('_json')) || (el[0].includes('_yaml')) || (el[0].includes('_html')) || (el[0].includes('_js')))
  1309. .filter(el => (el[0] !== 'info_json'));
  1310. console.log(worldFiles);
  1311. return worldFiles
  1312. });
  1313. }
  1314. async cloneWorldPrototype(worldName, userName, newWorldName, stateFileName) {
  1315. let self = this;
  1316. _app.showProgressBar();
  1317. let userPub = await _app.helpers.getUserPub(userName);
  1318. let newOwner = _LCSDB.user().is.pub;
  1319. let myWorlds = (await _LCSDB.user(newOwner).get('worlds').promOnce()).data;
  1320. //if (!myWorlds) _LCSDB.user(newOwner).get('worlds').put({});
  1321. _LCSDB.user(newOwner).get('worlds').not(res => {
  1322. _LCSDB.user(newOwner).get('worlds').put({});
  1323. })
  1324. if (myWorlds) {
  1325. let checkExist = Object.keys(myWorlds).filter(el => el == newWorldName);
  1326. if (newWorldName) {
  1327. if (checkExist.length > 0 && myWorlds[newWorldName]) {
  1328. console.log('already exist!');
  1329. return
  1330. }
  1331. }
  1332. }
  1333. let worldID = window._app.helpers.GenerateInstanceID().toString();
  1334. if (newWorldName) {
  1335. worldID = newWorldName
  1336. }
  1337. //let modified = new Date().valueOf();
  1338. console.log('clone: ' + worldName + 'to: ' + worldID);
  1339. let created = new Date().valueOf();
  1340. await _LCSDB.user(userPub).get('worlds').get(worldName).load(all => {
  1341. let worldObj = Object.assign({}, all);
  1342. worldObj.owner = newOwner;
  1343. worldObj.parent = userName + '/' + worldName;
  1344. worldObj.featured = true
  1345. worldObj.published = true
  1346. worldObj.created = created
  1347. if (!all.proxy) {
  1348. worldObj.proxy = userPub;
  1349. } else {
  1350. worldObj.proxy = all.proxy;
  1351. }
  1352. console.log(worldObj);
  1353. //let myWorlds = await _LCSDB.user(newOwner).get('worlds').once().then();
  1354. //let myWorld = _LCSDB.user(newOwner).get('worlds').get(worldID).put({id:worldID});
  1355. let myWorld = _LCSDB.user(newOwner).get('worlds').get(worldID).put({ id: worldID });
  1356. myWorld.put(worldObj, function (res) {
  1357. if (stateFileName) {
  1358. self.saveStateAsFile(stateFileName)
  1359. }
  1360. console.log(res)
  1361. }); //.get(worldID) let myWorld =
  1362. _app.hideProgressBar();
  1363. console.log('CLONED!!!');
  1364. let appEl = document.createElement("div");
  1365. appEl.setAttribute("id", 'cloneLink');
  1366. let entry = document.querySelector('#worldActionsGUI');
  1367. if (entry) {
  1368. entry.appendChild(appEl);
  1369. document.querySelector("#cloneLink").$cell({
  1370. id: 'cloneLink',
  1371. $cell: true,
  1372. $type: "div",
  1373. $components: [
  1374. {
  1375. $type: "a",
  1376. class: "mdc-button mdc-button--raised mdc-card__action",
  1377. $text: "Go to new cloned World!",
  1378. onclick: function (e) {
  1379. let myName = _LCSDB.user().is.alias;
  1380. window.location.pathname = '/' + myName + '/' + worldID + '/about'
  1381. }
  1382. }
  1383. ]
  1384. })
  1385. }
  1386. }, { wait: 500 }).then();
  1387. }
  1388. async cloneWorldState(filename) {
  1389. let myWorldProtos = (await _LCSDB.user().get('worlds').promOnce()).data;
  1390. let userName = this.helpers.worldUser;
  1391. // let users = await _LCSDB.get('users').then();
  1392. // let userPub = (await _LCSDB.get('users').get(userName).get('pub').promOnce()).data;
  1393. let userPub = await _app.helpers.getUserPub(userName);
  1394. let protoUserRoot = this.helpers.getRoot(true).root;
  1395. //let myName = this.db.user().is.alias;
  1396. //let proto = Object.keys(myWorldProtos).filter(el => el == protoUserRoot);
  1397. var protosKeys = [];
  1398. if (myWorldProtos)
  1399. protosKeys = Object.keys(myWorldProtos);
  1400. if (protosKeys.includes(protoUserRoot) && myWorldProtos[protoUserRoot]) {
  1401. let userProtoFiles = await this.getProtoWorldFiles(userPub, protoUserRoot);
  1402. let myProtoFiles = await this.getProtoWorldFiles(_LCSDB.user().is.pub, protoUserRoot);
  1403. let hashUP = await this.helpers.sha256(JSON.stringify(userProtoFiles));
  1404. let hashMP = await this.helpers.sha256(JSON.stringify(myProtoFiles));
  1405. if (hashUP == hashMP) {
  1406. this.saveStateAsFile(filename);
  1407. } else {
  1408. let noty = new Noty({
  1409. text: 'world prototype is modified.. could not clone world state',
  1410. timeout: 2000,
  1411. theme: 'mint',
  1412. layout: 'bottomRight',
  1413. type: 'error'
  1414. });
  1415. noty.show();
  1416. }
  1417. } else {
  1418. await this.cloneWorldPrototype(protoUserRoot, userName, protoUserRoot, filename);
  1419. //this.saveStateAsFile(filename);
  1420. }
  1421. }
  1422. //TODO: refactor and config save
  1423. async saveStateAsFile(filename, otherProto) // invoke with the view as "this"
  1424. {
  1425. console.log("Saving: " + filename);
  1426. //var clients = this.nodes["http://vwf.example.com/clients.vwf"];
  1427. // Save State Information
  1428. var state = vwf.getState();
  1429. state.nodes[0].children = {};
  1430. var timestamp = state["queue"].time;
  1431. timestamp = Math.round(timestamp * 1000);
  1432. let jsonValuePure = _app.helpers.replaceFloatArraysInNodeDef(state);
  1433. //remove all Ohm generated grammarsfrom state
  1434. let jsonValue = _app.helpers.removeGrammarObj(jsonValuePure);
  1435. var jsonState = JSON.stringify(jsonValue, null, '\t'); //JSON.stringify(jsonValue);
  1436. let rootPath = this.helpers.getRoot(true);
  1437. var inst = rootPath.inst;
  1438. if (filename == '') filename = inst;
  1439. //if (root.indexOf('.vwf') != -1) root = root.substring(0, root.lastIndexOf('/'));
  1440. var root = rootPath.root;
  1441. var json = jsonState;
  1442. if (otherProto) {
  1443. console.log('need to modify state...');
  1444. json = this.helpers.replaceSubStringALL(jsonState, '/' + root + '/', '/' + otherProto + '/');//jsonState.replace(('/' + root + '/'), ('/' + otherProto +'/') );
  1445. root = otherProto;
  1446. console.log(json);
  1447. }
  1448. //var documents = this.db.user().get('documents');
  1449. _LCSDB.user().get('documents').not(res => {
  1450. _LCSDB.user().get('documents').put({ id: 'documents' })
  1451. })
  1452. var saveRevision = new Date().valueOf();
  1453. var stateForStore = {
  1454. "root": root,
  1455. "filename": filename,
  1456. "inst": inst,
  1457. "timestamp": timestamp,
  1458. "extension": ".vwf.json",
  1459. "jsonState": json,
  1460. "publish": true
  1461. };
  1462. let rev = JSON.stringify(saveRevision);
  1463. var docNameRev = 'savestate_' + rev + '/' + root + '/' + filename + '_vwf_json';
  1464. let stateWithRev = Object.assign({}, stateForStore);
  1465. stateWithRev.revs = { [docNameRev]: stateForStore };
  1466. stateWithRev.revs[docNameRev].revision = saveRevision;
  1467. //let objName = loadInfo[ 'save_name' ] +'/'+ "savestate_" + loadInfo[ 'save_revision' ];
  1468. // "savestate_" + loadInfo[ 'save_revision' ] + '/' + loadInfo[ 'save_name' ] + '_vwf_json'
  1469. var docName = 'savestate_/' + root + '/' + filename + '_vwf_json';
  1470. let myNewWorldState = _LCSDB.user().get('documents').get(root).get(docName).put({ 'id': docName });
  1471. //_LCSDB.user().get('documents').get(root).get(docName).put(stateWithRev, function(res) {
  1472. myNewWorldState.put(stateWithRev, function (res) {
  1473. if (res) {
  1474. let noty = new Noty({
  1475. text: 'Saved to ' + docName,
  1476. timeout: 2000,
  1477. theme: 'mint',
  1478. layout: 'bottomRight',
  1479. type: 'success'
  1480. });
  1481. noty.show();
  1482. }
  1483. });
  1484. // let docInfo = await _LCSDB.user().get('worlds').get(root).get('info_json').get('file').then();
  1485. _LCSDB.user().get('worlds').get(root).get('info_json').once(function (file) {
  1486. if (file) {
  1487. let fileData = (typeof file == 'object') ? JSON.stringify(file) : file;
  1488. let docInfoName = 'savestate_/' + root + '/' + filename + '_info_vwf_json';
  1489. _LCSDB.user().get('documents').get(root).get(docInfoName).put(fileData);
  1490. }
  1491. });
  1492. // // Save Config Information
  1493. // var config = { "info": {}, "model": {}, "view": {} };
  1494. // // Save browser title
  1495. // config["info"]["title"] = document.title//$('title').html();
  1496. // // Save model drivers
  1497. // Object.keys(vwf_view.kernel.kernel.models).forEach(function (modelDriver) {
  1498. // if (modelDriver.indexOf('vwf/model/') != -1) config["model"][modelDriver] = "";
  1499. // });
  1500. // // If neither glge or threejs model drivers are defined, specify nodriver
  1501. // if (config["model"]["vwf/model/glge"] === undefined && config["model"]["vwf/model/threejs"] === undefined) config["model"]["nodriver"] = "";
  1502. // // Save view drivers and associated parameters, if any
  1503. // Object.keys(vwf_view.kernel.kernel.views).forEach(function (viewDriver) {
  1504. // if (viewDriver.indexOf('vwf/view/') != -1) {
  1505. // if (vwf_view.kernel.kernel.views[viewDriver].parameters) {
  1506. // config["view"][viewDriver] = vwf_view.kernel.kernel.views[viewDriver].parameters;
  1507. // }
  1508. // else config["view"][viewDriver] = "";
  1509. // }
  1510. // });
  1511. // //var jsonConfig = $.encoder.encodeForURL(JSON.stringify(config));
  1512. // var jsonConfig = JSON.stringify(config);
  1513. // let configStateForStore = {
  1514. // "root": root,
  1515. // "filename": filename,
  1516. // "inst": inst,
  1517. // "timestamp": timestamp,
  1518. // "extension": "config.vwf.json",
  1519. // "jsonState": jsonConfig
  1520. // };
  1521. //let objName = loadInfo[ 'save_name' ] +'/'+ "savestate_" + loadInfo[ 'save_revision' ];
  1522. // "savestate_" + loadInfo[ 'save_revision' ] + '/' + loadInfo[ 'save_name' ] + '_vwf_json'
  1523. // let configName = 'savestate_/' + root + '/' + filename + '_config_vwf_json';
  1524. // let documentSaveConfigState = this.db.user().get(configName).put(configStateForStore);
  1525. // //documents.path(root).set(documentSaveConfigState);
  1526. // let configNameRev = 'savestate_' + saveRevision.toString() + '/' + root + '/' + filename + '_config_vwf_json';
  1527. // this.db.user().get(configNameRev).put(configStateForStore);
  1528. // this.db.user().get(configNameRev).path("revision").put(saveRevision);
  1529. //documentSaveConfigState.path('revs').set(documentSaveStateRevision);
  1530. // Save config file to server
  1531. // var xhrConfig = new XMLHttpRequest();
  1532. // xhrConfig.open("POST", "/" + root + "/save/" + filename, true);
  1533. // xhrConfig.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  1534. // xhrConfig.send("root=" + root + "/" + filename + "&filename=saveState&inst=" + inst + "&timestamp=" + timestamp + "&extension=.vwf.config.json" + "&jsonState=" + jsonConfig);
  1535. }
  1536. fixSaveState(jsonState, otherProto, oldProtoName) {
  1537. console.log('fix proto in state...');
  1538. let json = this.helpers.replaceSubStringALL(jsonState, '/' + oldProtoName + '/', '/' + otherProto + '/');//jsonState.replace(('/' + root + '/'), ('/' + otherProto +'/') );
  1539. console.log(json);
  1540. return json
  1541. }
  1542. // LoadSavedState
  1543. async loadSavedState(filename, applicationpath, revision) {
  1544. console.log("Loading: " + filename);
  1545. let userDB = _LCSDB.user(_LCS_WORLD_USER.pub);
  1546. let userName = (await userDB.get('alias').promOnce()).data;
  1547. if (revision) {
  1548. window.location.pathname = '/' + userName + applicationpath + '/load/' + filename + '/' + revision + '/';
  1549. }
  1550. else { // applicationpath + "/" + inst + '/load/' + filename + '/';
  1551. window.location.pathname = '/' + userName + applicationpath + '/load/' + filename + '/';
  1552. }
  1553. }
  1554. hideUIControl() {
  1555. let el = document.getElementById("ui-controls");
  1556. if (el) {
  1557. el.classList.remove("visible");
  1558. el.classList.add("not-visible");
  1559. }
  1560. }
  1561. showUIControl() {
  1562. let el = document.getElementById("ui-controls");
  1563. if (el) {
  1564. el.classList.remove("not-visible");
  1565. el.classList.add("visible");
  1566. }
  1567. }
  1568. hideProgressBar() {
  1569. var progressbar = document.getElementById("load-progressbar");
  1570. if (progressbar) {
  1571. progressbar.classList.remove("visible");
  1572. progressbar.classList.remove("mdc-linear-progress--indeterminate");
  1573. progressbar.classList.add("not-visible");
  1574. progressbar.classList.add("mdc-linear-progress--closed");
  1575. }
  1576. }
  1577. showProgressBar() {
  1578. let progressbar = document.getElementById("load-progressbar");
  1579. if (progressbar) {
  1580. progressbar.classList.remove("not-visible");
  1581. progressbar.classList.remove("mdc-linear-progress--closed");
  1582. progressbar.classList.add("visible");
  1583. progressbar.classList.add("mdc-linear-progress--indeterminate");
  1584. }
  1585. }
  1586. // SUPPORT of DELETE USER WORLDS & SAVE STATES (experimental)
  1587. // TODO: manual garbage collection
  1588. async deleteWorldState(worldName, stateName) {
  1589. //let pathName = 'savestate_/' + worldName+ '/' + this._worldName.stateName + '_info_vwf_json';
  1590. let db = _LCSDB.user();
  1591. let stateEntryInfo = 'savestate_/' + worldName + '/' + stateName + '_info_vwf_json';
  1592. let stateEntry = 'savestate_/' + worldName + '/' + stateName + '_vwf_json';
  1593. db.get('documents').get(worldName).get(stateEntry).get('revs').once().map().once((res, k) => {
  1594. db.get('documents').get(worldName).get(stateEntry).get('revs').get(k).put(null);
  1595. //console.log(k, ' - ', res);
  1596. });
  1597. db.get('documents').get(worldName).get(stateEntryInfo).put(null, res => {
  1598. let id = 'worldCard_' + _LCSDB.user().is.alias + '_' + worldName + '_' + stateName;
  1599. let doc = document.querySelector('#' + id);
  1600. if (doc)
  1601. doc._refresh({})
  1602. });
  1603. db.get('documents').get(worldName).get(stateEntry).get('revs').put(null, res => {
  1604. db.get('documents').get(worldName).get(stateEntry).put(null);
  1605. });
  1606. }
  1607. async deleteWorld(name, type) {
  1608. let self = this;
  1609. if (type == 'proto') {
  1610. let worldName = name;
  1611. //TODO check for states (ask for deleting all states first...)
  1612. //delete states
  1613. let db = _LCSDB.user();
  1614. db.get('documents').once().map((res, k) => { if (k == worldName) return res }).once((res, k) => {
  1615. if (res) {
  1616. let worldStatesInfo = Object.entries(res).filter(el => el[0].includes('_info_vwf_json'));
  1617. worldStatesInfo.map(el => {
  1618. let saveName = el[0].split('/')[2].replace('_info_vwf_json', "");
  1619. console.log(saveName);
  1620. self.deleteWorldState(worldName, saveName)
  1621. //let stateEntry = 'savestate_/' + k + '/' + saveName + '_vwf_json';
  1622. })
  1623. }
  1624. })
  1625. db.get('worlds').get(worldName).put(null, res => {
  1626. let id = 'worldCard_' + _LCSDB.user().is.alias + '_' + worldName + '_';
  1627. let doc = document.querySelector('#' + id);
  1628. if (doc)
  1629. doc._refresh({})
  1630. })
  1631. } else if (type == 'state') {
  1632. let worldName = name.split('/')[0];
  1633. let stateName = name.split('/')[2];
  1634. // let stateEntryInfo = 'savestate_/' + worldName + '/' + stateName + '_info_vwf_json';
  1635. // let stateEntry = 'savestate_/' + worldName + '/' + stateName + '_vwf_json';
  1636. // await this.deleteWorldState(worldName, stateEntryInfo);
  1637. // await this.deleteWorldState(worldName, stateEntry);
  1638. await this.deleteWorldState(worldName, stateName);
  1639. }
  1640. let noty = new Noty({
  1641. text: "World Deleted!",
  1642. timeout: 2000,
  1643. theme: 'mint',
  1644. layout: 'bottomRight',
  1645. type: 'success'
  1646. });
  1647. noty.show();
  1648. }
  1649. parseAppInstancesData(data) {
  1650. let jsonObj = JSON.parse(data);
  1651. var parsed = {};
  1652. let listData = {};
  1653. for (var prop in jsonObj) {
  1654. var name = prop.split('/')[1];
  1655. if (parsed[name]) {
  1656. parsed[name][prop] = jsonObj[prop];
  1657. } else {
  1658. parsed[name] = {};
  1659. parsed[name][prop] = jsonObj[prop];
  1660. }
  1661. }
  1662. //console.log(parsed);
  1663. for (var prop in parsed) {
  1664. var name = prop;
  1665. let obj = Object.entries(parsed[prop]);
  1666. var lists = {};
  1667. obj.forEach(el => {
  1668. if (el[1].loadInfo['save_name']) {
  1669. let saveName = prop + '/load/' + el[1].loadInfo.save_name;
  1670. if (!lists[saveName])
  1671. lists[saveName] = {};
  1672. lists[saveName][el[0]] = el[1]
  1673. } else {
  1674. if (!lists[name])
  1675. lists[name] = {};
  1676. lists[name][el[0]] = el[1]
  1677. }
  1678. });
  1679. // console.log(lists);
  1680. Object.entries(lists).forEach(list => {
  1681. listData[list[0]] = list[1];
  1682. })
  1683. }
  1684. return listData
  1685. // console.log(data)
  1686. }
  1687. async getAllStateWorldsInfoForUser(userAlias, worldName, saveName) {
  1688. //let userPub = await new Promise(res => _LCSDB.get('users').get(userAlias).get('pub').once(res));
  1689. let userPub = await _app.helpers.getUserPub(userAlias);
  1690. var db = _LCSDB.user(userPub);
  1691. if (_LCSDB.user().is) {
  1692. if (_LCSDB.user().is.alias == userAlias)
  1693. db = _LCSDB.user();
  1694. }
  1695. //let hasDocs = await (new Promise(res => db.get('documents').not(res(false)))).then(res=>{return res});
  1696. let list = await (new Promise(res => db.get('documents').load(res, { wait: 400 })))
  1697. .then(r => {
  1698. if (!worldName) {
  1699. return Promise.all(Object.keys(r).map(k => db.get('documents').get(k).then(res => { return [k, res] })))
  1700. } else {
  1701. return Promise.all([db.get('documents').get(worldName).then(res => { return [worldName, res] })])
  1702. }
  1703. }
  1704. )
  1705. .then(r => Promise.all(Object.keys(r).map(k => {
  1706. let objEl = r[k][1];
  1707. if (objEl) {
  1708. let obj = Object.entries(objEl).filter(el => el[0].includes('_info_vwf_json'));
  1709. if (obj) {
  1710. return { world: r[k][0], states: obj }
  1711. }
  1712. } else {
  1713. return { world: r[k][0], states: [] }
  1714. }
  1715. }
  1716. )
  1717. )).then(r =>
  1718. Promise.all(r.map(k =>
  1719. Promise.all((k.states).map(el => {
  1720. let obj = el[1];
  1721. if (obj) {
  1722. return _LCSDB.get(el[1]['#']).load().then(m => { return { world: k.world, stateName: el[0], stateInfo: m } })
  1723. }
  1724. }
  1725. ))
  1726. ))
  1727. )
  1728. //console.log('All states: ', list)
  1729. let docs = {};
  1730. list.map(el => {
  1731. el.map(el => {
  1732. if (el) {
  1733. let res = el.stateInfo;
  1734. let doc = {};
  1735. if (res && res !== 'null') {
  1736. //if (res.file && res.file !== 'null') {
  1737. let saveName = el.stateName.split('/')[2].replace('_info_vwf_json', "");
  1738. var worldDesc = {};
  1739. if (typeof (res) == 'object') {
  1740. worldDesc = res
  1741. } else {
  1742. worldDesc = JSON.parse(res)
  1743. }
  1744. let root = Object.keys(worldDesc)[0];
  1745. var appInfo = worldDesc[root]['en'];
  1746. let langID = localStorage.getItem('krestianstvo_locale');
  1747. if (langID) {
  1748. appInfo = worldDesc[root][langID]
  1749. }
  1750. let settings = worldDesc[root]['settings'];
  1751. doc = {
  1752. 'worldName': el.world + '/load/' + saveName,
  1753. 'created': res.created ? res.created : res.modified,
  1754. 'modified': res.modified,
  1755. 'type': 'saveState',
  1756. 'userAlias': userAlias,
  1757. 'info': appInfo,
  1758. 'settings': settings
  1759. }
  1760. //}
  1761. }
  1762. if (Object.keys(doc).length !== 0) {
  1763. docs[doc.worldName] = doc;
  1764. }
  1765. }
  1766. })
  1767. })
  1768. console.log(docs);
  1769. if (saveName) {
  1770. return docs[saveName]
  1771. }
  1772. return docs
  1773. }
  1774. async getAllProtoWorldsInfoForUser(userAlias, worldName) {
  1775. //let userPub = await new Promise(res => _LCSDB.get('users').get(userAlias).get('pub').once(res));
  1776. let userPub = await _app.helpers.getUserPub(userAlias);
  1777. var db = _LCSDB.user(userPub);
  1778. if (_LCSDB.user().is) {
  1779. if (_LCSDB.user().is.alias == userAlias)
  1780. db = _LCSDB.user();
  1781. }
  1782. let list = await (new Promise(res => db.get('worlds').load(res, { wait: 400 })))
  1783. .then(r => {
  1784. if (!worldName) {
  1785. return Promise.all(Object.keys(r).map(k => db.get('worlds').get(k).then(res => { return [k, res] })))
  1786. } else {
  1787. return Promise.all([db.get('worlds').get(worldName).then(res => { return [worldName, res] })])
  1788. }
  1789. }
  1790. )
  1791. .then(r => Promise.all(Object.keys(r).map(k => {
  1792. let objEl = r[k][1];
  1793. if (objEl) {
  1794. let obj = objEl.info_json;
  1795. if (obj) {
  1796. return _LCSDB.get(obj["#"]).then(res => { return { world: r[k], info: res } })
  1797. }
  1798. }
  1799. }))).then(r => { return r })
  1800. //console.log(list);
  1801. let docs = {};
  1802. list.forEach(el => {
  1803. if (el) {
  1804. let doc = {}
  1805. let res = el.info;
  1806. let index = el.world[0];
  1807. let proxy = el.world[1].proxy;
  1808. if (res && res !== 'null') {
  1809. //if (res.file && res.file !== 'null') {
  1810. //let worldDesc = JSON.parse(res.file);
  1811. var worldDesc = {};
  1812. if (typeof (res) == 'object') {
  1813. worldDesc = res
  1814. } else {
  1815. worldDesc = JSON.parse(res)
  1816. }
  1817. let root = Object.keys(worldDesc)[0];
  1818. var appInfo = worldDesc[root]['en'];
  1819. let langID = localStorage.getItem('krestianstvo_locale');
  1820. if (langID) {
  1821. appInfo = worldDesc[root][langID]
  1822. }
  1823. let settings = worldDesc[root]['settings'];
  1824. doc = {
  1825. 'worldName': index,
  1826. 'created': res.created ? res.created : res.modified,
  1827. 'modified': res.modified,
  1828. 'proxy': proxy,
  1829. 'type': 'proto',
  1830. 'userAlias': userAlias,
  1831. 'info': appInfo,
  1832. 'settings': settings
  1833. }
  1834. //}
  1835. }
  1836. if (Object.keys(doc).length !== 0)
  1837. docs[index] = doc;
  1838. }
  1839. })
  1840. if (worldName) {
  1841. return docs[worldName]
  1842. }
  1843. return docs
  1844. }
  1845. async setNewProxyForWorld(worldName, proxyName) {
  1846. if (_LCSDB.user().is) {
  1847. let newProxy = await _app.helpers.getUserPub(proxyName)
  1848. if (newProxy)
  1849. _LCSDB.user().get('worlds').get(worldName).put({ 'proxy': newProxy })
  1850. }
  1851. }
  1852. }
  1853. export { App }