app.js 71 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426
  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 for worlds protos');
  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 dragDropProxyArea = {
  618. $cell: true,
  619. $type: 'div',
  620. id: "ddProxy",
  621. class: 'dragdropArea',
  622. _ddText: '',
  623. _refresh: function (aText) {
  624. this._ddText = aText;
  625. },
  626. $init: function () {
  627. console.log('init d&d area for proxy files');
  628. this._refresh('Drag & Drop a folder with proxy files here...');
  629. let self = this;
  630. DragDrop("#ddProxy",
  631. {
  632. onDrop: function (files, pos, fileList, directories) {
  633. console.log('onDrop: ' + files.length + ' files at ' + pos.x + ', ' + pos.y);
  634. //let worldsObj = {};
  635. let proxy = _LCSDB.user().get('proxy');
  636. files.forEach(function (file) {
  637. let proxyObj = {};
  638. if ((file.name.indexOf('.yaml') !== -1) ||
  639. (file.type == "text/javascript") ||
  640. (file.type == "text/html") ||
  641. (file.type == "application/json")) {
  642. console.log('- ' + file.name + ' (' + file.size + ') (' + file.type + ')');
  643. // convert the file to a Buffer that we can use!
  644. const reader = new FileReader()
  645. reader.addEventListener('load', e => {
  646. // e.target.result is an ArrayBuffer
  647. const arr = new Uint8Array(e.target.result)
  648. const fileBuffer = new buffer.Buffer(arr);
  649. const fileSource = fileBuffer.toString();
  650. // do something with the buffer!
  651. var entryName = file.fullPath.slice(1).split(".").join("_");
  652. let userPub = _LCSDB.user().is.pub;
  653. let created = new Date().valueOf();
  654. let obj = {
  655. 'owner': userPub,
  656. 'file': fileSource,
  657. 'modified': created,
  658. 'created': created
  659. }
  660. proxyObj[entryName] = obj;
  661. console.log(proxyObj);
  662. proxy.put(proxyObj);
  663. })
  664. reader.addEventListener('error', err => {
  665. console.error('FileReader error' + err)
  666. })
  667. reader.readAsArrayBuffer(file)
  668. }
  669. })
  670. //console.log('Worlds', worldsObj);
  671. console.log('files array', files)
  672. console.log('FileList object', fileList)
  673. console.log('directories array', directories)
  674. self._refresh(directories.map(el=>{return el.name}).toString());
  675. },
  676. onDropText: function (text, pos) {
  677. console.log('onDropText: ' + text + ' at ' + pos.x + ', ' + pos.y)
  678. }
  679. }
  680. )
  681. },
  682. $update: function () {
  683. this.$components = [
  684. {
  685. $type: "h5",
  686. class: "mdc-typography--headline5",
  687. $text: this._ddText
  688. }
  689. ]
  690. }
  691. }
  692. let userProfile = {
  693. $type: 'div',
  694. id: "profile",
  695. _status: "",
  696. _refresh: function(status){
  697. this._status = status;
  698. },
  699. $init: function () {
  700. this._status = "user is not signed in..."
  701. },
  702. $update: function () {
  703. var ddWorldArea = {}
  704. var ddProxyArea = {}
  705. if(_LCSDB.user().is){
  706. ddWorldArea = dragDropWorldsArea
  707. ddProxyArea = dragDropProxyArea
  708. }
  709. this.$components = [
  710. {
  711. $type: "h3",
  712. class: "mdc-typography--headline3",
  713. $text: this._status //"Profile for: " + this.db.user().is.alias
  714. },
  715. _app.widgets.divider,
  716. {
  717. $type: "h4",
  718. class: "mdc-typography--headline4",
  719. $text: 'Load my world\'s protos:' //"Profile for: " + this.db.user().is.alias
  720. },
  721. ddWorldArea,
  722. {
  723. $type: "h4",
  724. class: "mdc-typography--headline4",
  725. $text: 'Load proxy files:' //"Profile for: " + this.db.user().is.alias
  726. },
  727. ddProxyArea
  728. ]
  729. }
  730. }
  731. document.querySelector("#userProfile").$cell({
  732. $cell: true,
  733. $type: "div",
  734. $components: [userProfile]
  735. })
  736. }
  737. async HandleUserWorlds(ctx) {
  738. console.log("USER WORLDS INDEX");
  739. console.log(ctx.params);
  740. let user = ctx.params.user;
  741. page.redirect('/' + user + '/worlds/protos');
  742. }
  743. async HandleFileEdit(ctx) {
  744. console.log("USER WORLD FILE EDIT");
  745. let user = ctx.params.user;
  746. let worldName = ctx.params.name;
  747. let fileOriginal = ctx.params.file;
  748. let type = ctx.params.type;
  749. window._app.hideProgressBar();
  750. window._app.hideUIControl();
  751. _LCSDB.on('auth',
  752. async function (ack) {
  753. if (_LCSDB.user().is) {
  754. if (_LCSDB.user().is.alias == user) {
  755. var worldType = 'worlds';
  756. var file = fileOriginal;
  757. if (type == 'state') {
  758. worldType = 'documents';
  759. file = _app.helpers.replaceSubStringALL(fileOriginal, "~", '/');
  760. }
  761. _LCSDB.user().get(worldType).get(worldName).get(file).load(worldFile => {
  762. if (worldFile) {
  763. var source = worldFile.file;
  764. if (type == 'state') {
  765. if (!file.includes('_info_vwf_json')) {
  766. source = worldFile.jsonState;
  767. var saveName = worldFile.filename;
  768. }
  769. }
  770. //console.log(source);
  771. //var source = (typeof(sourceToEdit) =="object") ? JSON.stringify(sourceToEdit): sourceToEdit;
  772. if (file.includes('_json') && (typeof source !== 'object')) {
  773. source = (typeof JSON.parse(source) == 'object') ? JSON.stringify(JSON.parse(source), null, '\t') : source
  774. //source = source;//JSON.stringify(source, null, '\t');
  775. } else if (typeof source == 'object') {
  776. source = JSON.stringify(source, null, '\t')
  777. }
  778. let el = document.createElement("div");
  779. el.setAttribute("id", "worldFILE");
  780. document.body.appendChild(el);
  781. var saveGUI = {};
  782. if (type == 'proto' || file.includes('_info_vwf_json')) {
  783. saveGUI = {
  784. $type: "button",
  785. class: "mdc-button mdc-button--raised",
  786. $text: "Save",
  787. onclick: async function (e) {
  788. console.log("save new info");
  789. let editor = document.querySelector("#aceEditor").env.editor;
  790. let newInfo = editor.getValue();
  791. _LCSDB.user().get(worldType).get(worldName).get(file).get('file').put(newInfo, function (res) {
  792. if (res) {
  793. let noty = new Noty({
  794. text: 'Saved!',
  795. timeout: 2000,
  796. theme: 'mint',
  797. layout: 'bottomRight',
  798. type: 'success'
  799. });
  800. noty.show();
  801. let modified = new Date().valueOf();
  802. _LCSDB.user().get(worldType).get(worldName).get(file).get('modified').put(modified);
  803. }
  804. })
  805. }
  806. }
  807. }
  808. if (type == 'state' && !file.includes('_info_vwf_json')) {
  809. saveGUI =
  810. {
  811. $type: "div",
  812. class: "",
  813. $components: [
  814. {
  815. $type: "button",
  816. class: "mdc-button mdc-button--raised",
  817. $text: "Replace state",
  818. onclick: async function (e) {
  819. console.log("fix state");
  820. let editor = document.querySelector("#aceEditor").env.editor;
  821. let newInfo = editor.getValue();
  822. let fixedState = newInfo; //_app.fixSaveState(newInfo, worldName, oldProtoName);
  823. let userPub = (await _LCSDB.get('users').get(user).get('pub').promOnce()).data;
  824. let revs = await _app.lookupSaveRevisions(worldName, saveName, userPub);
  825. let lastRevision = revs.sort()[0];
  826. var newFile = file.replace('savestate_', 'savestate_' + lastRevision.toString());
  827. _LCSDB.user().get(worldType).get(worldName).get(file).get('revs').get(newFile).get('jsonState').put(fixedState);
  828. _LCSDB.user().get(worldType).get(worldName).get(file).get('jsonState').put(fixedState, function (res) {
  829. if (res) {
  830. let noty = new Noty({
  831. text: 'Repalced!',
  832. timeout: 2000,
  833. theme: 'mint',
  834. layout: 'bottomRight',
  835. type: 'success'
  836. });
  837. noty.show();
  838. let modified = new Date().valueOf();
  839. _LCSDB.user().get(worldType).get(worldName).get(file).get('modified').put(modified);
  840. }
  841. })
  842. }
  843. }
  844. ]
  845. }
  846. }
  847. let aceEditorCell = {
  848. $type: "div",
  849. $components: [
  850. {
  851. class: "aceEditor",
  852. id: "aceEditor",
  853. //style: "width:1200px; height: 800px",
  854. $type: "div",
  855. $text: source,
  856. $init: function () {
  857. var mode = "ace/mode/json";
  858. if (file.includes('_yaml'))
  859. mode = "ace/mode/yaml"
  860. if (file.includes('_js'))
  861. mode = "ace/mode/javascript"
  862. var editor = ace.edit("aceEditor");
  863. editor.setTheme("ace/theme/monokai");
  864. editor.setFontSize(16);
  865. editor.getSession().setMode(mode);
  866. editor.setOptions({
  867. maxLines: Infinity
  868. });
  869. editor.session.setUseWrapMode(true);
  870. }
  871. },
  872. saveGUI,
  873. {
  874. $type: "button",
  875. class: "mdc-button mdc-button--raised",
  876. $text: "Close",
  877. onclick: function (e) {
  878. console.log("close");
  879. //window.location.pathname = "/" + user + '/' + worldName + '/about'
  880. window.history.back();
  881. // if (type == "proto")
  882. // window.location.pathname = "/" + user + '/' + worldName + '/about'
  883. // if (type == "state")
  884. // window.location.pathname = "/" + user + '/' + worldName + '/about'
  885. }
  886. }
  887. ]
  888. }
  889. document.querySelector("#worldFILE").$cell({
  890. $cell: true,
  891. $type: "div",
  892. $components: [aceEditorCell
  893. ]
  894. })
  895. }
  896. });
  897. }
  898. }
  899. })
  900. }
  901. HandleUserWorldsWithType(ctx) {
  902. console.log("USER WORLDS INDEX");
  903. console.log(ctx.params);
  904. let user = ctx.params.user;
  905. let type = ctx.params.type;
  906. window._app.hideProgressBar();
  907. window._app.hideUIControl();
  908. if (!_app.indexApp) {
  909. _app.indexApp = new IndexApp;
  910. _app.indexApp.initHTML();
  911. _app.indexApp.initApp();
  912. }
  913. if (type == 'protos') {
  914. _app.indexApp.initWorldsProtosListForUser(user)//.getWorldsProtosListForUser(user);
  915. } else if (type == 'states') {
  916. _app.indexApp.initWorldsStatesListForUser(user);
  917. //await _app.indexApp.getWorldsFromUserDB(user);
  918. }
  919. }
  920. async HandleIndex() {
  921. console.log("INDEX");
  922. window._app.hideProgressBar();
  923. window._app.hideUIControl();
  924. if (!_app.indexApp) {
  925. _app.indexApp = new IndexApp;
  926. await _app.indexApp.generateFrontPage();
  927. _app.indexApp.initHTML();
  928. }
  929. _app.indexApp.initApp();
  930. _q(_LCSDB).get('~@app').data().then(res => {
  931. if (res) {
  932. _app.indexApp.initWorldsProtosListForUser('app');
  933. }
  934. })
  935. // _LCSDB.get('~@app').once(res=>{
  936. // if (res){
  937. // _app.indexApp.initWorldsProtosListForUser('app');
  938. // }
  939. // })
  940. //await _app.indexApp.getAppDetailsFromDB();
  941. }
  942. HandleNoPage() {
  943. console.log("no such page")
  944. }
  945. //handle parcable requests
  946. HandleParsableLoadRequest(ctx) {
  947. let app = window._app;
  948. console.log(ctx.params);
  949. //var pathname = ctx.pathname;
  950. var spaceName = ctx.params.space;
  951. var saveName = ctx.params.savename;
  952. let user = ctx.params.user;
  953. page.redirect('/' + user + '/' + spaceName + '/' + app.helpers.GenerateInstanceID() + '/load/' + saveName);
  954. }
  955. HandleParsableLoadRequestWithRev(ctx) {
  956. let app = window._app;
  957. console.log(ctx.params);
  958. //var pathname = ctx.pathname;
  959. var spaceName = ctx.params.space;
  960. var saveName = ctx.params.savename;
  961. var rev = ctx.params.rev;
  962. let user = ctx.params.user;
  963. page.redirect('/' + user + '/' + spaceName + '/' + app.helpers.GenerateInstanceID() + '/load/' + saveName + '/' + rev);
  964. }
  965. async setUserPaths(user) {
  966. await _q(_LCSDB).get('users').get(user).get('pub').data().then(function (res) {
  967. if (res)
  968. window._LCS_WORLD_USER = {
  969. alias: user,
  970. pub: res
  971. }
  972. })
  973. //let users = _LCSDB.get('users');
  974. // await _LCSDB.get('users').get(user).get('pub').then(function (res) {
  975. // if (res)
  976. // window._LCS_WORLD_USER = {
  977. // alias: user,
  978. // pub: res
  979. // }
  980. // })
  981. // await _LCSDB.get('users').get(user).get('pub').once(res => {
  982. // if (res)
  983. // window._LCS_WORLD_USER = _LCSDB.user(res);
  984. // }).then();
  985. }
  986. HandleParsableRequestGenID(ctx) {
  987. let app = window._app;
  988. console.log(ctx.params);
  989. let user = ctx.params.user;
  990. let space = ctx.params.space;
  991. var pathname = ctx.pathname;
  992. //await app.setUserPaths(user);
  993. _q(_LCSDB).get('users').get(user).get('pub').data().then(function (res) {
  994. if (res)
  995. window._LCS_WORLD_USER = {
  996. alias: user,
  997. pub: res
  998. }
  999. if (pathname[pathname.length - 1] == '/') {
  1000. pathname = pathname.slice(0, -1)
  1001. }
  1002. let pathToParse = '/' + space; // pathname.replace('/' + user, "");
  1003. let parsedRequest = {
  1004. application: "index.vwf",
  1005. instance: undefined,
  1006. private_path: undefined,
  1007. public_path: pathToParse
  1008. }
  1009. localStorage.setItem('lcs_app', JSON.stringify({ path: parsedRequest }));
  1010. console.log(parsedRequest);
  1011. if ((parsedRequest['instance'] == undefined) && (parsedRequest['private_path'] == undefined) && (parsedRequest['public_path'] !== "/") && (parsedRequest['application'] !== undefined)) {
  1012. //page.redirect(pathname + '/' + app.helpers.GenerateInstanceID());
  1013. window.location.pathname = pathname + '/' + app.helpers.GenerateInstanceID()
  1014. }
  1015. })
  1016. }
  1017. HandleParsableRequestWithID(ctx) {
  1018. let app = window._app;
  1019. console.log(ctx.params);
  1020. var pathname = ctx.pathname;
  1021. let user = ctx.params.user;
  1022. let genID = ctx.params.id;
  1023. let space = ctx.params.space;
  1024. let savename = ctx.params.savename;
  1025. if (pathname[pathname.length - 1] == '/') {
  1026. pathname = pathname.slice(0, -1)
  1027. }
  1028. //await app.setUserPaths(user);
  1029. //_q(_LCSDB).get('users').get(user).get('pub').data()
  1030. new Promise(res => _LCSDB.get('users').get(user).get('pub').once(res)).then(function (res) {
  1031. if (res)
  1032. window._LCS_WORLD_USER = {
  1033. alias: user,
  1034. pub: res
  1035. }
  1036. }).then(res => {
  1037. return app.loadAppLibs()
  1038. }).then(res => {
  1039. let pathToParse = '/' + space; //pathname.replace('/' + user, "");
  1040. let parsedRequest = {
  1041. application: "index.vwf",
  1042. instance: genID,
  1043. private_path: undefined,
  1044. public_path: pathToParse
  1045. }
  1046. if (savename) {
  1047. parsedRequest.private_path = 'load/' + savename;
  1048. }
  1049. localStorage.setItem('lcs_app', JSON.stringify({ path: parsedRequest }));
  1050. return parsedRequest
  1051. }).then(pr => {
  1052. let cpath = pr.public_path;
  1053. return new Promise(res => _LCSDB.user(_LCS_WORLD_USER.pub).get('worlds').get(cpath.slice(1)).load(res, { wait: 400 }))
  1054. }).then(val => {
  1055. let res = val['index_vwf_config_yaml'].file;
  1056. var conf = "";
  1057. if (res) {
  1058. let config = YAML.parse(res);
  1059. conf = config
  1060. }
  1061. let manualSettings = localStorage.getItem('lcs_app_manual_settings');
  1062. if (manualSettings) {
  1063. let manualConf = JSON.parse(manualSettings);
  1064. conf.model = manualConf.model;
  1065. conf.view = manualConf.view;
  1066. }
  1067. return conf
  1068. }).then(res => {
  1069. var userLibraries = { model: {}, view: {} };
  1070. var application;
  1071. vwf.loadConfiguration(application, userLibraries, res, compatibilityCheck);
  1072. })
  1073. }
  1074. async loadAppLibs() {
  1075. await loadjs([
  1076. '/vwf/model/aframe/aframe-master.min.js',
  1077. '/vwf/model/aframe/extras/aframe-extras.loaders.js',
  1078. '/vwf/model/aframe/extras/aframe-extras.controls.min.js',
  1079. '/vwf/model/aframe/kframe/aframe-aabb-collider-component.min.js',
  1080. '/vwf/model/aframe/addon/aframe-interpolation.js',
  1081. '/vwf/model/aframe/addon/aframe-sun-sky.js',
  1082. '/vwf/model/aframe/addon/SkyShader.js',
  1083. '/vwf/model/aframe/addon/BVHLoader.js',
  1084. '/vwf/model/aframe/addon/TransformControls.js',
  1085. '/vwf/model/aframe/addon/THREE.MeshLine.js',
  1086. '/vwf/model/aframe/addon/aframe-components.js',
  1087. '/vwf/view/arjs/aframe-ar.js'
  1088. ], {
  1089. async: false,
  1090. returnPromise: true
  1091. });
  1092. return loadjs([
  1093. '/lib/compatibilitycheck.js',
  1094. '/vwf/view/webrtc/adapter-latest.js',
  1095. '/lib/draggabilly/draggabilly.pkgd.js',
  1096. '/vwf/model/aframe/addon/virtualgc/nipplejs.js',
  1097. '/lib/lively.vm_standalone.js',
  1098. '/lib/require.js',
  1099. '/lib/crypto.js',
  1100. '/lib/md5.js',
  1101. '/lib/alea.js',
  1102. '/lib/mash.js',
  1103. '/vwf.js'
  1104. ], {
  1105. async: false,
  1106. returnPromise: true
  1107. })
  1108. }
  1109. //get DB application state information for reflector (called from VWF)
  1110. async getApplicationState() {
  1111. let dataJson = JSON.parse(localStorage.getItem('lcs_app'));
  1112. if (dataJson) {
  1113. if (!dataJson.path['instance']) return undefined;
  1114. }
  1115. //let userAlias = await _LCS_WORLD_USER.get('alias').once().then();
  1116. // let userPub = await _LCSDB.get('users').get(userAlias).get('pub').once().then();
  1117. let userAlias = _LCS_WORLD_USER.alias;
  1118. let userPub = _LCS_WORLD_USER.pub;
  1119. let parsedRequest = dataJson.path;
  1120. if (parsedRequest['private_path']) {
  1121. var segments = this.helpers.GenerateSegments(parsedRequest['private_path']);
  1122. if ((segments.length > 1) && (segments[0] == "load")) {
  1123. var potentialRevs = await this.lookupSaveRevisions((parsedRequest['public_path']).slice(1), segments[1]);
  1124. }
  1125. var loadInfo = this.getLoadInformation(dataJson, potentialRevs);
  1126. var saveInfo = await this.loadSaveObject(loadInfo);
  1127. }
  1128. let loadObj = {
  1129. loadInfo: loadInfo ? loadInfo: {},
  1130. path: dataJson.path,
  1131. saveObject: saveInfo,
  1132. user: userAlias
  1133. }
  1134. //dataJson.app = loadObj;
  1135. localStorage.setItem('lcs_app', JSON.stringify(loadObj));
  1136. console.log(loadObj);
  1137. //temporary solution for syncing DB replicas using Gun.load()
  1138. // _LCS_SYS_USER.get('proxy').load(res=>{
  1139. // if (res)
  1140. // {console.log('proxy loaded');
  1141. // _LCSDB.user(userPub).get('worlds').get(loadObj.path.public_path.slice(1)).load(w=>{
  1142. // if (w) {
  1143. // console.log('world files loaded');
  1144. // vwf.ready( vwf.application, loadObj)
  1145. // }
  1146. // });
  1147. // }
  1148. // });
  1149. return loadObj
  1150. }
  1151. // LookupSaveRevisions takes the public path and the name of a save, and provides
  1152. // an array of all revisions for that save. (If the save does not exist, this will be
  1153. // an empty array).
  1154. async lookupSaveRevisions(public_path, save_name, userPub) {
  1155. var pub = "";
  1156. if (!_LCS_WORLD_USER) {
  1157. pub = userPub;
  1158. } else {
  1159. pub = _LCS_WORLD_USER.pub
  1160. }
  1161. //let userDB = _LCSDB.user(pub);
  1162. var result = [];
  1163. let docName = 'savestate_/' + public_path + '/' + save_name + '_vwf_json';
  1164. let node = _LCSDB.user(pub).get('documents').get(public_path).get(docName).get('revs');
  1165. let revs = await new Promise(res => node.load(res, { wait: 400 }));
  1166. if (revs) {
  1167. for (const res of Object.values(revs)) {
  1168. result.push(parseInt(res.revision));
  1169. }
  1170. return result
  1171. }
  1172. }
  1173. // GetLoadInformation receives a parsed request {private_path, public_path, instance, application} and returns the
  1174. // details of the save that is designated by the initial request. The details are returned in an object
  1175. // composed of: save_name (name of the save) save_revision (revision of the save), explicit_revision (boolean, true if the request
  1176. // explicitly specified the revision, false if it did not), and application_path (the public_path of the application this is a save for).
  1177. getLoadInformation(response, potentialRevisions) {
  1178. let parsedRequest = response.path;
  1179. let segments = this.helpers.GenerateSegments(parsedRequest['private_path']);
  1180. let result = { 'save_name': undefined, 'save_revision': undefined, 'explicit_revision': undefined, 'application_path': undefined };
  1181. if (potentialRevisions.length > 0) {
  1182. result['save_name'] = segments[1];
  1183. if (segments.length > 2) {
  1184. var requestedRevision = parseInt(segments[2]);
  1185. if (requestedRevision) {
  1186. if (potentialRevisions.indexOf(requestedRevision) > -1) {
  1187. result['save_revision'] = requestedRevision;
  1188. result['explicit_revision'] = true;
  1189. result['application_path'] = parsedRequest['public_path'];
  1190. }
  1191. }
  1192. }
  1193. if (result['explicit_revision'] == undefined) {
  1194. result['explicit_revision'] = false;
  1195. potentialRevisions.sort();
  1196. result['save_revision'] = potentialRevisions.pop();
  1197. result['application_path'] = parsedRequest['public_path'];
  1198. }
  1199. }
  1200. return result;
  1201. }
  1202. async loadSaveObject(loadInfo) {
  1203. //let objName = loadInfo[ 'save_name' ] +'/'+ "savestate_" + loadInfo[ 'save_revision' ];
  1204. //let userDB = _LCSDB.user(_LCS_WORLD_USER.pub);
  1205. if (!loadInfo.save_name) {
  1206. return undefined
  1207. }
  1208. let objName = "savestate_" + loadInfo['application_path'] + '/' + loadInfo['save_name'] + '_vwf_json';
  1209. let objNameRev = "savestate_" + loadInfo['save_revision'] + loadInfo['application_path'] + '/' + loadInfo['save_name'] + '_vwf_json';
  1210. // if(loadInfo[ 'save_revision' ]){
  1211. // }
  1212. let worldName = this.helpers.appPath //loadInfo[ 'application_path' ].slice(1);
  1213. let dbNode = _LCSDB.user(_LCS_WORLD_USER.pub).get('documents').get(worldName).get(objName).get('revs').get(objNameRev);
  1214. let saveObject = await new Promise(res => dbNode.load(res, { wait: 300 }));
  1215. //(await userDB.get('documents').get(worldName).get(objName).get('revs').get(objNameRev).promOnce()).data;
  1216. var saveInfo = null;
  1217. if (saveObject) {
  1218. saveInfo = (typeof (saveObject.jsonState) == 'object') ? saveObject.jsonState : JSON.parse(saveObject.jsonState);
  1219. }
  1220. //typeof(saveObject == 'object')
  1221. return saveInfo;
  1222. }
  1223. // GetSaveInformation is a helper function that takes the application_path (/path/to/application).
  1224. // It returns an array of all saves found for that
  1225. // application (including separate entries for individual revisions of saves ).
  1226. async getSaveInformation(application_path, userPUB) {
  1227. var result = [];
  1228. let user = _LCSDB.user(userPUB);
  1229. var docName = application_path.slice(1);
  1230. let potentialSaveNames = (await user.get('documents').get(docName).promOnce()).data;
  1231. if (potentialSaveNames) {
  1232. for (const res of Object.keys(potentialSaveNames)) {
  1233. if (res !== '_') {
  1234. let el = (await user.get('documents').path(docName).get(res).promOnce()).data;
  1235. let revisionList = await this.lookupSaveRevisions(application_path.slice(1), el.filename);
  1236. var latestsave = true;
  1237. revisionList.sort();
  1238. while (revisionList.length > 0) {
  1239. var newEntry = {};
  1240. newEntry['applicationpath'] = application_path;
  1241. newEntry['savename'] = el.filename;
  1242. newEntry['revision'] = revisionList.pop().toString();
  1243. newEntry['latestsave'] = latestsave;
  1244. if (latestsave) {
  1245. newEntry['url'] = this.helpers.JoinPath(window.location.origin, application_path, "load", el.filename + "/");
  1246. }
  1247. else {
  1248. newEntry['url'] = this.helpers.JoinPath(window.location.origin, application_path, "load", el.filename + "/", newEntry['revision'] + "/");
  1249. }
  1250. latestsave = false;
  1251. result.push(newEntry);
  1252. }
  1253. }
  1254. }
  1255. }
  1256. return result;
  1257. }
  1258. async getProtoWorldFiles(userPub, worldName, date) {
  1259. let fileNamesAll = (await _LCSDB.user(userPub).get('worlds').get(worldName).promOnce()).data;
  1260. 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'));
  1261. let worldObj = {};
  1262. for (var doc in worldFileNames) {
  1263. let fn = worldFileNames[doc];
  1264. let res = (await _LCSDB.user(userPub).get('worlds').get(worldName).get(fn).promOnce()).data;
  1265. var data = {
  1266. 'file': res.file,
  1267. 'modified': res.modified,
  1268. 'created': res.created
  1269. }
  1270. if (!date) {
  1271. data = {
  1272. 'file': res.file
  1273. }
  1274. }
  1275. worldObj[fn] = data;
  1276. }
  1277. console.log(worldObj);
  1278. return worldObj
  1279. }
  1280. async cloneWorldPrototype(worldName, userName, newWorldName, stateFileName) {
  1281. let self = this;
  1282. _app.showProgressBar();
  1283. //let users = await _LCSDB.get('users').then();
  1284. let userPub = (await _LCSDB.get('users').get(userName).get('pub').promOnce()).data;
  1285. let newOwner = _LCSDB.user().is.pub;
  1286. let myWorlds = (await _LCSDB.user(newOwner).get('worlds').promOnce()).data;
  1287. //if (!myWorlds) _LCSDB.user(newOwner).get('worlds').put({});
  1288. _LCSDB.user(newOwner).get('worlds').not(res => {
  1289. _LCSDB.user(newOwner).get('worlds').put({});
  1290. })
  1291. if (myWorlds) {
  1292. let checkExist = Object.keys(myWorlds).filter(el => el == newWorldName);
  1293. if (newWorldName) {
  1294. //let worldProto = (await _LCSDB.user(newOwner).get('worlds').get(newWorldName).promOnce()).data;
  1295. if (checkExist.length > 0 && myWorlds[newWorldName]) {
  1296. console.log('already exist!');
  1297. return
  1298. }
  1299. }
  1300. }
  1301. var worldID = window._app.helpers.GenerateInstanceID().toString();
  1302. if (newWorldName) {
  1303. worldID = newWorldName
  1304. }
  1305. //let modified = new Date().valueOf();
  1306. console.log('clone: ' + worldName + 'to: ' + worldID);
  1307. let created = new Date().valueOf();
  1308. let worldObj = {
  1309. 'owner': newOwner,
  1310. 'parent': userName + '/' + worldName,
  1311. 'featured': true,
  1312. 'published': true
  1313. };
  1314. // let fileNamesAll =
  1315. await _LCSDB.user(userPub).get('worlds').get(worldName).load(all => {
  1316. let worldFileNames = Object.keys(all).filter(el => (el !== '_') && (el !== 'owner') && (el !== 'parent') && (el !== 'featured') && (el !== 'published') && (el !== '_config_yaml') && (el !== '_yaml') && (el !== '_html'));
  1317. for (var doc in worldFileNames) {
  1318. let fn = worldFileNames[doc];
  1319. let res = all[fn]; //(await _LCSDB.user(userPub).get('worlds').get(worldName).get(fn).promOnce()).data;
  1320. let fileData = (typeof res.file == 'object') ? JSON.stringify(res.file) : res.file;
  1321. let data = {
  1322. 'file': fileData, //JSON.stringify(res.file),
  1323. 'modified': created
  1324. }
  1325. worldObj[fn] = data;
  1326. }
  1327. console.log(worldObj);
  1328. // for (const obj of Object.keys(worldObj)) {
  1329. // let myWorlds = _LCSDB.user().get('worlds');
  1330. // let myNewWorld = myWorlds.get(worldID);
  1331. // myNewWorld.get(obj).put(worldObj[obj]);
  1332. // }
  1333. //let myWorlds = await _LCSDB.user(newOwner).get('worlds').once().then();
  1334. let myWorld = _LCSDB.user(newOwner).get('worlds').get(worldID).put({});
  1335. myWorld.put(worldObj, function (res) {
  1336. if (stateFileName) {
  1337. self.saveStateAsFile(stateFileName)
  1338. }
  1339. console.log(res)
  1340. }); //.get(worldID) let myWorld =
  1341. // let myWorld = _LCSDB.user().get(worldID).put(worldObj);
  1342. // _LCSDB.user().get('worlds').set(myWorld);
  1343. _app.hideProgressBar();
  1344. console.log('CLONED!!!');
  1345. let appEl = document.createElement("div");
  1346. appEl.setAttribute("id", 'cloneLink');
  1347. let entry = document.querySelector('#worldActionsGUI');
  1348. if (entry) {
  1349. entry.appendChild(appEl);
  1350. document.querySelector("#cloneLink").$cell({
  1351. id: 'cloneLink',
  1352. $cell: true,
  1353. $type: "div",
  1354. $components: [
  1355. {
  1356. $type: "a",
  1357. class: "mdc-button mdc-button--raised mdc-card__action",
  1358. $text: "Go to new cloned World!",
  1359. onclick: function (e) {
  1360. let myName = _LCSDB.user().is.alias;
  1361. window.location.pathname = '/' + myName + '/' + worldID + '/about'
  1362. }
  1363. }
  1364. ]
  1365. })
  1366. }
  1367. }, { wait: 500 }).then();
  1368. //window.location.pathname = '/' + userName + '/' + worldID + '/about'
  1369. //page()
  1370. // Object.keys(worldObj).forEach(el => {
  1371. // this.db.user().get('worlds').get(worldID).get(el).put(worldObj[el]);
  1372. // })
  1373. }
  1374. async cloneWorldState(filename) {
  1375. let myWorldProtos = (await _LCSDB.user().get('worlds').promOnce()).data;
  1376. let userName = this.helpers.worldUser;
  1377. // let users = await _LCSDB.get('users').then();
  1378. let userPub = (await _LCSDB.get('users').get(userName).get('pub').promOnce()).data;
  1379. let protoUserRoot = this.helpers.getRoot(true).root;
  1380. //let myName = this.db.user().is.alias;
  1381. //let proto = Object.keys(myWorldProtos).filter(el => el == protoUserRoot);
  1382. var protosKeys = [];
  1383. if (myWorldProtos)
  1384. protosKeys = Object.keys(myWorldProtos);
  1385. if (protosKeys.includes(protoUserRoot) && myWorldProtos[protoUserRoot]) {
  1386. let userProtoFiles = await this.getProtoWorldFiles(userPub, protoUserRoot);
  1387. let myProtoFiles = await this.getProtoWorldFiles(_LCSDB.user().is.pub, protoUserRoot);
  1388. let hashUP = await this.helpers.sha256(JSON.stringify(userProtoFiles));
  1389. let hashMP = await this.helpers.sha256(JSON.stringify(myProtoFiles));
  1390. if (hashUP == hashMP) {
  1391. this.saveStateAsFile(filename);
  1392. } else {
  1393. let noty = new Noty({
  1394. text: 'world prototype is modified.. could not clone world state',
  1395. timeout: 2000,
  1396. theme: 'mint',
  1397. layout: 'bottomRight',
  1398. type: 'error'
  1399. });
  1400. noty.show();
  1401. }
  1402. } else {
  1403. await this.cloneWorldPrototype(protoUserRoot, userName, protoUserRoot, filename);
  1404. //this.saveStateAsFile(filename);
  1405. }
  1406. }
  1407. //TODO: refactor and config save
  1408. async saveStateAsFile(filename, otherProto) // invoke with the view as "this"
  1409. {
  1410. console.log("Saving: " + filename);
  1411. //var clients = this.nodes["http://vwf.example.com/clients.vwf"];
  1412. // Save State Information
  1413. var state = vwf.getState();
  1414. state.nodes[0].children = {};
  1415. var timestamp = state["queue"].time;
  1416. timestamp = Math.round(timestamp * 1000);
  1417. let jsonValuePure = _app.helpers.replaceFloatArraysInNodeDef(state);
  1418. //remove all Ohm generated grammarsfrom state
  1419. let jsonValue = _app.helpers.removeGrammarObj(jsonValuePure);
  1420. var jsonState = JSON.stringify(jsonValue, null, '\t'); //JSON.stringify(jsonValue);
  1421. let rootPath = this.helpers.getRoot(true);
  1422. var inst = rootPath.inst;
  1423. if (filename == '') filename = inst;
  1424. //if (root.indexOf('.vwf') != -1) root = root.substring(0, root.lastIndexOf('/'));
  1425. var root = rootPath.root;
  1426. var json = jsonState;
  1427. if (otherProto) {
  1428. console.log('need to modify state...');
  1429. json = this.helpers.replaceSubStringALL(jsonState, '/' + root + '/', '/' + otherProto + '/');//jsonState.replace(('/' + root + '/'), ('/' + otherProto +'/') );
  1430. root = otherProto;
  1431. console.log(json);
  1432. }
  1433. //var documents = this.db.user().get('documents');
  1434. var saveRevision = new Date().valueOf();
  1435. var stateForStore = {
  1436. "root": root,
  1437. "filename": filename,
  1438. "inst": inst,
  1439. "timestamp": timestamp,
  1440. "extension": ".vwf.json",
  1441. "jsonState": json,
  1442. "publish": true
  1443. };
  1444. let rev = JSON.stringify(saveRevision);
  1445. var docNameRev = 'savestate_' + rev + '/' + root + '/' + filename + '_vwf_json';
  1446. let stateWithRev = Object.assign({}, stateForStore);
  1447. stateWithRev.revs = { [docNameRev]: stateForStore };
  1448. stateWithRev.revs[docNameRev].revision = saveRevision;
  1449. //let objName = loadInfo[ 'save_name' ] +'/'+ "savestate_" + loadInfo[ 'save_revision' ];
  1450. // "savestate_" + loadInfo[ 'save_revision' ] + '/' + loadInfo[ 'save_name' ] + '_vwf_json'
  1451. var docName = 'savestate_/' + root + '/' + filename + '_vwf_json';
  1452. let myNewWorldState = _LCSDB.user().get('documents').get(root).get(docName).put({});
  1453. //_LCSDB.user().get('documents').get(root).get(docName).put(stateWithRev, function(res) {
  1454. myNewWorldState.put(stateWithRev, function (res) {
  1455. if (res) {
  1456. let noty = new Noty({
  1457. text: 'Saved to ' + docName,
  1458. timeout: 2000,
  1459. theme: 'mint',
  1460. layout: 'bottomRight',
  1461. type: 'success'
  1462. });
  1463. noty.show();
  1464. }
  1465. });
  1466. // let docInfo = await _LCSDB.user().get('worlds').get(root).get('info_json').get('file').then();
  1467. _LCSDB.user().get('worlds').get(root).get('info_json').get('file').once(function (file) {
  1468. if (file) {
  1469. let modified = saveRevision;
  1470. let newOwner = _LCSDB.user().is.pub;
  1471. let userName = _LCSDB.user().is.alias;
  1472. let fileData = (typeof file == 'object') ? JSON.stringify(file) : file;
  1473. let obj = {
  1474. 'parent': userName + '/' + root,
  1475. 'owner': newOwner,
  1476. 'file': fileData, //file, //JSON.stringify(file),
  1477. //'modified': modified,
  1478. 'created': modified
  1479. }
  1480. let docInfoName = 'savestate_/' + root + '/' + filename + '_info_vwf_json';
  1481. _LCSDB.user().get('documents').get(root).get(docInfoName).get('file').not(function (res) {
  1482. _LCSDB.user().get('documents').get(root).get(docInfoName).put(obj);
  1483. });
  1484. _LCSDB.user().get('documents').get(root).get(docInfoName).get('created').not(function (res) {
  1485. _LCSDB.user().get('documents').get(root).get(docInfoName).get('created').put(modified);
  1486. });
  1487. _LCSDB.user().get('documents').get(root).get(docInfoName).get('modified').put(modified);
  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, indexState) {
  1587. let revs = (await _LCSDB.user().get('documents').get(worldName).get(indexState).get('revs').promOnce()).data;
  1588. if (revs) {
  1589. for (const el of Object.keys(revs)) {
  1590. if (el !== '_') {
  1591. let doc = (await _LCSDB.user().get('documents').get(worldName).get(indexState).get('revs').get(el).promOnce()).data;
  1592. for (const rev of Object.keys(doc)) {
  1593. if (rev !== '_') {
  1594. await _LCSDB.user().get('documents').get(worldName).get(indexState).get('revs').get(el).get(rev).put(null).promOnce();
  1595. }
  1596. }
  1597. await _LCSDB.user().get('documents').get(worldName).get(indexState).get('revs').get(el).put(null).promOnce();
  1598. }
  1599. }
  1600. }
  1601. // clear all state params
  1602. let stateDoc = (await _LCSDB.user().get('documents').get(worldName).get(indexState).promOnce()).data;
  1603. for (const state of Object.keys(stateDoc)) {
  1604. if (state !== '_' && state !== 'revs') {
  1605. await _LCSDB.user().get('documents').get(worldName).get(indexState).get(state).put(null).promOnce();
  1606. }
  1607. }
  1608. await _LCSDB.user().get('documents').get(worldName).get(indexState).get('revs').put(null).promOnce();
  1609. await _LCSDB.user().get('documents').get(worldName).get(indexState).put(null).promOnce();
  1610. }
  1611. async deleteWorld(name, type) {
  1612. if (type == 'proto') {
  1613. let worldName = name;
  1614. //TODO check for states (ask for deleting all states first...)
  1615. //delete states
  1616. let documents = (await _LCSDB.user().get('documents').promOnce()).data;
  1617. if (documents) {
  1618. let states = (await _LCSDB.user().get('documents').get(worldName).promOnce()).data;
  1619. if (states) {
  1620. for (const st of Object.keys(states)) {
  1621. if (st !== '_') {
  1622. if (states[st]) {
  1623. await this.deleteWorldState(worldName, st);
  1624. }
  1625. }
  1626. }
  1627. }
  1628. }
  1629. let worldFiles = (await _LCSDB.user().get('worlds').get(worldName).promOnce()).data;
  1630. if (worldFiles) {
  1631. for (const el of Object.keys(worldFiles)) {
  1632. if (el !== '_') {
  1633. let doc = (await _LCSDB.user().get('worlds').get(worldName).get(el).promOnce()).data;
  1634. if (doc) {
  1635. if (doc.file) {
  1636. for (const fEl of Object.keys(doc)) {
  1637. if (fEl !== '_') {
  1638. await _LCSDB.user().get('worlds').get(worldName).get(el).get(fEl).put(null).promOnce();
  1639. }
  1640. }
  1641. await _LCSDB.user().get('worlds').get(worldName).get(el).put(null).promOnce();
  1642. } else {
  1643. await _LCSDB.user().get('worlds').get(worldName).get(el).put(null).promOnce()
  1644. }
  1645. }
  1646. }
  1647. }
  1648. }
  1649. // this.db.user().get('worlds').get(worldName).map((res, index) => {
  1650. // if(typeof res == 'object'){
  1651. // this.db.user().get('worlds').get(worldName).get(index)
  1652. // .get('file').put("null")
  1653. // .back(1)
  1654. // .get('modified').put("null")
  1655. // .back(1)
  1656. // .get('created').put("null")
  1657. // .back(1).put("null")
  1658. // } else {
  1659. // this.db.user().get('worlds').get(worldName).get(index).put("null")
  1660. // }
  1661. // })
  1662. await _LCSDB.user().get('worlds').get(worldName).put(null).promOnce();
  1663. } else if (type == 'state') {
  1664. let worldName = name.split('/')[0];
  1665. let stateName = name.split('/')[2];
  1666. let stateEntryInfo = 'savestate_/' + worldName + '/' + stateName + '_info_vwf_json';
  1667. let stateEntry = 'savestate_/' + worldName + '/' + stateName + '_vwf_json';
  1668. await this.deleteWorldState(worldName, stateEntryInfo);
  1669. await this.deleteWorldState(worldName, stateEntry);
  1670. }
  1671. let noty = new Noty({
  1672. text: "World Deleted!",
  1673. timeout: 2000,
  1674. theme: 'mint',
  1675. layout: 'bottomRight',
  1676. type: 'success'
  1677. });
  1678. noty.show();
  1679. }
  1680. parseAppInstancesData(data) {
  1681. let jsonObj = JSON.parse(data);
  1682. var parsed = {};
  1683. let listData = {};
  1684. for (var prop in jsonObj) {
  1685. var name = prop.split('/')[1];
  1686. if (parsed[name]) {
  1687. parsed[name][prop] = jsonObj[prop];
  1688. } else {
  1689. parsed[name] = {};
  1690. parsed[name][prop] = jsonObj[prop];
  1691. }
  1692. }
  1693. //console.log(parsed);
  1694. for (var prop in parsed) {
  1695. var name = prop;
  1696. let obj = Object.entries(parsed[prop]);
  1697. var lists = {};
  1698. obj.forEach(el => {
  1699. if (el[1].loadInfo['save_name']) {
  1700. let saveName = prop + '/load/' + el[1].loadInfo.save_name;
  1701. if (!lists[saveName])
  1702. lists[saveName] = {};
  1703. lists[saveName][el[0]] = el[1]
  1704. } else {
  1705. if (!lists[name])
  1706. lists[name] = {};
  1707. lists[name][el[0]] = el[1]
  1708. }
  1709. });
  1710. // console.log(lists);
  1711. Object.entries(lists).forEach(list => {
  1712. listData[list[0]] = list[1];
  1713. })
  1714. }
  1715. return listData
  1716. // console.log(data)
  1717. }
  1718. async getAllStateWorldsInfoForUser(userAlias, worldName, saveName) {
  1719. let userPub = await new Promise(res => _LCSDB.get('users').get(userAlias).get('pub').once(res));
  1720. var db = _LCSDB.user(userPub);
  1721. if (_LCSDB.user().is) {
  1722. if (_LCSDB.user().is.alias == userAlias)
  1723. db = _LCSDB.user();
  1724. }
  1725. let list = await (new Promise(res => db.get('documents').load(res, { wait: 300 })))
  1726. .then(r => {
  1727. if (!worldName) {
  1728. return Promise.all(Object.keys(r).map(k => db.get('documents').get(k).then(res => { return [k, res] })))
  1729. } else {
  1730. return Promise.all([db.get('documents').get(worldName).then(res => { return [worldName, res] })])
  1731. }
  1732. }
  1733. )
  1734. .then(r => Promise.all(Object.keys(r).map(k => {
  1735. let objEl = r[k][1];
  1736. if(objEl){
  1737. let obj = Object.entries(objEl).filter(el => el[0].includes('_info_vwf_json'));
  1738. if (obj) {
  1739. return { world: r[k][0], states: obj }
  1740. }
  1741. } else {
  1742. return { world: r[k][0], states: [] }
  1743. }
  1744. }
  1745. )
  1746. )).then(r =>
  1747. Promise.all(r.map(k =>
  1748. Promise.all((k.states).map(el =>
  1749. {
  1750. let obj = el[1];
  1751. if(obj){
  1752. return _LCSDB.get(el[1]['#']).load().then(m => { return { world: k.world, stateName: el[0], stateInfo: m } })
  1753. }
  1754. }
  1755. ))
  1756. ))
  1757. )
  1758. //console.log('All states: ', list)
  1759. let docs = {};
  1760. list.map(el => {
  1761. el.map(el => {
  1762. if(el){
  1763. let res = el.stateInfo;
  1764. let doc = {};
  1765. if (res && res !== 'null') {
  1766. if (res.file && res.file !== 'null') {
  1767. let saveName = el.stateName.split('/')[2].replace('_info_vwf_json', "");
  1768. var worldDesc = {};
  1769. if (typeof (res.file) == 'object') {
  1770. worldDesc = res.file
  1771. } else {
  1772. worldDesc = JSON.parse(res.file)
  1773. }
  1774. let root = Object.keys(worldDesc)[0];
  1775. var appInfo = worldDesc[root]['en'];
  1776. let langID = localStorage.getItem('krestianstvo_locale');
  1777. if (langID) {
  1778. appInfo = worldDesc[root][langID]
  1779. }
  1780. doc = {
  1781. 'worldName': el.world + '/load/' + saveName,
  1782. 'created': res.created ? res.created : res.modified,
  1783. 'modified': res.modified,
  1784. 'type': 'saveState',
  1785. 'userAlias': userAlias,
  1786. 'info': appInfo
  1787. }
  1788. }
  1789. }
  1790. if (Object.keys(doc).length !== 0) {
  1791. docs[doc.worldName] = doc;
  1792. }
  1793. }
  1794. })
  1795. })
  1796. console.log(docs);
  1797. if (saveName) {
  1798. return docs[saveName]
  1799. }
  1800. return docs
  1801. }
  1802. async getAllProtoWorldsInfoForUser(userAlias, worldName) {
  1803. let userPub = await new Promise(res => _LCSDB.get('users').get(userAlias).get('pub').once(res));
  1804. var db = _LCSDB.user(userPub);
  1805. if (_LCSDB.user().is) {
  1806. if (_LCSDB.user().is.alias == userAlias)
  1807. db = _LCSDB.user();
  1808. }
  1809. let list = await (new Promise(res => db.get('worlds').load(res, { wait: 300 })))
  1810. .then(r => {
  1811. if (!worldName) {
  1812. return Promise.all(Object.keys(r).map(k => db.get('worlds').get(k).then(res => { return [k, res] })))
  1813. } else {
  1814. return Promise.all([db.get('worlds').get(worldName).then(res => { return [worldName, res] })])
  1815. }
  1816. }
  1817. )
  1818. .then(r => Promise.all(Object.keys(r).map(k => {
  1819. let objEl = r[k][1];
  1820. if(objEl){
  1821. let obj = objEl.info_json;
  1822. if (obj) {
  1823. return _LCSDB.get(obj["#"]).then(res => { return { world: r[k][0], info: res } })
  1824. }
  1825. }
  1826. }))).then(r => { return r })
  1827. //console.log(list);
  1828. let docs = {};
  1829. list.forEach(el => {
  1830. if (el) {
  1831. let doc = {}
  1832. let res = el.info;
  1833. let index = el.world;
  1834. if (res && res !== 'null') {
  1835. if (res.file && res.file !== 'null') {
  1836. //let worldDesc = JSON.parse(res.file);
  1837. var worldDesc = {};
  1838. if (typeof (res.file) == 'object') {
  1839. worldDesc = res.file
  1840. } else {
  1841. worldDesc = JSON.parse(res.file)
  1842. }
  1843. let root = Object.keys(worldDesc)[0];
  1844. var appInfo = worldDesc[root]['en'];
  1845. let langID = localStorage.getItem('krestianstvo_locale');
  1846. if (langID) {
  1847. appInfo = worldDesc[root][langID]
  1848. }
  1849. doc = {
  1850. 'worldName': index,
  1851. 'created': res.created ? res.created : res.modified,
  1852. 'modified': res.modified,
  1853. 'type': 'proto',
  1854. 'userAlias': userAlias,
  1855. 'info': appInfo
  1856. }
  1857. }
  1858. }
  1859. if (Object.keys(doc).length !== 0)
  1860. docs[index] = doc;
  1861. }
  1862. })
  1863. if (worldName) {
  1864. return docs[worldName]
  1865. }
  1866. return docs
  1867. }
  1868. }
  1869. export { App }