ServerStorage.vue 12 KB

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