ServerStorage.vue 7.5 KB

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