ServerStorage.vue 7.4 KB

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