ServerStorage.vue 11 KB

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