ServerStorage.vue 22 KB

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