ServerStorage.vue 6.9 KB

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