app.js 76 KB

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