ServerStorage.vue 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731
  1. <template>
  2. <div class="hidden"></div>
  3. </template>
  4. <script>
  5. //-----------------------------------------------------------------------------
  6. import Vue from 'vue';
  7. import Component from 'vue-class-component';
  8. import _ from 'lodash';
  9. import bookManager from '../share/bookManager';
  10. import readerApi from '../../../api/reader';
  11. import * as utils from '../../../share/utils';
  12. import * as cryptoUtils from '../../../share/cryptoUtils';
  13. import localForage from 'localforage';
  14. const ssCacheStore = localForage.createInstance({
  15. name: 'ssCacheStore'
  16. });
  17. export default @Component({
  18. watch: {
  19. serverSyncEnabled: function() {
  20. this.serverSyncEnabledChanged();
  21. },
  22. serverStorageKey: function() {
  23. this.serverStorageKeyChanged(true);
  24. },
  25. settings: function() {
  26. this.debouncedSaveSettings();
  27. },
  28. profiles: function() {
  29. this.saveProfiles();
  30. },
  31. currentProfile: function() {
  32. this.currentProfileChanged(true);
  33. },
  34. libs: function() {
  35. this.debouncedSaveLibs();
  36. },
  37. },
  38. })
  39. class ServerStorage extends Vue {
  40. created() {
  41. this.inited = false;
  42. this.keyInited = false;
  43. this.commit = this.$store.commit;
  44. this.prevServerStorageKey = null;
  45. this.$root.$on('generateNewServerStorageKey', () => {this.generateNewServerStorageKey()});
  46. this.debouncedSaveSettings = _.debounce(() => {
  47. this.saveSettings();
  48. }, 500);
  49. this.debouncedSaveLibs = _.debounce(() => {
  50. this.saveLibs();
  51. }, 500);
  52. this.debouncedNotifySuccess = _.debounce(() => {
  53. this.success('Данные синхронизированы с сервером');
  54. }, 1000);
  55. this.oldProfiles = {};
  56. this.oldSettings = {};
  57. this.oldLibs = {};
  58. }
  59. async init() {
  60. try {
  61. this.cachedRecent = await ssCacheStore.getItem('recent');
  62. if (!this.cachedRecent)
  63. await this.cleanCachedRecent('cachedRecent');
  64. this.cachedRecentPatch = await ssCacheStore.getItem('recent-patch');
  65. if (!this.cachedRecentPatch)
  66. await this.cleanCachedRecent('cachedRecentPatch');
  67. this.cachedRecentMod = await ssCacheStore.getItem('recent-mod');
  68. if (!this.cachedRecentMod)
  69. await this.cleanCachedRecent('cachedRecentMod');
  70. if (!this.serverStorageKey) {
  71. //генерируем новый ключ
  72. await this.generateNewServerStorageKey();
  73. } else {
  74. await this.serverStorageKeyChanged();
  75. }
  76. } finally {
  77. this.inited = true;
  78. }
  79. }
  80. async setCachedRecent(value) {
  81. await ssCacheStore.setItem('recent', value);
  82. this.cachedRecent = value;
  83. }
  84. async setCachedRecentPatch(value) {
  85. await ssCacheStore.setItem('recent-patch', value);
  86. this.cachedRecentPatch = value;
  87. }
  88. async setCachedRecentMod(value) {
  89. await ssCacheStore.setItem('recent-mod', value);
  90. this.cachedRecentMod = value;
  91. }
  92. async cleanCachedRecent(whatToClean) {
  93. if (whatToClean == 'cachedRecent' || whatToClean == 'all')
  94. await this.setCachedRecent({rev: 0, data: {}});
  95. if (whatToClean == 'cachedRecentPatch' || whatToClean == 'all')
  96. await this.setCachedRecentPatch({rev: 0, data: {}});
  97. if (whatToClean == 'cachedRecentMod' || whatToClean == 'all')
  98. await this.setCachedRecentMod({rev: 0, data: {}});
  99. }
  100. async generateNewServerStorageKey() {
  101. const key = utils.toBase58(utils.randomArray(32));
  102. this.commit('reader/setServerStorageKey', key);
  103. await this.serverStorageKeyChanged(true);
  104. }
  105. async serverSyncEnabledChanged() {
  106. if (this.serverSyncEnabled) {
  107. this.prevServerStorageKey = null;
  108. if (!this.serverStorageKey) {
  109. //генерируем новый ключ
  110. await this.generateNewServerStorageKey();
  111. } else {
  112. await this.serverStorageKeyChanged(true);
  113. }
  114. }
  115. }
  116. async serverStorageKeyChanged(force) {
  117. if (this.prevServerStorageKey != this.serverStorageKey) {
  118. this.prevServerStorageKey = this.serverStorageKey;
  119. this.hashedStorageKey = utils.toBase58(cryptoUtils.sha256(this.serverStorageKey));
  120. this.keyInited = true;
  121. await this.loadProfiles(force);
  122. this.checkCurrentProfile();
  123. await this.currentProfileChanged(force);
  124. await this.loadLibs(force);
  125. if (force)
  126. await this.cleanCachedRecent('all');
  127. const loadSuccess = await this.loadRecent();
  128. if (loadSuccess && force) {
  129. await this.saveRecent();
  130. }
  131. }
  132. }
  133. async currentProfileChanged(force) {
  134. if (!this.currentProfile)
  135. return;
  136. await this.loadSettings(force);
  137. }
  138. get serverSyncEnabled() {
  139. return this.$store.state.reader.serverSyncEnabled;
  140. }
  141. get settings() {
  142. return this.$store.state.reader.settings;
  143. }
  144. get settingsRev() {
  145. return this.$store.state.reader.settingsRev;
  146. }
  147. get serverStorageKey() {
  148. return this.$store.state.reader.serverStorageKey;
  149. }
  150. get profiles() {
  151. return this.$store.state.reader.profiles;
  152. }
  153. get profilesRev() {
  154. return this.$store.state.reader.profilesRev;
  155. }
  156. get currentProfile() {
  157. return this.$store.state.reader.currentProfile;
  158. }
  159. get showServerStorageMessages() {
  160. return this.settings.showServerStorageMessages;
  161. }
  162. get libs() {
  163. return this.$store.state.reader.libs;
  164. }
  165. get libsRev() {
  166. return this.$store.state.reader.libsRev;
  167. }
  168. checkCurrentProfile() {
  169. if (!this.profiles[this.currentProfile]) {
  170. this.commit('reader/setCurrentProfile', '');
  171. }
  172. }
  173. success(message) {
  174. if (this.showServerStorageMessages)
  175. this.$root.notify.success(message);
  176. }
  177. warning(message) {
  178. if (this.showServerStorageMessages && !this.offlineModeActive)
  179. this.$root.notify.warning(message);
  180. }
  181. error(message) {
  182. if (this.showServerStorageMessages && !this.offlineModeActive)
  183. this.$root.notify.error(message);
  184. }
  185. async loadSettings(force = false, doNotifySuccess = true) {
  186. if (!this.keyInited || !this.serverSyncEnabled || !this.currentProfile)
  187. return;
  188. const setsId = `settings-${this.currentProfile}`;
  189. const oldRev = this.settingsRev[setsId] || 0;
  190. //проверим ревизию на сервере
  191. if (!force) {
  192. try {
  193. const revs = await this.storageCheck({[setsId]: {}});
  194. if (revs.state == 'success' && revs.items[setsId].rev == oldRev) {
  195. return;
  196. }
  197. } catch(e) {
  198. this.error(`Ошибка соединения с сервером: ${e.message}`);
  199. return;
  200. }
  201. }
  202. let sets = null;
  203. try {
  204. sets = await this.storageGet({[setsId]: {}});
  205. } catch(e) {
  206. this.error(`Ошибка соединения с сервером: ${e.message}`);
  207. return;
  208. }
  209. if (sets.state == 'success') {
  210. sets = sets.items[setsId];
  211. if (sets.rev == 0)
  212. sets.data = {};
  213. this.oldSettings = _.cloneDeep(sets.data);
  214. this.commit('reader/setSettings', sets.data);
  215. this.commit('reader/setSettingsRev', {[setsId]: sets.rev});
  216. if (doNotifySuccess)
  217. this.debouncedNotifySuccess();
  218. } else {
  219. this.warning(`Неверный ответ сервера: ${sets.state}`);
  220. }
  221. }
  222. async saveSettings() {
  223. if (!this.keyInited || !this.serverSyncEnabled || !this.currentProfile || this.savingSettings)
  224. return;
  225. const diff = utils.getObjDiff(this.oldSettings, this.settings);
  226. if (utils.isEmptyObjDiff(diff))
  227. return;
  228. this.savingSettings = true;
  229. try {
  230. const setsId = `settings-${this.currentProfile}`;
  231. let result = {state: ''};
  232. const oldRev = this.settingsRev[setsId] || 0;
  233. try {
  234. result = await this.storageSet({[setsId]: {rev: oldRev + 1, data: this.settings}});
  235. } catch(e) {
  236. this.error(`Ошибка соединения с сервером (${e.message}). Данные не сохранены и могут быть перезаписаны.`);
  237. }
  238. if (result.state == 'reject') {
  239. await this.loadSettings(true, false);
  240. this.warning(`Последние изменения отменены. Данные синхронизированы с сервером.`);
  241. } else if (result.state == 'success') {
  242. this.oldSettings = _.cloneDeep(this.settings);
  243. this.commit('reader/setSettingsRev', {[setsId]: this.settingsRev[setsId] + 1});
  244. }
  245. } finally {
  246. this.savingSettings = false;
  247. }
  248. }
  249. async loadProfiles(force = false, doNotifySuccess = true) {
  250. if (!this.keyInited || !this.serverSyncEnabled)
  251. return;
  252. const oldRev = this.profilesRev;
  253. //проверим ревизию на сервере
  254. if (!force) {
  255. try {
  256. const revs = await this.storageCheck({profiles: {}});
  257. if (revs.state == 'success' && revs.items.profiles.rev == oldRev) {
  258. return;
  259. }
  260. } catch(e) {
  261. this.error(`Ошибка соединения с сервером: ${e.message}`);
  262. return;
  263. }
  264. }
  265. let prof = null;
  266. try {
  267. prof = await this.storageGet({profiles: {}});
  268. } catch(e) {
  269. this.error(`Ошибка соединения с сервером: ${e.message}`);
  270. return;
  271. }
  272. if (prof.state == 'success') {
  273. prof = prof.items.profiles;
  274. if (prof.rev == 0)
  275. prof.data = {};
  276. this.oldProfiles = _.cloneDeep(prof.data);
  277. this.commit('reader/setProfiles', prof.data);
  278. this.commit('reader/setProfilesRev', prof.rev);
  279. this.checkCurrentProfile();
  280. if (doNotifySuccess)
  281. this.debouncedNotifySuccess();
  282. } else {
  283. this.warning(`Неверный ответ сервера: ${prof.state}`);
  284. }
  285. }
  286. async saveProfiles() {
  287. if (!this.keyInited || !this.serverSyncEnabled || this.savingProfiles)
  288. return;
  289. const diff = utils.getObjDiff(this.oldProfiles, this.profiles);
  290. if (utils.isEmptyObjDiff(diff))
  291. return;
  292. //обнуляются профили во время разработки при hotReload, подстраховка
  293. if (!this.$store.state.reader.allowProfilesSave) {
  294. console.error('Сохранение профилей не санкционировано');
  295. return;
  296. }
  297. this.savingProfiles = true;
  298. try {
  299. let result = {state: ''};
  300. try {
  301. result = await this.storageSet({profiles: {rev: this.profilesRev + 1, data: this.profiles}});
  302. } catch(e) {
  303. this.error(`Ошибка соединения с сервером (${e.message}). Данные не сохранены и могут быть перезаписаны.`);
  304. }
  305. if (result.state == 'reject') {
  306. await this.loadProfiles(true, false);
  307. this.warning(`Последние изменения отменены. Данные синхронизированы с сервером.`);
  308. } else if (result.state == 'success') {
  309. this.oldProfiles = _.cloneDeep(this.profiles);
  310. this.commit('reader/setProfilesRev', this.profilesRev + 1);
  311. }
  312. } finally {
  313. this.savingProfiles = false;
  314. }
  315. }
  316. async loadLibs(force = false, doNotifySuccess = true) {
  317. if (!this.keyInited || !this.serverSyncEnabled)
  318. return;
  319. const oldRev = this.libsRev;
  320. //проверим ревизию на сервере
  321. if (!force) {
  322. try {
  323. const revs = await this.storageCheck({libs: {}});
  324. if (revs.state == 'success' && revs.items.libs.rev == oldRev) {
  325. return;
  326. }
  327. } catch(e) {
  328. this.error(`Ошибка соединения с сервером: ${e.message}`);
  329. return;
  330. }
  331. }
  332. let libs = null;
  333. try {
  334. libs = await this.storageGet({libs: {}});
  335. } catch(e) {
  336. this.error(`Ошибка соединения с сервером: ${e.message}`);
  337. return;
  338. }
  339. if (libs.state == 'success') {
  340. libs = libs.items.libs;
  341. if (libs.rev == 0)
  342. libs.data = {};
  343. this.oldLibs = _.cloneDeep(libs.data);
  344. this.commit('reader/setLibs', libs.data);
  345. this.commit('reader/setLibsRev', libs.rev);
  346. if (doNotifySuccess)
  347. this.debouncedNotifySuccess();
  348. } else {
  349. this.warning(`Неверный ответ сервера: ${libs.state}`);
  350. }
  351. }
  352. async saveLibs() {
  353. if (!this.keyInited || !this.serverSyncEnabled || this.savingLibs)
  354. return;
  355. const diff = utils.getObjDiff(this.oldLibs, this.libs);
  356. if (utils.isEmptyObjDiff(diff))
  357. return;
  358. this.savingLibs = true;
  359. try {
  360. let result = {state: ''};
  361. try {
  362. result = await this.storageSet({libs: {rev: this.libsRev + 1, data: this.libs}});
  363. } catch(e) {
  364. this.error(`Ошибка соединения с сервером (${e.message}). Данные не сохранены и могут быть перезаписаны.`);
  365. }
  366. if (result.state == 'reject') {
  367. await this.loadLibs(true, false);
  368. this.warning(`Последние изменения отменены. Данные синхронизированы с сервером.`);
  369. } else if (result.state == 'success') {
  370. this.oldLibs = _.cloneDeep(this.libs);
  371. this.commit('reader/setLibsRev', this.libsRev + 1);
  372. }
  373. } finally {
  374. this.savingLibs = false;
  375. }
  376. }
  377. async loadRecent(skipRevCheck = false, doNotifySuccess = true) {
  378. if (!this.keyInited || !this.serverSyncEnabled || this.loadingRecent)
  379. return;
  380. this.loadingRecent = true;
  381. try {
  382. //проверим ревизию на сервере
  383. let query = {recent: {}, recentPatch: {}, recentMod: {}};
  384. let revs = null;
  385. if (!skipRevCheck) {
  386. try {
  387. revs = await this.storageCheck(query);
  388. if (revs.state == 'success') {
  389. if (revs.items.recent.rev != this.cachedRecent.rev) {
  390. //no changes
  391. } else if (revs.items.recentPatch.rev != this.cachedRecentPatch.rev) {
  392. query = {recentPatch: {}, recentMod: {}};
  393. } else if (revs.items.recentMod.rev != this.cachedRecentMod.rev) {
  394. query = {recentMod: {}};
  395. } else
  396. return true;
  397. }
  398. } catch(e) {
  399. this.error(`Ошибка соединения с сервером: ${e.message}`);
  400. return;
  401. }
  402. }
  403. let recent = null;
  404. try {
  405. recent = await this.storageGet(query);
  406. } catch(e) {
  407. this.error(`Ошибка соединения с сервером: ${e.message}`);
  408. return;
  409. }
  410. if (recent.state == 'success') {
  411. let newRecent = recent.items.recent;
  412. let newRecentPatch = recent.items.recentPatch;
  413. let newRecentMod = recent.items.recentMod;
  414. if (!newRecent) {
  415. newRecent = _.cloneDeep(this.cachedRecent);
  416. }
  417. if (!newRecentPatch) {
  418. newRecentPatch = _.cloneDeep(this.cachedRecentPatch);
  419. }
  420. if (!newRecentMod) {
  421. newRecentMod = _.cloneDeep(this.cachedRecentMod);
  422. }
  423. if (newRecent.rev == 0) newRecent.data = {};
  424. if (newRecentPatch.rev == 0) newRecentPatch.data = {};
  425. if (newRecentMod.rev == 0) newRecentMod.data = {};
  426. let result = Object.assign({}, newRecent.data, newRecentPatch.data);
  427. const md = newRecentMod.data;
  428. if (md.key && result[md.key])
  429. result[md.key] = utils.applyObjDiff(result[md.key], md.mod, {isAddChanged: true});
  430. if (!bookManager.loaded) {
  431. this.warning('Ожидание загрузки списка книг перед синхронизацией');
  432. while (!bookManager.loaded) await utils.sleep(100);
  433. }
  434. if (newRecent.rev != this.cachedRecent.rev)
  435. await this.setCachedRecent(newRecent);
  436. if (newRecentPatch.rev != this.cachedRecentPatch.rev)
  437. await this.setCachedRecentPatch(newRecentPatch);
  438. if (newRecentMod.rev != this.cachedRecentMod.rev)
  439. await this.setCachedRecentMod(newRecentMod);
  440. await bookManager.setRecent(result);
  441. } else {
  442. this.warning(`Неверный ответ сервера: ${recent.state}`);
  443. return;
  444. }
  445. if (doNotifySuccess)
  446. this.debouncedNotifySuccess();
  447. } finally {
  448. this.loadingRecent = false;
  449. }
  450. return true;
  451. }
  452. async saveRecent(itemKey, recurse) {
  453. while (!this.inited || this.savingRecent)
  454. await utils.sleep(100);
  455. if (!this.keyInited || !this.serverSyncEnabled || this.savingRecent)
  456. return;
  457. this.savingRecent = true;
  458. try {
  459. const bm = bookManager;
  460. let needSaveRecent = false;
  461. let needSaveRecentPatch = false;
  462. let needSaveRecentMod = false;
  463. //newRecentMod
  464. let newRecentMod = {};
  465. if (itemKey && this.cachedRecentPatch.data[itemKey] && this.prevItemKey == itemKey) {
  466. newRecentMod = _.cloneDeep(this.cachedRecentMod);
  467. newRecentMod.rev++;
  468. newRecentMod.data.key = itemKey;
  469. newRecentMod.data.mod = utils.getObjDiff(this.cachedRecentPatch.data[itemKey], bm.recent[itemKey]);
  470. needSaveRecentMod = true;
  471. }
  472. this.prevItemKey = itemKey;
  473. //newRecentPatch
  474. let newRecentPatch = {};
  475. if (itemKey && !needSaveRecentMod) {
  476. newRecentPatch = _.cloneDeep(this.cachedRecentPatch);
  477. newRecentPatch.rev++;
  478. newRecentPatch.data[itemKey] = _.cloneDeep(bm.recent[itemKey]);
  479. let applyMod = this.cachedRecentMod.data;
  480. if (applyMod && applyMod.key && newRecentPatch.data[applyMod.key])
  481. newRecentPatch.data[applyMod.key] = utils.applyObjDiff(newRecentPatch.data[applyMod.key], applyMod.mod, {isAddChanged: true});
  482. newRecentMod = {rev: this.cachedRecentMod.rev + 1, data: {}};
  483. needSaveRecentPatch = true;
  484. needSaveRecentMod = true;
  485. }
  486. //newRecent
  487. let newRecent = {};
  488. if (!itemKey || (needSaveRecentPatch && Object.keys(newRecentPatch.data).length > 10)) {
  489. //ждем весь bm.recent
  490. while (!bookManager.loaded)
  491. await utils.sleep(100);
  492. newRecent = {rev: this.cachedRecent.rev + 1, data: _.cloneDeep(bm.recent)};
  493. newRecentPatch = {rev: this.cachedRecentPatch.rev + 1, data: {}};
  494. newRecentMod = {rev: this.cachedRecentMod.rev + 1, data: {}};
  495. needSaveRecent = true;
  496. needSaveRecentPatch = true;
  497. needSaveRecentMod = true;
  498. }
  499. //query
  500. let query = {};
  501. if (needSaveRecent) {
  502. query = {recent: newRecent, recentPatch: newRecentPatch, recentMod: newRecentMod};
  503. } else if (needSaveRecentPatch) {
  504. query = {recentPatch: newRecentPatch, recentMod: newRecentMod};
  505. } else {
  506. query = {recentMod: newRecentMod};
  507. }
  508. //сохранение
  509. let result = {state: ''};
  510. try {
  511. result = await this.storageSet(query);
  512. } catch(e) {
  513. this.error(`Ошибка соединения с сервером (${e.message}). Данные не сохранены и могут быть перезаписаны.`);
  514. }
  515. if (result.state == 'reject') {
  516. const res = await this.loadRecent(false, false);
  517. if (res)
  518. this.warning(`Последние изменения отменены. Данные синхронизированы с сервером.`);
  519. if (!recurse && itemKey) {
  520. this.savingRecent = false;
  521. this.saveRecent(itemKey, true);
  522. return;
  523. }
  524. } else if (result.state == 'success') {
  525. if (needSaveRecent && newRecent.rev)
  526. await this.setCachedRecent(newRecent);
  527. if (needSaveRecentPatch && newRecentPatch.rev)
  528. await this.setCachedRecentPatch(newRecentPatch);
  529. if (needSaveRecentMod && newRecentMod.rev)
  530. await this.setCachedRecentMod(newRecentMod);
  531. }
  532. } finally {
  533. this.savingRecent = false;
  534. }
  535. }
  536. async storageCheck(items) {
  537. return await this.storageApi('check', items);
  538. }
  539. async storageGet(items) {
  540. return await this.storageApi('get', items);
  541. }
  542. async storageSet(items, force) {
  543. return await this.storageApi('set', items, force);
  544. }
  545. async storageApi(action, items, force) {
  546. const request = {action, items};
  547. if (force)
  548. request.force = true;
  549. const encodedRequest = await this.encodeStorageItems(request);
  550. return await this.decodeStorageItems(await readerApi.storage(encodedRequest));
  551. }
  552. async encodeStorageItems(request) {
  553. if (!this.hashedStorageKey)
  554. throw new Error('hashedStorageKey is empty');
  555. if (!_.isObject(request.items))
  556. throw new Error('items is not an object');
  557. let result = Object.assign({}, request);
  558. let items = {};
  559. for (const id of Object.keys(request.items)) {
  560. const item = request.items[id];
  561. if (request.action == 'set' && !_.isObject(item.data))
  562. throw new Error('encodeStorageItems: data is not an object');
  563. let encoded = Object.assign({}, item);
  564. if (item.data) {
  565. const comp = utils.pako.deflate(JSON.stringify(item.data), {level: 1});
  566. let encrypted = null;
  567. try {
  568. encrypted = cryptoUtils.aesEncrypt(comp, this.serverStorageKey);
  569. } catch (e) {
  570. throw new Error('encrypt failed');
  571. }
  572. encoded.data = '1' + utils.toBase64(encrypted);
  573. }
  574. items[`${this.hashedStorageKey}.${utils.toBase58(id)}`] = encoded;
  575. }
  576. result.items = items;
  577. return result;
  578. }
  579. async decodeStorageItems(response) {
  580. if (!this.hashedStorageKey)
  581. throw new Error('hashedStorageKey is empty');
  582. let result = Object.assign({}, response);
  583. let items = {};
  584. if (response.items) {
  585. if (!_.isObject(response.items))
  586. throw new Error('items is not an object');
  587. for (const id of Object.keys(response.items)) {
  588. const item = response.items[id];
  589. let decoded = Object.assign({}, item);
  590. if (item.data) {
  591. if (!_.isString(item.data) || !item.data.length)
  592. throw new Error('decodeStorageItems: data is not a string');
  593. if (item.data[0] !== '1')
  594. throw new Error('decodeStorageItems: unknown data format');
  595. const a = utils.fromBase64(item.data.substr(1));
  596. let decrypted = null;
  597. try {
  598. decrypted = cryptoUtils.aesDecrypt(a, this.serverStorageKey);
  599. } catch (e) {
  600. throw new Error('decrypt failed');
  601. }
  602. decoded.data = JSON.parse(utils.pako.inflate(decrypted, {to: 'string'}));
  603. }
  604. const ids = id.split('.');
  605. if (!(ids.length == 2) || !(ids[0] == this.hashedStorageKey))
  606. throw new Error(`decodeStorageItems: bad id - ${id}`);
  607. items[utils.fromBase58(ids[1])] = decoded;
  608. }
  609. }
  610. result.items = items;
  611. return result;
  612. }
  613. }
  614. //-----------------------------------------------------------------------------
  615. </script>