app.js 61 KB

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