app.js 75 KB

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