app.js 76 KB

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