app.js 73 KB

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