app.js 77 KB

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