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