ServerStorage.vue 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  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. get showServerStorageMessages() {
  94. return this.settings.showServerStorageMessages;
  95. }
  96. checkCurrentProfile() {
  97. if (!this.profiles[this.currentProfile]) {
  98. this.commit('reader/setCurrentProfile', '');
  99. }
  100. }
  101. notifySuccessIfNeeded(rev1, rev2) {
  102. if (rev1 != rev2)
  103. this.success('Данные синхронизированы с сервером');
  104. }
  105. success(message) {
  106. if (this.showServerStorageMessages)
  107. this.$notify.success({message});
  108. }
  109. warning(message) {
  110. if (this.showServerStorageMessages)
  111. this.$notify.warning({message});
  112. }
  113. error(message) {
  114. if (this.showServerStorageMessages)
  115. this.$notify.error({message});
  116. }
  117. async loadSettings() {
  118. if (!this.serverSyncEnabled || !this.currentProfile)
  119. return;
  120. const setsId = `settings-${this.currentProfile}`;
  121. let sets = null;
  122. try {
  123. sets = await this.storageGet({[setsId]: {}});
  124. } catch(e) {
  125. this.error(`Ошибка соединения с сервером: ${e.message}`);
  126. return;
  127. }
  128. if (sets.state == 'success') {
  129. const oldRev = this.settingsRev[setsId] || 0;
  130. sets = sets.items[setsId];
  131. if (sets.rev == 0)
  132. sets.data = {};
  133. this.oldSettings = _.cloneDeep(sets.data);
  134. this.commit('reader/setSettings', sets.data);
  135. this.commit('reader/setSettingsRev', {[setsId]: sets.rev});
  136. this.notifySuccessIfNeeded(oldRev, sets.rev);
  137. } else {
  138. this.warning(`Неверный ответ сервера: ${sets.state}`);
  139. }
  140. }
  141. async saveSettings() {
  142. if (!this.serverSyncEnabled || !this.currentProfile || this.savingSettings)
  143. return;
  144. const diff = utils.getObjDiff(this.oldSettings, this.settings);
  145. if (utils.isEmptyObjDiff(diff))
  146. return;
  147. this.savingSettings = true;
  148. try {
  149. const setsId = `settings-${this.currentProfile}`;
  150. let result = {state: ''};
  151. let tries = 0;
  152. while (result.state != 'success' && tries < maxSetTries) {
  153. const oldRev = this.settingsRev[setsId] || 0;
  154. try {
  155. result = await this.storageSet({[setsId]: {rev: oldRev + 1, data: this.settings}});
  156. } catch(e) {
  157. this.savingSettings = false;
  158. this.error(`Ошибка соединения с сервером (${e.message}). Данные не сохранены и могут быть перезаписаны.`);
  159. return;
  160. }
  161. if (result.state == 'reject') {
  162. await this.loadSettings();
  163. const newSettings = utils.applyObjDiff(this.settings, diff);
  164. this.commit('reader/setSettings', newSettings);
  165. }
  166. tries++;
  167. }
  168. if (tries >= maxSetTries) {
  169. //отменять изменения не будем, просто предупредим
  170. //this.commit('reader/setSettings', this.oldSettings);
  171. console.error(result);
  172. this.error('Не удалось отправить настройки на сервер. Данные не сохранены и могут быть перезаписаны.');
  173. } else {
  174. this.oldSettings = _.cloneDeep(this.settings);
  175. this.commit('reader/setSettingsRev', {[setsId]: this.settingsRev[setsId] + 1});
  176. }
  177. } finally {
  178. this.savingSettings = false;
  179. }
  180. }
  181. async loadProfiles() {
  182. if (!this.serverSyncEnabled)
  183. return;
  184. let prof = null;
  185. try {
  186. prof = await this.storageGet({'profiles': {}});
  187. } catch(e) {
  188. this.error(`Ошибка соединения с сервером: ${e.message}`);
  189. return;
  190. }
  191. if (prof.state == 'success') {
  192. const oldRev = this.profilesRev;
  193. prof = prof.items.profiles;
  194. if (prof.rev == 0)
  195. prof.data = {};
  196. this.oldProfiles = _.cloneDeep(prof.data);
  197. this.commit('reader/setProfiles', prof.data);
  198. this.commit('reader/setProfilesRev', prof.rev);
  199. this.notifySuccessIfNeeded(oldRev, prof.rev);
  200. } else {
  201. this.warning(`Неверный ответ сервера: ${prof.state}`);
  202. }
  203. }
  204. async saveProfiles() {
  205. if (!this.serverSyncEnabled || this.savingProfiles)
  206. return;
  207. const diff = utils.getObjDiff(this.oldProfiles, this.profiles);
  208. if (utils.isEmptyObjDiff(diff))
  209. return;
  210. this.savingProfiles = true;
  211. try {
  212. let result = {state: ''};
  213. let tries = 0;
  214. while (result.state != 'success' && tries < maxSetTries) {
  215. try {
  216. result = await this.storageSet({'profiles': {rev: this.profilesRev + 1, data: this.profiles}});
  217. } catch(e) {
  218. this.savingProfiles = false;
  219. this.commit('reader/setProfiles', this.oldProfiles);
  220. this.checkCurrentProfile();
  221. this.error(`Ошибка соединения с сервером: (${e.message}). Изменения отменены.`);
  222. return;
  223. }
  224. if (result.state == 'reject') {
  225. await this.loadProfiles();
  226. const newProfiles = utils.applyObjDiff(this.profiles, diff);
  227. this.commit('reader/setProfiles', newProfiles);
  228. }
  229. tries++;
  230. }
  231. if (tries >= maxSetTries) {
  232. this.commit('reader/setProfiles', this.oldProfiles);
  233. this.checkCurrentProfile();
  234. console.error(result);
  235. this.error('Не удалось отправить данные на сервер. Изменения отменены.');
  236. } else {
  237. this.oldProfiles = _.cloneDeep(this.profiles);
  238. this.commit('reader/setProfilesRev', this.profilesRev + 1);
  239. }
  240. } finally {
  241. this.savingProfiles = false;
  242. }
  243. }
  244. async generateNewServerStorageKey() {
  245. const key = utils.toBase58(utils.randomArray(32));
  246. this.commit('reader/setServerStorageKey', key);
  247. await this.serverStorageKeyChanged();
  248. }
  249. async storageCheck(items) {
  250. return await this.storageApi('check', items);
  251. }
  252. async storageGet(items) {
  253. return await this.storageApi('get', items);
  254. }
  255. async storageSet(items, force) {
  256. return await this.storageApi('set', items, force);
  257. }
  258. async storageApi(action, items, force) {
  259. const request = {action, items};
  260. if (force)
  261. request.force = true;
  262. const encodedRequest = await this.encodeStorageItems(request);
  263. return await this.decodeStorageItems(await readerApi.storage(encodedRequest));
  264. }
  265. async encodeStorageItems(request) {
  266. if (!this.hashedStorageKey)
  267. throw new Error('hashedStorageKey is empty');
  268. if (!_.isObject(request.items))
  269. throw new Error('items is not an object');
  270. let result = Object.assign({}, request);
  271. let items = {};
  272. for (const id of Object.keys(request.items)) {
  273. const item = request.items[id];
  274. if (request.action == 'set' && !_.isObject(item.data))
  275. throw new Error('encodeStorageItems: data is not an object');
  276. let encoded = Object.assign({}, item);
  277. if (item.data) {
  278. const comp = utils.pako.deflate(JSON.stringify(item.data), {level: 1});
  279. let encrypted = null;
  280. try {
  281. encrypted = cryptoUtils.aesEncrypt(comp, this.serverStorageKey);
  282. } catch (e) {
  283. throw new Error('encrypt failed');
  284. }
  285. encoded.data = '1' + utils.toBase64(encrypted);
  286. }
  287. items[`${this.hashedStorageKey}.${utils.toBase58(id)}`] = encoded;
  288. }
  289. result.items = items;
  290. return result;
  291. }
  292. async decodeStorageItems(response) {
  293. if (!this.hashedStorageKey)
  294. throw new Error('hashedStorageKey is empty');
  295. let result = Object.assign({}, response);
  296. let items = {};
  297. if (response.items) {
  298. if (!_.isObject(response.items))
  299. throw new Error('items is not an object');
  300. for (const id of Object.keys(response.items)) {
  301. const item = response.items[id];
  302. let decoded = Object.assign({}, item);
  303. if (item.data) {
  304. if (!_.isString(item.data) || !item.data.length)
  305. throw new Error('decodeStorageItems: data is not a string');
  306. if (item.data[0] !== '1')
  307. throw new Error('decodeStorageItems: unknown data format');
  308. const a = utils.fromBase64(item.data.substr(1));
  309. let decrypted = null;
  310. try {
  311. decrypted = cryptoUtils.aesDecrypt(a, this.serverStorageKey);
  312. } catch (e) {
  313. throw new Error('decrypt failed');
  314. }
  315. decoded.data = JSON.parse(utils.pako.inflate(decrypted, {to: 'string'}));
  316. }
  317. const ids = id.split('.');
  318. if (!(ids.length == 2) || !(ids[0] == this.hashedStorageKey))
  319. throw new Error(`decodeStorageItems: bad id - ${id}`);
  320. items[utils.fromBase58(ids[1])] = decoded;
  321. }
  322. }
  323. result.items = items;
  324. return result;
  325. }
  326. }
  327. //-----------------------------------------------------------------------------
  328. </script>