ServerStorage.vue 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  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. const maxSetTries = 5;
  14. export default @Component({
  15. watch: {
  16. profiles: function() {
  17. this.saveProfiles();
  18. },
  19. },
  20. })
  21. class ServerStorage extends Vue {
  22. created() {
  23. this.commit = this.$store.commit;
  24. }
  25. async init() {
  26. if (!this.serverStorageKey) {
  27. //генерируем новый ключ
  28. this.generateNewServerStorageKey();
  29. }
  30. this.hashedStorageKey = utils.toBase58(await cryptoUtils.sha256(this.serverStorageKey));
  31. await this.loadProfiles();
  32. }
  33. get settings() {
  34. return this.$store.state.reader.settings;
  35. }
  36. get serverStorageKey() {
  37. return this.$store.state.reader.serverStorageKey;
  38. }
  39. get profiles() {
  40. return this.$store.state.reader.profiles;
  41. }
  42. get profilesRev() {
  43. return this.$store.state.reader.profilesRev;
  44. }
  45. notifySuccessIfNeeded(rev1, rev2) {
  46. if (rev1 != rev2)
  47. this.$notify.success({message: 'Данные синхронизированы с сервером'});
  48. }
  49. warning(message) {
  50. this.$notify.warning({message});
  51. }
  52. error(message) {
  53. this.$notify.error({message});
  54. }
  55. async loadProfiles() {
  56. let prof = await this.storageGet({'profiles': {}});
  57. if (prof.state == 'success') {
  58. const oldRev = this.profilesRev;
  59. prof = prof.items.profiles;
  60. this.commit('reader/setProfiles', prof.data);
  61. this.commit('reader/setProfilesRev', prof.rev);
  62. this.oldProfiles = this.profiles;
  63. this.notifySuccessIfNeeded(oldRev, prof.rev);
  64. } else {
  65. this.warning(`Неверный ответ сервера: ${prof.state}`);
  66. }
  67. }
  68. async saveProfiles() {
  69. if (!this.savingProfiles) {
  70. this.savingProfiles = true;
  71. const diff = utils.getObjDiff(this.oldProfiles, this.profiles);
  72. let result = {state: ''};
  73. let tries = 0;
  74. while (result.state != 'success' && tries < maxSetTries) {
  75. result = await this.storageSet({'profiles': {rev: this.profilesRev + 1, data: this.profiles}});
  76. if (result.state == 'reject') {
  77. await this.loadProfiles();
  78. const newProfiles = utils.applyObjDiff(this.profiles, diff);
  79. this.commit('reader/setProfiles', newProfiles);
  80. this.commit('reader/setProfilesRev', result.items.profiles.rev);
  81. }
  82. tries++;
  83. }
  84. this.commit('reader/setProfilesRev', this.profilesRev + 1);
  85. if (tries >= maxSetTries) {
  86. throw new Error('Не удалось отправить данные на сервер');
  87. }
  88. this.savingProfiles = false;
  89. }
  90. }
  91. generateNewServerStorageKey() {
  92. const key = utils.toBase58(utils.randomArray(32));
  93. this.commit('reader/setServerStorageKey', key);
  94. }
  95. async storageCheck(items) {
  96. return await this.storageApi('check', items);
  97. }
  98. async storageGet(items) {
  99. return await this.storageApi('get', items);
  100. }
  101. async storageSet(items, force) {
  102. return await this.storageApi('set', items, force);
  103. }
  104. async storageApi(action, items, force) {
  105. const request = {action, items};
  106. if (force)
  107. request.force = true;
  108. const encodedRequest = await this.encodeStorageItems(request);
  109. return await this.decodeStorageItems(await readerApi.storage(encodedRequest));
  110. }
  111. async encodeStorageItems(request) {
  112. if (!this.hashedStorageKey)
  113. throw new Error('hashedStorageKey is empty');
  114. if (!_.isObject(request.items))
  115. throw new Error('items is not an object');
  116. let result = Object.assign({}, request);
  117. let items = {};
  118. for (const id of Object.keys(request.items)) {
  119. const item = request.items[id];
  120. if (request.action == 'set' && !_.isObject(item.data))
  121. throw new Error('encodeStorageItems: data is not an object');
  122. let encoded = Object.assign({}, item);
  123. if (item.data) {
  124. const comp = utils.pako.deflate(JSON.stringify(item.data), {level: 1});
  125. let encrypted = null;
  126. try {
  127. encrypted = await cryptoUtils.aesEncrypt(comp, this.serverStorageKey);
  128. } catch (e) {
  129. throw new Error('encrypt failed');
  130. }
  131. encoded.data = '1' + utils.toBase64(encrypted);
  132. }
  133. items[`${this.hashedStorageKey}.${utils.toBase58(id)}`] = encoded;
  134. }
  135. result.items = items;
  136. return result;
  137. }
  138. async decodeStorageItems(response) {
  139. if (!this.hashedStorageKey)
  140. throw new Error('hashedStorageKey is empty');
  141. let result = Object.assign({}, response);
  142. let items = {};
  143. if (response.items) {
  144. if (!_.isObject(response.items))
  145. throw new Error('items is not an object');
  146. for (const id of Object.keys(response.items)) {
  147. const item = response.items[id];
  148. let decoded = Object.assign({}, item);
  149. if (item.data) {
  150. if (!_.isString(item.data) || !item.data.length)
  151. throw new Error('decodeStorageItems: data is not a string');
  152. if (item.data[0] !== '1')
  153. throw new Error('decodeStorageItems: unknown data format');
  154. const a = utils.fromBase64(item.data.substr(1));
  155. let decrypted = null;
  156. try {
  157. decrypted = await cryptoUtils.aesDecrypt(a, this.serverStorageKey);
  158. } catch (e) {
  159. throw new Error('decrypt failed');
  160. }
  161. decoded.data = JSON.parse(utils.pako.inflate(decrypted, {to: 'string'}));
  162. }
  163. const ids = id.split('.');
  164. if (!(ids.length == 2) || !(ids[0] == this.hashedStorageKey))
  165. throw new Error(`decodeStorageItems: bad id - ${id}`);
  166. items[utils.fromBase58(ids[1])] = decoded;
  167. }
  168. }
  169. result.items = items;
  170. return result;
  171. }
  172. }
  173. //-----------------------------------------------------------------------------
  174. </script>