app.js 68 KB

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