app.js 61 KB

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