ServerStorage.vue 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  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. this.error('Не удалось отправить настройки на сервер. Данные не сохранены и могут быть перезаписаны.');
  172. } else {
  173. this.oldSettings = _.cloneDeep(this.settings);
  174. this.commit('reader/setSettingsRev', {[setsId]: this.settingsRev[setsId] + 1});
  175. }
  176. } finally {
  177. this.savingSettings = false;
  178. }
  179. }
  180. async loadProfiles() {
  181. if (!this.serverSyncEnabled)
  182. return;
  183. let prof = null;
  184. try {
  185. prof = await this.storageGet({'profiles': {}});
  186. } catch(e) {
  187. this.error(`Ошибка соединения с сервером: ${e.message}`);
  188. return;
  189. }
  190. if (prof.state == 'success') {
  191. const oldRev = this.profilesRev;
  192. prof = prof.items.profiles;
  193. if (prof.rev == 0)
  194. prof.data = {};
  195. this.oldProfiles = _.cloneDeep(prof.data);
  196. this.commit('reader/setProfiles', prof.data);
  197. this.commit('reader/setProfilesRev', prof.rev);
  198. this.notifySuccessIfNeeded(oldRev, prof.rev);
  199. } else {
  200. this.warning(`Неверный ответ сервера: ${prof.state}`);
  201. }
  202. }
  203. async saveProfiles() {
  204. if (!this.serverSyncEnabled || this.savingProfiles)
  205. return;
  206. const diff = utils.getObjDiff(this.oldProfiles, this.profiles);
  207. if (utils.isEmptyObjDiff(diff))
  208. return;
  209. this.savingProfiles = true;
  210. try {
  211. let result = {state: ''};
  212. let tries = 0;
  213. while (result.state != 'success' && tries < maxSetTries) {
  214. try {
  215. result = await this.storageSet({'profiles': {rev: this.profilesRev + 1, data: this.profiles}});
  216. } catch(e) {
  217. this.savingProfiles = false;
  218. this.commit('reader/setProfiles', this.oldProfiles);
  219. this.checkCurrentProfile();
  220. this.error(`Ошибка соединения с сервером: (${e.message}). Изменения отменены.`);
  221. return;
  222. }
  223. if (result.state == 'reject') {
  224. await this.loadProfiles();
  225. const newProfiles = utils.applyObjDiff(this.profiles, diff);
  226. this.commit('reader/setProfiles', newProfiles);
  227. }
  228. tries++;
  229. }
  230. if (tries >= maxSetTries) {
  231. this.commit('reader/setProfiles', this.oldProfiles);
  232. this.checkCurrentProfile();
  233. this.error('Не удалось отправить данные на сервер. Изменения отменены.');
  234. } else {
  235. this.oldProfiles = _.cloneDeep(this.profiles);
  236. this.commit('reader/setProfilesRev', this.profilesRev + 1);
  237. }
  238. } finally {
  239. this.savingProfiles = false;
  240. }
  241. }
  242. async generateNewServerStorageKey() {
  243. const key = utils.toBase58(utils.randomArray(32));
  244. this.commit('reader/setServerStorageKey', key);
  245. await this.serverStorageKeyChanged();
  246. }
  247. async storageCheck(items) {
  248. return await this.storageApi('check', items);
  249. }
  250. async storageGet(items) {
  251. return await this.storageApi('get', items);
  252. }
  253. async storageSet(items, force) {
  254. return await this.storageApi('set', items, force);
  255. }
  256. async storageApi(action, items, force) {
  257. const request = {action, items};
  258. if (force)
  259. request.force = true;
  260. const encodedRequest = await this.encodeStorageItems(request);
  261. return await this.decodeStorageItems(await readerApi.storage(encodedRequest));
  262. }
  263. async encodeStorageItems(request) {
  264. if (!this.hashedStorageKey)
  265. throw new Error('hashedStorageKey is empty');
  266. if (!_.isObject(request.items))
  267. throw new Error('items is not an object');
  268. let result = Object.assign({}, request);
  269. let items = {};
  270. for (const id of Object.keys(request.items)) {
  271. const item = request.items[id];
  272. if (request.action == 'set' && !_.isObject(item.data))
  273. throw new Error('encodeStorageItems: data is not an object');
  274. let encoded = Object.assign({}, item);
  275. if (item.data) {
  276. const comp = utils.pako.deflate(JSON.stringify(item.data), {level: 1});
  277. let encrypted = null;
  278. try {
  279. encrypted = cryptoUtils.aesEncrypt(comp, this.serverStorageKey);
  280. } catch (e) {
  281. throw new Error('encrypt failed');
  282. }
  283. encoded.data = '1' + utils.toBase64(encrypted);
  284. }
  285. items[`${this.hashedStorageKey}.${utils.toBase58(id)}`] = encoded;
  286. }
  287. result.items = items;
  288. return result;
  289. }
  290. async decodeStorageItems(response) {
  291. if (!this.hashedStorageKey)
  292. throw new Error('hashedStorageKey is empty');
  293. let result = Object.assign({}, response);
  294. let items = {};
  295. if (response.items) {
  296. if (!_.isObject(response.items))
  297. throw new Error('items is not an object');
  298. for (const id of Object.keys(response.items)) {
  299. const item = response.items[id];
  300. let decoded = Object.assign({}, item);
  301. if (item.data) {
  302. if (!_.isString(item.data) || !item.data.length)
  303. throw new Error('decodeStorageItems: data is not a string');
  304. if (item.data[0] !== '1')
  305. throw new Error('decodeStorageItems: unknown data format');
  306. const a = utils.fromBase64(item.data.substr(1));
  307. let decrypted = null;
  308. try {
  309. decrypted = cryptoUtils.aesDecrypt(a, this.serverStorageKey);
  310. } catch (e) {
  311. throw new Error('decrypt failed');
  312. }
  313. decoded.data = JSON.parse(utils.pako.inflate(decrypted, {to: 'string'}));
  314. }
  315. const ids = id.split('.');
  316. if (!(ids.length == 2) || !(ids[0] == this.hashedStorageKey))
  317. throw new Error(`decodeStorageItems: bad id - ${id}`);
  318. items[utils.fromBase58(ids[1])] = decoded;
  319. }
  320. }
  321. result.items = items;
  322. return result;
  323. }
  324. }
  325. //-----------------------------------------------------------------------------
  326. </script>