ServerStorage.vue 11 KB

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