app.js 70 KB

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