ServerStorage.vue 21 KB

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