ServerStorage.vue 7.5 KB

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