ServerStorage.vue 22 KB

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