ServerStorage.vue 7.0 KB

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