app.js 77 KB

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