app.js 70 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399
  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/aframe-sun-sky.min.js',
  1139. '/vwf/model/aframe/extras/aframe-extras.loaders.min.js',
  1140. '/vwf/model/aframe/extras/aframe-extras.controls.min.js',
  1141. '/vwf/model/aframe/kframe/aframe-aabb-collider-component.min.js',
  1142. '/vwf/model/aframe/addon/aframe-interpolation.js',
  1143. '/vwf/model/aframe/addon/aframe-components.js'
  1144. //'/vwf/view/arjs/aframe-ar.js' //load in aframe-ar-driver
  1145. ], {
  1146. async: false,
  1147. returnPromise: true
  1148. });
  1149. return loadjs([
  1150. '/lib/compatibilitycheck.js',
  1151. '/vwf/view/webrtc/adapter-latest.js',
  1152. '/lib/draggabilly/draggabilly.pkgd.js',
  1153. '/vwf/model/aframe/addon/virtualgc/nipplejs.js',
  1154. '/lib/lively.vm_standalone.js',
  1155. '/lib/require.js',
  1156. '/lib/crypto.js',
  1157. '/lib/md5.js',
  1158. '/lib/alea.js',
  1159. '/lib/mash.js',
  1160. '/vwf.js'
  1161. ], {
  1162. async: false,
  1163. returnPromise: true
  1164. })
  1165. }
  1166. //get DB application state information for reflector (called from VWF)
  1167. async getApplicationState() {
  1168. let dataJson = JSON.parse(localStorage.getItem('lcs_app'));
  1169. if (dataJson) {
  1170. if (!dataJson.path['instance']) return undefined;
  1171. }
  1172. //let userAlias = await _LCS_WORLD_USER.get('alias').once().then();
  1173. // let userPub = await _LCSDB.get('users').get(userAlias).get('pub').once().then();
  1174. //let userPub = _LCS_WORLD_USER.pub;
  1175. let userAlias = _LCS_WORLD_USER.alias;
  1176. let parsedRequest = dataJson.path;
  1177. if (parsedRequest['private_path']) {
  1178. var segments = this.helpers.GenerateSegments(parsedRequest['private_path']);
  1179. if ((segments.length > 1) && (segments[0] == "load")) {
  1180. var potentialRevs = await this.lookupSaveRevisions((parsedRequest['public_path']).slice(1), segments[1]);
  1181. }
  1182. var loadInfo = this.getLoadInformation(dataJson, potentialRevs);
  1183. var saveInfo = await this.loadSaveObject(loadInfo);
  1184. }
  1185. let loadObj = {
  1186. loadInfo: loadInfo ? loadInfo : {},
  1187. path: dataJson.path,
  1188. saveObject: saveInfo,
  1189. user: userAlias
  1190. }
  1191. //dataJson.app = loadObj;
  1192. localStorage.setItem('lcs_app', JSON.stringify(loadObj));
  1193. console.log(loadObj);
  1194. return loadObj
  1195. }
  1196. // LookupSaveRevisions takes the public path and the name of a save, and provides
  1197. // an array of all revisions for that save. (If the save does not exist, this will be
  1198. // an empty array).
  1199. async lookupSaveRevisions(public_path, save_name, userPub) {
  1200. var pub = "";
  1201. if (!_LCS_WORLD_USER) {
  1202. pub = userPub;
  1203. } else {
  1204. pub = _LCS_WORLD_USER.pub
  1205. }
  1206. //let userDB = _LCSDB.user(pub);
  1207. var result = [];
  1208. let docName = 'savestate_/' + public_path + '/' + save_name + '_vwf_json';
  1209. let node = _LCSDB.user(pub).get('documents').get(public_path).get(docName).get('revs');
  1210. let revs = await new Promise(res => node.load(res, { wait: 400 }));
  1211. if (revs) {
  1212. for (const res of Object.values(revs)) {
  1213. if (res)
  1214. result.push(parseInt(res.revision));
  1215. }
  1216. return result
  1217. }
  1218. }
  1219. // GetLoadInformation receives a parsed request {private_path, public_path, instance, application} and returns the
  1220. // details of the save that is designated by the initial request. The details are returned in an object
  1221. // composed of: save_name (name of the save) save_revision (revision of the save), explicit_revision (boolean, true if the request
  1222. // explicitly specified the revision, false if it did not), and application_path (the public_path of the application this is a save for).
  1223. getLoadInformation(response, potentialRevisions) {
  1224. let parsedRequest = response.path;
  1225. let segments = this.helpers.GenerateSegments(parsedRequest['private_path']);
  1226. let result = { 'save_name': undefined, 'save_revision': undefined, 'explicit_revision': undefined, 'application_path': undefined };
  1227. if (potentialRevisions.length > 0) {
  1228. result['save_name'] = segments[1];
  1229. if (segments.length > 2) {
  1230. var requestedRevision = parseInt(segments[2]);
  1231. if (requestedRevision) {
  1232. if (potentialRevisions.indexOf(requestedRevision) > -1) {
  1233. result['save_revision'] = requestedRevision;
  1234. result['explicit_revision'] = true;
  1235. result['application_path'] = parsedRequest['public_path'];
  1236. }
  1237. }
  1238. }
  1239. if (result['explicit_revision'] == undefined) {
  1240. result['explicit_revision'] = false;
  1241. potentialRevisions.sort();
  1242. result['save_revision'] = potentialRevisions.pop();
  1243. result['application_path'] = parsedRequest['public_path'];
  1244. }
  1245. }
  1246. return result;
  1247. }
  1248. async loadSaveObject(loadInfo) {
  1249. //let objName = loadInfo[ 'save_name' ] +'/'+ "savestate_" + loadInfo[ 'save_revision' ];
  1250. //let userDB = _LCSDB.user(_LCS_WORLD_USER.pub);
  1251. if (!loadInfo.save_name) {
  1252. return undefined
  1253. }
  1254. let objName = "savestate_" + loadInfo['application_path'] + '/' + loadInfo['save_name'] + '_vwf_json';
  1255. let objNameRev = "savestate_" + loadInfo['save_revision'] + loadInfo['application_path'] + '/' + loadInfo['save_name'] + '_vwf_json';
  1256. // if(loadInfo[ 'save_revision' ]){
  1257. // }
  1258. let worldName = this.helpers.appPath //loadInfo[ 'application_path' ].slice(1);
  1259. let dbNode = _LCSDB.user(_LCS_WORLD_USER.pub).get('documents').get(worldName).get(objName).get('revs').get(objNameRev);
  1260. let saveObject = await new Promise(res => dbNode.load(res, { wait: 300 }));
  1261. //(await userDB.get('documents').get(worldName).get(objName).get('revs').get(objNameRev).promOnce()).data;
  1262. var saveInfo = null;
  1263. if (saveObject) {
  1264. saveInfo = (typeof (saveObject.jsonState) == 'object') ? saveObject.jsonState : JSON.parse(saveObject.jsonState);
  1265. }
  1266. //typeof(saveObject == 'object')
  1267. return saveInfo;
  1268. }
  1269. // GetSaveInformation is a helper function that takes the application_path (/path/to/application).
  1270. // It returns an array of all saves found for that
  1271. // application (including separate entries for individual revisions of saves ).
  1272. async getSaveInformation(application_path, userPUB) {
  1273. var result = [];
  1274. let user = _LCSDB.user(userPUB);
  1275. var docName = application_path.slice(1);
  1276. let potentialSaveNames = (await user.get('documents').get(docName).promOnce()).data;
  1277. if (potentialSaveNames) {
  1278. for (const res of Object.keys(potentialSaveNames)) {
  1279. if (res !== '_') {
  1280. let el = (await user.get('documents').path(docName).get(res).promOnce()).data;
  1281. let revisionList = await this.lookupSaveRevisions(application_path.slice(1), el.filename);
  1282. var latestsave = true;
  1283. revisionList.sort();
  1284. while (revisionList.length > 0) {
  1285. var newEntry = {};
  1286. newEntry['applicationpath'] = application_path;
  1287. newEntry['savename'] = el.filename;
  1288. newEntry['revision'] = revisionList.pop().toString();
  1289. newEntry['latestsave'] = latestsave;
  1290. if (latestsave) {
  1291. newEntry['url'] = this.helpers.JoinPath(window.location.origin, application_path, "load", el.filename + "/");
  1292. }
  1293. else {
  1294. newEntry['url'] = this.helpers.JoinPath(window.location.origin, application_path, "load", el.filename + "/", newEntry['revision'] + "/");
  1295. }
  1296. latestsave = false;
  1297. result.push(newEntry);
  1298. }
  1299. }
  1300. }
  1301. }
  1302. return result;
  1303. }
  1304. async getProtoWorldFiles(userPub, worldName, date) {
  1305. return (new Promise(res => _LCSDB.user(userPub).get('worlds').get(worldName).once(res))).then(res => {
  1306. let worldFiles = Object.entries(res).filter(el => (el[0].includes('_json')) || (el[0].includes('_yaml')) || (el[0].includes('_html')) || (el[0].includes('_js')))
  1307. .filter(el => (el[0] !== 'info_json'));
  1308. console.log(worldFiles);
  1309. return worldFiles
  1310. });
  1311. }
  1312. async cloneWorldPrototype(worldName, userName, newWorldName, stateFileName) {
  1313. let self = this;
  1314. _app.showProgressBar();
  1315. let userPub = await _app.helpers.getUserPub(userName);
  1316. let newOwner = _LCSDB.user().is.pub;
  1317. let myWorlds = (await _LCSDB.user(newOwner).get('worlds').promOnce()).data;
  1318. //if (!myWorlds) _LCSDB.user(newOwner).get('worlds').put({});
  1319. _LCSDB.user(newOwner).get('worlds').not(res => {
  1320. _LCSDB.user(newOwner).get('worlds').put({});
  1321. })
  1322. if (myWorlds) {
  1323. let checkExist = Object.keys(myWorlds).filter(el => el == newWorldName);
  1324. if (newWorldName) {
  1325. if (checkExist.length > 0 && myWorlds[newWorldName]) {
  1326. console.log('already exist!');
  1327. return
  1328. }
  1329. }
  1330. }
  1331. let worldID = window._app.helpers.GenerateInstanceID().toString();
  1332. if (newWorldName) {
  1333. worldID = newWorldName
  1334. }
  1335. //let modified = new Date().valueOf();
  1336. console.log('clone: ' + worldName + 'to: ' + worldID);
  1337. let created = new Date().valueOf();
  1338. await _LCSDB.user(userPub).get('worlds').get(worldName).load(all => {
  1339. let worldObj = Object.assign({}, all);
  1340. worldObj.owner = newOwner;
  1341. worldObj.parent = userName + '/' + worldName;
  1342. worldObj.featured = true
  1343. worldObj.published = true
  1344. worldObj.created = created
  1345. if (!all.proxy) {
  1346. worldObj.proxy = userPub;
  1347. } else {
  1348. worldObj.proxy = all.proxy;
  1349. }
  1350. console.log(worldObj);
  1351. //let myWorlds = await _LCSDB.user(newOwner).get('worlds').once().then();
  1352. //let myWorld = _LCSDB.user(newOwner).get('worlds').get(worldID).put({id:worldID});
  1353. let myWorld = _LCSDB.user(newOwner).get('worlds').get(worldID).put({ id: worldID });
  1354. myWorld.put(worldObj, function (res) {
  1355. if (stateFileName) {
  1356. self.saveStateAsFile(stateFileName)
  1357. }
  1358. console.log(res)
  1359. }); //.get(worldID) let myWorld =
  1360. _app.hideProgressBar();
  1361. console.log('CLONED!!!');
  1362. let appEl = document.createElement("div");
  1363. appEl.setAttribute("id", 'cloneLink');
  1364. let entry = document.querySelector('#worldActionsGUI');
  1365. if (entry) {
  1366. entry.appendChild(appEl);
  1367. document.querySelector("#cloneLink").$cell({
  1368. id: 'cloneLink',
  1369. $cell: true,
  1370. $type: "div",
  1371. $components: [
  1372. {
  1373. $type: "a",
  1374. class: "mdc-button mdc-button--raised mdc-card__action",
  1375. $text: "Go to new cloned World!",
  1376. onclick: function (e) {
  1377. let myName = _LCSDB.user().is.alias;
  1378. window.location.pathname = '/' + myName + '/' + worldID + '/about'
  1379. }
  1380. }
  1381. ]
  1382. })
  1383. }
  1384. }, { wait: 500 }).then();
  1385. }
  1386. async cloneWorldState(filename) {
  1387. let myWorldProtos = (await _LCSDB.user().get('worlds').promOnce()).data;
  1388. let userName = this.helpers.worldUser;
  1389. // let users = await _LCSDB.get('users').then();
  1390. // let userPub = (await _LCSDB.get('users').get(userName).get('pub').promOnce()).data;
  1391. let userPub = await _app.helpers.getUserPub(userName);
  1392. let protoUserRoot = this.helpers.getRoot(true).root;
  1393. //let myName = this.db.user().is.alias;
  1394. //let proto = Object.keys(myWorldProtos).filter(el => el == protoUserRoot);
  1395. var protosKeys = [];
  1396. if (myWorldProtos)
  1397. protosKeys = Object.keys(myWorldProtos);
  1398. if (protosKeys.includes(protoUserRoot) && myWorldProtos[protoUserRoot]) {
  1399. let userProtoFiles = await this.getProtoWorldFiles(userPub, protoUserRoot);
  1400. let myProtoFiles = await this.getProtoWorldFiles(_LCSDB.user().is.pub, protoUserRoot);
  1401. let hashUP = await this.helpers.sha256(JSON.stringify(userProtoFiles));
  1402. let hashMP = await this.helpers.sha256(JSON.stringify(myProtoFiles));
  1403. if (hashUP == hashMP) {
  1404. this.saveStateAsFile(filename);
  1405. } else {
  1406. let noty = new Noty({
  1407. text: 'world prototype is modified.. could not clone world state',
  1408. timeout: 2000,
  1409. theme: 'mint',
  1410. layout: 'bottomRight',
  1411. type: 'error'
  1412. });
  1413. noty.show();
  1414. }
  1415. } else {
  1416. await this.cloneWorldPrototype(protoUserRoot, userName, protoUserRoot, filename);
  1417. //this.saveStateAsFile(filename);
  1418. }
  1419. }
  1420. //TODO: refactor and config save
  1421. async saveStateAsFile(filename, otherProto) // invoke with the view as "this"
  1422. {
  1423. console.log("Saving: " + filename);
  1424. //var clients = this.nodes["http://vwf.example.com/clients.vwf"];
  1425. // Save State Information
  1426. var state = vwf.getState();
  1427. state.nodes[0].children = {};
  1428. var timestamp = state["queue"].time;
  1429. timestamp = Math.round(timestamp * 1000);
  1430. let jsonValuePure = _app.helpers.replaceFloatArraysInNodeDef(state);
  1431. //remove all Ohm generated grammarsfrom state
  1432. let jsonValue = _app.helpers.removeGrammarObj(jsonValuePure);
  1433. var jsonState = JSON.stringify(jsonValue, null, '\t'); //JSON.stringify(jsonValue);
  1434. let rootPath = this.helpers.getRoot(true);
  1435. var inst = rootPath.inst;
  1436. if (filename == '') filename = inst;
  1437. //if (root.indexOf('.vwf') != -1) root = root.substring(0, root.lastIndexOf('/'));
  1438. var root = rootPath.root;
  1439. var json = jsonState;
  1440. if (otherProto) {
  1441. console.log('need to modify state...');
  1442. json = this.helpers.replaceSubStringALL(jsonState, '/' + root + '/', '/' + otherProto + '/');//jsonState.replace(('/' + root + '/'), ('/' + otherProto +'/') );
  1443. root = otherProto;
  1444. console.log(json);
  1445. }
  1446. //var documents = this.db.user().get('documents');
  1447. _LCSDB.user().get('documents').not(res => {
  1448. _LCSDB.user().get('documents').put({ id: 'documents' })
  1449. })
  1450. var saveRevision = new Date().valueOf();
  1451. var stateForStore = {
  1452. "root": root,
  1453. "filename": filename,
  1454. "inst": inst,
  1455. "timestamp": timestamp,
  1456. "extension": ".vwf.json",
  1457. "jsonState": json,
  1458. "publish": true
  1459. };
  1460. let rev = JSON.stringify(saveRevision);
  1461. var docNameRev = 'savestate_' + rev + '/' + root + '/' + filename + '_vwf_json';
  1462. let stateWithRev = Object.assign({}, stateForStore);
  1463. stateWithRev.revs = { [docNameRev]: stateForStore };
  1464. stateWithRev.revs[docNameRev].revision = saveRevision;
  1465. //let objName = loadInfo[ 'save_name' ] +'/'+ "savestate_" + loadInfo[ 'save_revision' ];
  1466. // "savestate_" + loadInfo[ 'save_revision' ] + '/' + loadInfo[ 'save_name' ] + '_vwf_json'
  1467. var docName = 'savestate_/' + root + '/' + filename + '_vwf_json';
  1468. let myNewWorldState = _LCSDB.user().get('documents').get(root).get(docName).put({ 'id': docName });
  1469. //_LCSDB.user().get('documents').get(root).get(docName).put(stateWithRev, function(res) {
  1470. myNewWorldState.put(stateWithRev, function (res) {
  1471. if (res) {
  1472. let noty = new Noty({
  1473. text: 'Saved to ' + docName,
  1474. timeout: 2000,
  1475. theme: 'mint',
  1476. layout: 'bottomRight',
  1477. type: 'success'
  1478. });
  1479. noty.show();
  1480. }
  1481. });
  1482. // let docInfo = await _LCSDB.user().get('worlds').get(root).get('info_json').get('file').then();
  1483. _LCSDB.user().get('worlds').get(root).get('info_json').once(function (file) {
  1484. if (file) {
  1485. let fileData = (typeof file == 'object') ? JSON.stringify(file) : file;
  1486. let docInfoName = 'savestate_/' + root + '/' + filename + '_info_vwf_json';
  1487. _LCSDB.user().get('documents').get(root).get(docInfoName).put(fileData);
  1488. }
  1489. });
  1490. // // Save Config Information
  1491. // var config = { "info": {}, "model": {}, "view": {} };
  1492. // // Save browser title
  1493. // config["info"]["title"] = document.title//$('title').html();
  1494. // // Save model drivers
  1495. // Object.keys(vwf_view.kernel.kernel.models).forEach(function (modelDriver) {
  1496. // if (modelDriver.indexOf('vwf/model/') != -1) config["model"][modelDriver] = "";
  1497. // });
  1498. // // If neither glge or threejs model drivers are defined, specify nodriver
  1499. // if (config["model"]["vwf/model/glge"] === undefined && config["model"]["vwf/model/threejs"] === undefined) config["model"]["nodriver"] = "";
  1500. // // Save view drivers and associated parameters, if any
  1501. // Object.keys(vwf_view.kernel.kernel.views).forEach(function (viewDriver) {
  1502. // if (viewDriver.indexOf('vwf/view/') != -1) {
  1503. // if (vwf_view.kernel.kernel.views[viewDriver].parameters) {
  1504. // config["view"][viewDriver] = vwf_view.kernel.kernel.views[viewDriver].parameters;
  1505. // }
  1506. // else config["view"][viewDriver] = "";
  1507. // }
  1508. // });
  1509. // //var jsonConfig = $.encoder.encodeForURL(JSON.stringify(config));
  1510. // var jsonConfig = JSON.stringify(config);
  1511. // let configStateForStore = {
  1512. // "root": root,
  1513. // "filename": filename,
  1514. // "inst": inst,
  1515. // "timestamp": timestamp,
  1516. // "extension": "config.vwf.json",
  1517. // "jsonState": jsonConfig
  1518. // };
  1519. //let objName = loadInfo[ 'save_name' ] +'/'+ "savestate_" + loadInfo[ 'save_revision' ];
  1520. // "savestate_" + loadInfo[ 'save_revision' ] + '/' + loadInfo[ 'save_name' ] + '_vwf_json'
  1521. // let configName = 'savestate_/' + root + '/' + filename + '_config_vwf_json';
  1522. // let documentSaveConfigState = this.db.user().get(configName).put(configStateForStore);
  1523. // //documents.path(root).set(documentSaveConfigState);
  1524. // let configNameRev = 'savestate_' + saveRevision.toString() + '/' + root + '/' + filename + '_config_vwf_json';
  1525. // this.db.user().get(configNameRev).put(configStateForStore);
  1526. // this.db.user().get(configNameRev).path("revision").put(saveRevision);
  1527. //documentSaveConfigState.path('revs').set(documentSaveStateRevision);
  1528. // Save config file to server
  1529. // var xhrConfig = new XMLHttpRequest();
  1530. // xhrConfig.open("POST", "/" + root + "/save/" + filename, true);
  1531. // xhrConfig.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  1532. // xhrConfig.send("root=" + root + "/" + filename + "&filename=saveState&inst=" + inst + "&timestamp=" + timestamp + "&extension=.vwf.config.json" + "&jsonState=" + jsonConfig);
  1533. }
  1534. fixSaveState(jsonState, otherProto, oldProtoName) {
  1535. console.log('fix proto in state...');
  1536. let json = this.helpers.replaceSubStringALL(jsonState, '/' + oldProtoName + '/', '/' + otherProto + '/');//jsonState.replace(('/' + root + '/'), ('/' + otherProto +'/') );
  1537. console.log(json);
  1538. return json
  1539. }
  1540. // LoadSavedState
  1541. async loadSavedState(filename, applicationpath, revision) {
  1542. console.log("Loading: " + filename);
  1543. let userDB = _LCSDB.user(_LCS_WORLD_USER.pub);
  1544. let userName = (await userDB.get('alias').promOnce()).data;
  1545. if (revision) {
  1546. window.location.pathname = '/' + userName + applicationpath + '/load/' + filename + '/' + revision + '/';
  1547. }
  1548. else { // applicationpath + "/" + inst + '/load/' + filename + '/';
  1549. window.location.pathname = '/' + userName + applicationpath + '/load/' + filename + '/';
  1550. }
  1551. }
  1552. hideUIControl() {
  1553. let el = document.getElementById("ui-controls");
  1554. if (el) {
  1555. el.classList.remove("visible");
  1556. el.classList.add("not-visible");
  1557. }
  1558. }
  1559. showUIControl() {
  1560. let el = document.getElementById("ui-controls");
  1561. if (el) {
  1562. el.classList.remove("not-visible");
  1563. el.classList.add("visible");
  1564. }
  1565. }
  1566. hideProgressBar() {
  1567. var progressbar = document.getElementById("load-progressbar");
  1568. if (progressbar) {
  1569. progressbar.classList.remove("visible");
  1570. progressbar.classList.remove("mdc-linear-progress--indeterminate");
  1571. progressbar.classList.add("not-visible");
  1572. progressbar.classList.add("mdc-linear-progress--closed");
  1573. }
  1574. }
  1575. showProgressBar() {
  1576. let progressbar = document.getElementById("load-progressbar");
  1577. if (progressbar) {
  1578. progressbar.classList.remove("not-visible");
  1579. progressbar.classList.remove("mdc-linear-progress--closed");
  1580. progressbar.classList.add("visible");
  1581. progressbar.classList.add("mdc-linear-progress--indeterminate");
  1582. }
  1583. }
  1584. // SUPPORT of DELETE USER WORLDS & SAVE STATES (experimental)
  1585. // TODO: manual garbage collection
  1586. async deleteWorldState(worldName, stateName) {
  1587. //let pathName = 'savestate_/' + worldName+ '/' + this._worldName.stateName + '_info_vwf_json';
  1588. let db = _LCSDB.user();
  1589. let stateEntryInfo = 'savestate_/' + worldName + '/' + stateName + '_info_vwf_json';
  1590. let stateEntry = 'savestate_/' + worldName + '/' + stateName + '_vwf_json';
  1591. db.get('documents').get(worldName).get(stateEntry).get('revs').once().map().once((res, k) => {
  1592. db.get('documents').get(worldName).get(stateEntry).get('revs').get(k).put(null);
  1593. //console.log(k, ' - ', res);
  1594. });
  1595. db.get('documents').get(worldName).get(stateEntryInfo).put(null, res => {
  1596. let id = 'worldCard_' + _LCSDB.user().is.alias + '_' + worldName + '_' + stateName;
  1597. let doc = document.querySelector('#' + id);
  1598. if (doc)
  1599. doc._refresh({})
  1600. });
  1601. db.get('documents').get(worldName).get(stateEntry).get('revs').put(null, res => {
  1602. db.get('documents').get(worldName).get(stateEntry).put(null);
  1603. });
  1604. }
  1605. async deleteWorld(name, type) {
  1606. let self = this;
  1607. if (type == 'proto') {
  1608. let worldName = name;
  1609. //TODO check for states (ask for deleting all states first...)
  1610. //delete states
  1611. let db = _LCSDB.user();
  1612. db.get('documents').once().map((res, k) => { if (k == worldName) return res }).once((res, k) => {
  1613. if (res) {
  1614. let worldStatesInfo = Object.entries(res).filter(el => el[0].includes('_info_vwf_json'));
  1615. worldStatesInfo.map(el => {
  1616. let saveName = el[0].split('/')[2].replace('_info_vwf_json', "");
  1617. console.log(saveName);
  1618. self.deleteWorldState(worldName, saveName)
  1619. //let stateEntry = 'savestate_/' + k + '/' + saveName + '_vwf_json';
  1620. })
  1621. }
  1622. })
  1623. db.get('worlds').get(worldName).put(null, res => {
  1624. let id = 'worldCard_' + _LCSDB.user().is.alias + '_' + worldName + '_';
  1625. let doc = document.querySelector('#' + id);
  1626. if (doc)
  1627. doc._refresh({})
  1628. })
  1629. } else if (type == 'state') {
  1630. let worldName = name.split('/')[0];
  1631. let stateName = name.split('/')[2];
  1632. // let stateEntryInfo = 'savestate_/' + worldName + '/' + stateName + '_info_vwf_json';
  1633. // let stateEntry = 'savestate_/' + worldName + '/' + stateName + '_vwf_json';
  1634. // await this.deleteWorldState(worldName, stateEntryInfo);
  1635. // await this.deleteWorldState(worldName, stateEntry);
  1636. await this.deleteWorldState(worldName, stateName);
  1637. }
  1638. let noty = new Noty({
  1639. text: "World Deleted!",
  1640. timeout: 2000,
  1641. theme: 'mint',
  1642. layout: 'bottomRight',
  1643. type: 'success'
  1644. });
  1645. noty.show();
  1646. }
  1647. parseAppInstancesData(data) {
  1648. let jsonObj = JSON.parse(data);
  1649. var parsed = {};
  1650. let listData = {};
  1651. for (var prop in jsonObj) {
  1652. var name = prop.split('/')[1];
  1653. if (parsed[name]) {
  1654. parsed[name][prop] = jsonObj[prop];
  1655. } else {
  1656. parsed[name] = {};
  1657. parsed[name][prop] = jsonObj[prop];
  1658. }
  1659. }
  1660. //console.log(parsed);
  1661. for (var prop in parsed) {
  1662. var name = prop;
  1663. let obj = Object.entries(parsed[prop]);
  1664. var lists = {};
  1665. obj.forEach(el => {
  1666. if (el[1].loadInfo['save_name']) {
  1667. let saveName = prop + '/load/' + el[1].loadInfo.save_name;
  1668. if (!lists[saveName])
  1669. lists[saveName] = {};
  1670. lists[saveName][el[0]] = el[1]
  1671. } else {
  1672. if (!lists[name])
  1673. lists[name] = {};
  1674. lists[name][el[0]] = el[1]
  1675. }
  1676. });
  1677. // console.log(lists);
  1678. Object.entries(lists).forEach(list => {
  1679. listData[list[0]] = list[1];
  1680. })
  1681. }
  1682. return listData
  1683. // console.log(data)
  1684. }
  1685. async getAllStateWorldsInfoForUser(userAlias, worldName, saveName) {
  1686. //let userPub = await new Promise(res => _LCSDB.get('users').get(userAlias).get('pub').once(res));
  1687. let userPub = await _app.helpers.getUserPub(userAlias);
  1688. var db = _LCSDB.user(userPub);
  1689. if (_LCSDB.user().is) {
  1690. if (_LCSDB.user().is.alias == userAlias)
  1691. db = _LCSDB.user();
  1692. }
  1693. //let hasDocs = await (new Promise(res => db.get('documents').not(res(false)))).then(res=>{return res});
  1694. let list = await (new Promise(res => db.get('documents').load(res, { wait: 400 })))
  1695. .then(r => {
  1696. if (!worldName) {
  1697. return Promise.all(Object.keys(r).map(k => db.get('documents').get(k).then(res => { return [k, res] })))
  1698. } else {
  1699. return Promise.all([db.get('documents').get(worldName).then(res => { return [worldName, res] })])
  1700. }
  1701. }
  1702. )
  1703. .then(r => Promise.all(Object.keys(r).map(k => {
  1704. let objEl = r[k][1];
  1705. if (objEl) {
  1706. let obj = Object.entries(objEl).filter(el => el[0].includes('_info_vwf_json'));
  1707. if (obj) {
  1708. return { world: r[k][0], states: obj }
  1709. }
  1710. } else {
  1711. return { world: r[k][0], states: [] }
  1712. }
  1713. }
  1714. )
  1715. )).then(r =>
  1716. Promise.all(r.map(k =>
  1717. Promise.all((k.states).map(el => {
  1718. let obj = el[1];
  1719. if (obj) {
  1720. return _LCSDB.get(el[1]['#']).load().then(m => { return { world: k.world, stateName: el[0], stateInfo: m } })
  1721. }
  1722. }
  1723. ))
  1724. ))
  1725. )
  1726. //console.log('All states: ', list)
  1727. let docs = {};
  1728. list.map(el => {
  1729. el.map(el => {
  1730. if (el) {
  1731. let res = el.stateInfo;
  1732. let doc = {};
  1733. if (res && res !== 'null') {
  1734. //if (res.file && res.file !== 'null') {
  1735. let saveName = el.stateName.split('/')[2].replace('_info_vwf_json', "");
  1736. var worldDesc = {};
  1737. if (typeof (res) == 'object') {
  1738. worldDesc = res
  1739. } else {
  1740. worldDesc = JSON.parse(res)
  1741. }
  1742. let root = Object.keys(worldDesc)[0];
  1743. var appInfo = worldDesc[root]['en'];
  1744. let langID = localStorage.getItem('krestianstvo_locale');
  1745. if (langID) {
  1746. appInfo = worldDesc[root][langID]
  1747. }
  1748. let settings = worldDesc[root]['settings'];
  1749. doc = {
  1750. 'worldName': el.world + '/load/' + saveName,
  1751. 'created': res.created ? res.created : res.modified,
  1752. 'modified': res.modified,
  1753. 'type': 'saveState',
  1754. 'userAlias': userAlias,
  1755. 'info': appInfo,
  1756. 'settings': settings
  1757. }
  1758. //}
  1759. }
  1760. if (Object.keys(doc).length !== 0) {
  1761. docs[doc.worldName] = doc;
  1762. }
  1763. }
  1764. })
  1765. })
  1766. console.log(docs);
  1767. if (saveName) {
  1768. return docs[saveName]
  1769. }
  1770. return docs
  1771. }
  1772. async getAllProtoWorldsInfoForUser(userAlias, worldName) {
  1773. //let userPub = await new Promise(res => _LCSDB.get('users').get(userAlias).get('pub').once(res));
  1774. let userPub = await _app.helpers.getUserPub(userAlias);
  1775. var db = _LCSDB.user(userPub);
  1776. if (_LCSDB.user().is) {
  1777. if (_LCSDB.user().is.alias == userAlias)
  1778. db = _LCSDB.user();
  1779. }
  1780. let list = await (new Promise(res => db.get('worlds').load(res, { wait: 400 })))
  1781. .then(r => {
  1782. if (!worldName) {
  1783. return Promise.all(Object.keys(r).map(k => db.get('worlds').get(k).then(res => { return [k, res] })))
  1784. } else {
  1785. return Promise.all([db.get('worlds').get(worldName).then(res => { return [worldName, res] })])
  1786. }
  1787. }
  1788. )
  1789. .then(r => Promise.all(Object.keys(r).map(k => {
  1790. let objEl = r[k][1];
  1791. if (objEl) {
  1792. let obj = objEl.info_json;
  1793. if (obj) {
  1794. return _LCSDB.get(obj["#"]).then(res => { return { world: r[k], info: res } })
  1795. }
  1796. }
  1797. }))).then(r => { return r })
  1798. //console.log(list);
  1799. let docs = {};
  1800. list.forEach(el => {
  1801. if (el) {
  1802. let doc = {}
  1803. let res = el.info;
  1804. let index = el.world[0];
  1805. let proxy = el.world[1].proxy;
  1806. if (res && res !== 'null') {
  1807. //if (res.file && res.file !== 'null') {
  1808. //let worldDesc = JSON.parse(res.file);
  1809. var worldDesc = {};
  1810. if (typeof (res) == 'object') {
  1811. worldDesc = res
  1812. } else {
  1813. worldDesc = JSON.parse(res)
  1814. }
  1815. let root = Object.keys(worldDesc)[0];
  1816. var appInfo = worldDesc[root]['en'];
  1817. let langID = localStorage.getItem('krestianstvo_locale');
  1818. if (langID) {
  1819. appInfo = worldDesc[root][langID]
  1820. }
  1821. let settings = worldDesc[root]['settings'];
  1822. doc = {
  1823. 'worldName': index,
  1824. 'created': res.created ? res.created : res.modified,
  1825. 'modified': res.modified,
  1826. 'proxy': proxy,
  1827. 'type': 'proto',
  1828. 'userAlias': userAlias,
  1829. 'info': appInfo,
  1830. 'settings': settings
  1831. }
  1832. //}
  1833. }
  1834. if (Object.keys(doc).length !== 0)
  1835. docs[index] = doc;
  1836. }
  1837. })
  1838. if (worldName) {
  1839. return docs[worldName]
  1840. }
  1841. return docs
  1842. }
  1843. async setNewProxyForWorld(worldName, proxyName) {
  1844. if (_LCSDB.user().is) {
  1845. let newProxy = await _app.helpers.getUserPub(proxyName)
  1846. if (newProxy)
  1847. _LCSDB.user().get('worlds').get(worldName).put({ 'proxy': newProxy })
  1848. }
  1849. }
  1850. }
  1851. export { App }