ServerStorage.vue 11 KB

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