app.js 81 KB

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