ServerStorage.vue 8.0 KB

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