ServerStorage.vue 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621
  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. import localForage from 'localforage';
  14. const ssCacheStore = localForage.createInstance({
  15. name: 'ssCacheStore'
  16. });
  17. export default @Component({
  18. watch: {
  19. serverSyncEnabled: function() {
  20. this.serverSyncEnabledChanged();
  21. },
  22. serverStorageKey: function() {
  23. this.serverStorageKeyChanged(true);
  24. },
  25. settings: function() {
  26. this.debouncedSaveSettings();
  27. },
  28. profiles: function() {
  29. this.saveProfiles();
  30. },
  31. currentProfile: function() {
  32. this.currentProfileChanged(true);
  33. },
  34. },
  35. })
  36. class ServerStorage extends Vue {
  37. created() {
  38. this.inited = false;
  39. this.keyInited = false;
  40. this.commit = this.$store.commit;
  41. this.prevServerStorageKey = null;
  42. this.$root.$on('generateNewServerStorageKey', () => {this.generateNewServerStorageKey()});
  43. this.debouncedSaveSettings = _.debounce(() => {
  44. this.saveSettings();
  45. }, 500);
  46. this.debouncedNotifySuccess = _.debounce(() => {
  47. this.success('Данные синхронизированы с сервером');
  48. }, 1000);
  49. this.oldProfiles = {};
  50. this.oldSettings = {};
  51. }
  52. async init() {
  53. try {
  54. this.cachedRecent = await ssCacheStore.getItem('recent');
  55. if (!this.cachedRecent)
  56. await this.setCachedRecent({rev: 0, data: {}});
  57. this.cachedRecentPatch = await ssCacheStore.getItem('recent-patch');
  58. if (!this.cachedRecentPatch)
  59. await this.setCachedRecentPatch({rev: 0, data: {}});
  60. this.cachedRecentMod = await ssCacheStore.getItem('recent-mod');
  61. if (!this.cachedRecentMod)
  62. await this.setCachedRecentMod({rev: 0, data: {}});
  63. if (!this.serverStorageKey) {
  64. //генерируем новый ключ
  65. await this.generateNewServerStorageKey();
  66. } else {
  67. await this.serverStorageKeyChanged();
  68. }
  69. } finally {
  70. this.inited = true;
  71. }
  72. }
  73. async setCachedRecent(value) {
  74. await ssCacheStore.setItem('recent', value);
  75. this.cachedRecent = value;
  76. }
  77. async setCachedRecentPatch(value) {
  78. await ssCacheStore.setItem('recent-patch', value);
  79. this.cachedRecentPatch = value;
  80. }
  81. async setCachedRecentMod(value) {
  82. await ssCacheStore.setItem('recent-mod', value);
  83. this.cachedRecentMod = value;
  84. }
  85. async generateNewServerStorageKey() {
  86. const key = utils.toBase58(utils.randomArray(32));
  87. this.commit('reader/setServerStorageKey', key);
  88. await this.serverStorageKeyChanged(true);
  89. }
  90. async serverSyncEnabledChanged() {
  91. if (this.serverSyncEnabled) {
  92. this.prevServerStorageKey = null;
  93. if (!this.serverStorageKey) {
  94. //генерируем новый ключ
  95. await this.generateNewServerStorageKey();
  96. } else {
  97. await this.serverStorageKeyChanged(true);
  98. }
  99. }
  100. }
  101. async serverStorageKeyChanged(force) {
  102. if (this.prevServerStorageKey != this.serverStorageKey) {
  103. this.prevServerStorageKey = this.serverStorageKey;
  104. this.hashedStorageKey = utils.toBase58(cryptoUtils.sha256(this.serverStorageKey));
  105. this.keyInited = true;
  106. await this.loadProfiles(force);
  107. this.checkCurrentProfile();
  108. await this.currentProfileChanged(force);
  109. const loadSuccess = await this.loadRecent();
  110. if (loadSuccess && force)
  111. await this.saveRecent();
  112. }
  113. }
  114. async currentProfileChanged(force) {
  115. if (!this.currentProfile)
  116. return;
  117. await this.loadSettings(force);
  118. }
  119. get serverSyncEnabled() {
  120. return this.$store.state.reader.serverSyncEnabled;
  121. }
  122. get settings() {
  123. return this.$store.state.reader.settings;
  124. }
  125. get settingsRev() {
  126. return this.$store.state.reader.settingsRev;
  127. }
  128. get serverStorageKey() {
  129. return this.$store.state.reader.serverStorageKey;
  130. }
  131. get profiles() {
  132. return this.$store.state.reader.profiles;
  133. }
  134. get profilesRev() {
  135. return this.$store.state.reader.profilesRev;
  136. }
  137. get currentProfile() {
  138. return this.$store.state.reader.currentProfile;
  139. }
  140. get showServerStorageMessages() {
  141. return this.settings.showServerStorageMessages;
  142. }
  143. checkCurrentProfile() {
  144. if (!this.profiles[this.currentProfile]) {
  145. this.commit('reader/setCurrentProfile', '');
  146. }
  147. }
  148. success(message) {
  149. if (this.showServerStorageMessages)
  150. this.$notify.success({message});
  151. }
  152. warning(message) {
  153. if (this.showServerStorageMessages && !this.offlineModeActive)
  154. this.$notify.warning({message});
  155. }
  156. error(message) {
  157. if (this.showServerStorageMessages && !this.offlineModeActive)
  158. this.$notify.error({message});
  159. }
  160. async loadSettings(force = false, doNotifySuccess = true) {
  161. if (!this.keyInited || !this.serverSyncEnabled || !this.currentProfile)
  162. return;
  163. const setsId = `settings-${this.currentProfile}`;
  164. const oldRev = this.settingsRev[setsId] || 0;
  165. //проверим ревизию на сервере
  166. if (!force) {
  167. try {
  168. const revs = await this.storageCheck({[setsId]: {}});
  169. if (revs.state == 'success' && revs.items[setsId].rev == oldRev) {
  170. return;
  171. }
  172. } catch(e) {
  173. this.error(`Ошибка соединения с сервером: ${e.message}`);
  174. return;
  175. }
  176. }
  177. let sets = null;
  178. try {
  179. sets = await this.storageGet({[setsId]: {}});
  180. } catch(e) {
  181. this.error(`Ошибка соединения с сервером: ${e.message}`);
  182. return;
  183. }
  184. if (sets.state == 'success') {
  185. sets = sets.items[setsId];
  186. if (sets.rev == 0)
  187. sets.data = {};
  188. this.oldSettings = _.cloneDeep(sets.data);
  189. this.commit('reader/setSettings', sets.data);
  190. this.commit('reader/setSettingsRev', {[setsId]: sets.rev});
  191. if (doNotifySuccess)
  192. this.debouncedNotifySuccess();
  193. } else {
  194. this.warning(`Неверный ответ сервера: ${sets.state}`);
  195. }
  196. }
  197. async saveSettings() {
  198. if (!this.keyInited || !this.serverSyncEnabled || !this.currentProfile || this.savingSettings)
  199. return;
  200. const diff = utils.getObjDiff(this.oldSettings, this.settings);
  201. if (utils.isEmptyObjDiff(diff))
  202. return;
  203. this.savingSettings = true;
  204. try {
  205. const setsId = `settings-${this.currentProfile}`;
  206. let result = {state: ''};
  207. const oldRev = this.settingsRev[setsId] || 0;
  208. try {
  209. result = await this.storageSet({[setsId]: {rev: oldRev + 1, data: this.settings}});
  210. } catch(e) {
  211. this.error(`Ошибка соединения с сервером (${e.message}). Данные не сохранены и могут быть перезаписаны.`);
  212. }
  213. if (result.state == 'reject') {
  214. await this.loadSettings(true, false);
  215. this.warning(`Последние изменения отменены. Данные синхронизированы с сервером.`);
  216. } else if (result.state == 'success') {
  217. this.oldSettings = _.cloneDeep(this.settings);
  218. this.commit('reader/setSettingsRev', {[setsId]: this.settingsRev[setsId] + 1});
  219. }
  220. } finally {
  221. this.savingSettings = false;
  222. }
  223. }
  224. async loadProfiles(force = false, doNotifySuccess = true) {
  225. if (!this.keyInited || !this.serverSyncEnabled)
  226. return;
  227. const oldRev = this.profilesRev;
  228. //проверим ревизию на сервере
  229. if (!force) {
  230. try {
  231. const revs = await this.storageCheck({profiles: {}});
  232. if (revs.state == 'success' && revs.items.profiles.rev == oldRev) {
  233. return;
  234. }
  235. } catch(e) {
  236. this.error(`Ошибка соединения с сервером: ${e.message}`);
  237. return;
  238. }
  239. }
  240. let prof = null;
  241. try {
  242. prof = await this.storageGet({profiles: {}});
  243. } catch(e) {
  244. this.error(`Ошибка соединения с сервером: ${e.message}`);
  245. return;
  246. }
  247. if (prof.state == 'success') {
  248. prof = prof.items.profiles;
  249. if (prof.rev == 0)
  250. prof.data = {};
  251. this.oldProfiles = _.cloneDeep(prof.data);
  252. this.commit('reader/setProfiles', prof.data);
  253. this.commit('reader/setProfilesRev', prof.rev);
  254. this.checkCurrentProfile();
  255. if (doNotifySuccess)
  256. this.debouncedNotifySuccess();
  257. } else {
  258. this.warning(`Неверный ответ сервера: ${prof.state}`);
  259. }
  260. }
  261. async saveProfiles() {
  262. if (!this.keyInited || !this.serverSyncEnabled || this.savingProfiles)
  263. return;
  264. const diff = utils.getObjDiff(this.oldProfiles, this.profiles);
  265. if (utils.isEmptyObjDiff(diff))
  266. return;
  267. //обнуляются профили во время разработки при hotReload, подстраховка
  268. if (!this.$store.state.reader.allowProfilesSave) {
  269. console.error('Сохранение профилей не санкционировано');
  270. return;
  271. }
  272. this.savingProfiles = true;
  273. try {
  274. let result = {state: ''};
  275. try {
  276. result = await this.storageSet({profiles: {rev: this.profilesRev + 1, data: this.profiles}});
  277. } catch(e) {
  278. this.error(`Ошибка соединения с сервером (${e.message}). Данные не сохранены и могут быть перезаписаны.`);
  279. }
  280. if (result.state == 'reject') {
  281. await this.loadProfiles(true, false);
  282. this.warning(`Последние изменения отменены. Данные синхронизированы с сервером.`);
  283. } else if (result.state == 'success') {
  284. this.oldProfiles = _.cloneDeep(this.profiles);
  285. this.commit('reader/setProfilesRev', this.profilesRev + 1);
  286. }
  287. } finally {
  288. this.savingProfiles = false;
  289. }
  290. }
  291. async loadRecent(skipRevCheck = false, doNotifySuccess = true) {
  292. if (!this.keyInited || !this.serverSyncEnabled || this.loadingRecent)
  293. return;
  294. this.loadingRecent = true;
  295. try {
  296. //проверим ревизию на сервере
  297. let query = {recent: {}, recentPatch: {}, recentMod: {}};
  298. let revs = null;
  299. if (!skipRevCheck) {
  300. try {
  301. revs = await this.storageCheck(query);
  302. if (revs.state == 'success') {
  303. if (revs.items.recent.rev != this.cachedRecent.rev) {
  304. //no changes
  305. } else if (revs.items.recentPatch.rev != this.cachedRecentPatch.rev) {
  306. query = {recentPatch: {}, recentMod: {}};
  307. } else if (revs.items.recentMod.rev != this.cachedRecentMod.rev) {
  308. query = {recentMod: {}};
  309. } else
  310. return true;
  311. }
  312. } catch(e) {
  313. this.error(`Ошибка соединения с сервером: ${e.message}`);
  314. return;
  315. }
  316. }
  317. let recent = null;
  318. try {
  319. recent = await this.storageGet(query);
  320. } catch(e) {
  321. this.error(`Ошибка соединения с сервером: ${e.message}`);
  322. return;
  323. }
  324. if (recent.state == 'success') {
  325. let newRecent = recent.items.recent;
  326. let newRecentPatch = recent.items.recentPatch;
  327. let newRecentMod = recent.items.recentMod;
  328. if (!newRecent) {
  329. newRecent = _.cloneDeep(this.cachedRecent);
  330. }
  331. if (!newRecentPatch) {
  332. newRecentPatch = _.cloneDeep(this.cachedRecentPatch);
  333. }
  334. if (!newRecentMod) {
  335. newRecentMod = _.cloneDeep(this.cachedRecentMod);
  336. }
  337. if (newRecent.rev == 0) newRecent.data = {};
  338. if (newRecentPatch.rev == 0) newRecentPatch.data = {};
  339. if (newRecentMod.rev == 0) newRecentMod.data = {};
  340. let result = Object.assign({}, newRecent.data, newRecentPatch.data);
  341. const md = newRecentMod.data;
  342. if (md.key && result[md.key])
  343. result[md.key] = utils.applyObjDiff(result[md.key], md.mod);
  344. if (newRecent.rev != this.cachedRecent.rev)
  345. await this.setCachedRecent(newRecent);
  346. if (newRecentPatch.rev != this.cachedRecentPatch.rev)
  347. await this.setCachedRecentPatch(newRecentPatch);
  348. if (newRecentMod.rev != this.cachedRecentMod.rev)
  349. await this.setCachedRecentMod(newRecentMod);
  350. if (!bookManager.loaded) {
  351. this.warning('Ожидание загрузки списка книг перед синхронизацией');
  352. while (!bookManager.loaded) await utils.sleep(100);
  353. }
  354. await bookManager.setRecent(result);
  355. } else {
  356. this.warning(`Неверный ответ сервера: ${recent.state}`);
  357. return;
  358. }
  359. if (doNotifySuccess)
  360. this.debouncedNotifySuccess();
  361. } finally {
  362. this.loadingRecent = false;
  363. }
  364. return true;
  365. }
  366. async saveRecent(itemKey, recurse) {
  367. if (!this.keyInited || !this.serverSyncEnabled || this.savingRecent)
  368. return;
  369. this.savingRecent = true;
  370. try {
  371. const bm = bookManager;
  372. let needSaveRecent = false;
  373. let needSaveRecentPatch = false;
  374. let needSaveRecentMod = false;
  375. //newRecentMod
  376. let newRecentMod = {};
  377. if (itemKey && this.cachedRecentPatch.data[itemKey] && this.prevItemKey == itemKey) {
  378. newRecentMod = _.cloneDeep(this.cachedRecentMod);
  379. newRecentMod.rev++;
  380. newRecentMod.data.key = itemKey;
  381. newRecentMod.data.mod = utils.getObjDiff(this.cachedRecentPatch.data[itemKey], bm.recent[itemKey]);
  382. needSaveRecentMod = true;
  383. }
  384. this.prevItemKey = itemKey;
  385. //newRecentPatch
  386. let newRecentPatch = {};
  387. if (itemKey && !needSaveRecentMod) {
  388. newRecentPatch = _.cloneDeep(this.cachedRecentPatch);
  389. newRecentPatch.rev++;
  390. newRecentPatch.data[itemKey] = bm.recent[itemKey];
  391. let applyMod = this.cachedRecentMod.data;
  392. if (applyMod && applyMod.key && newRecentPatch.data[applyMod.key])
  393. newRecentPatch.data[applyMod.key] = utils.applyObjDiff(newRecentPatch.data[applyMod.key], applyMod.mod);
  394. newRecentMod = {rev: this.cachedRecentMod.rev + 1, data: {}};
  395. needSaveRecentPatch = true;
  396. needSaveRecentMod = true;
  397. }
  398. //newRecent
  399. let newRecent = {};
  400. if (!itemKey || (needSaveRecentPatch && Object.keys(newRecentPatch.data).length > 10)) {
  401. newRecent = {rev: this.cachedRecent.rev + 1, data: bm.recent};
  402. newRecentPatch = {rev: this.cachedRecentPatch.rev + 1, data: {}};
  403. newRecentMod = {rev: this.cachedRecentMod.rev + 1, data: {}};
  404. needSaveRecent = true;
  405. needSaveRecentPatch = true;
  406. needSaveRecentMod = true;
  407. }
  408. //query
  409. let query = {};
  410. if (needSaveRecent) {
  411. query = {recent: newRecent, recentPatch: newRecentPatch, recentMod: newRecentMod};
  412. } else if (needSaveRecentPatch) {
  413. query = {recentPatch: newRecentPatch, recentMod: newRecentMod};
  414. } else {
  415. query = {recentMod: newRecentMod};
  416. }
  417. //сохранение
  418. let result = {state: ''};
  419. try {
  420. result = await this.storageSet(query);
  421. } catch(e) {
  422. this.error(`Ошибка соединения с сервером (${e.message}). Данные не сохранены и могут быть перезаписаны.`);
  423. }
  424. if (result.state == 'reject') {
  425. await this.loadRecent(false, false);
  426. this.warning(`Последние изменения отменены. Данные синхронизированы с сервером.`);
  427. if (!recurse && itemKey) {
  428. this.savingRecent = false;
  429. this.saveRecent(itemKey, true);
  430. return;
  431. }
  432. } else if (result.state == 'success') {
  433. if (needSaveRecent && newRecent.rev)
  434. await this.setCachedRecent(newRecent);
  435. if (needSaveRecentPatch && newRecentPatch.rev)
  436. await this.setCachedRecentPatch(newRecentPatch);
  437. if (needSaveRecentMod && newRecentMod.rev)
  438. await this.setCachedRecentMod(newRecentMod);
  439. }
  440. } finally {
  441. this.savingRecent = false;
  442. }
  443. }
  444. async storageCheck(items) {
  445. return await this.storageApi('check', items);
  446. }
  447. async storageGet(items) {
  448. return await this.storageApi('get', items);
  449. }
  450. async storageSet(items, force) {
  451. return await this.storageApi('set', items, force);
  452. }
  453. async storageApi(action, items, force) {
  454. const request = {action, items};
  455. if (force)
  456. request.force = true;
  457. const encodedRequest = await this.encodeStorageItems(request);
  458. return await this.decodeStorageItems(await readerApi.storage(encodedRequest));
  459. }
  460. async encodeStorageItems(request) {
  461. if (!this.hashedStorageKey)
  462. throw new Error('hashedStorageKey is empty');
  463. if (!_.isObject(request.items))
  464. throw new Error('items is not an object');
  465. let result = Object.assign({}, request);
  466. let items = {};
  467. for (const id of Object.keys(request.items)) {
  468. const item = request.items[id];
  469. if (request.action == 'set' && !_.isObject(item.data))
  470. throw new Error('encodeStorageItems: data is not an object');
  471. let encoded = Object.assign({}, item);
  472. if (item.data) {
  473. const comp = utils.pako.deflate(JSON.stringify(item.data), {level: 1});
  474. let encrypted = null;
  475. try {
  476. encrypted = cryptoUtils.aesEncrypt(comp, this.serverStorageKey);
  477. } catch (e) {
  478. throw new Error('encrypt failed');
  479. }
  480. encoded.data = '1' + utils.toBase64(encrypted);
  481. }
  482. items[`${this.hashedStorageKey}.${utils.toBase58(id)}`] = encoded;
  483. }
  484. result.items = items;
  485. return result;
  486. }
  487. async decodeStorageItems(response) {
  488. if (!this.hashedStorageKey)
  489. throw new Error('hashedStorageKey is empty');
  490. let result = Object.assign({}, response);
  491. let items = {};
  492. if (response.items) {
  493. if (!_.isObject(response.items))
  494. throw new Error('items is not an object');
  495. for (const id of Object.keys(response.items)) {
  496. const item = response.items[id];
  497. let decoded = Object.assign({}, item);
  498. if (item.data) {
  499. if (!_.isString(item.data) || !item.data.length)
  500. throw new Error('decodeStorageItems: data is not a string');
  501. if (item.data[0] !== '1')
  502. throw new Error('decodeStorageItems: unknown data format');
  503. const a = utils.fromBase64(item.data.substr(1));
  504. let decrypted = null;
  505. try {
  506. decrypted = cryptoUtils.aesDecrypt(a, this.serverStorageKey);
  507. } catch (e) {
  508. throw new Error('decrypt failed');
  509. }
  510. decoded.data = JSON.parse(utils.pako.inflate(decrypted, {to: 'string'}));
  511. }
  512. const ids = id.split('.');
  513. if (!(ids.length == 2) || !(ids[0] == this.hashedStorageKey))
  514. throw new Error(`decodeStorageItems: bad id - ${id}`);
  515. items[utils.fromBase58(ids[1])] = decoded;
  516. }
  517. }
  518. result.items = items;
  519. return result;
  520. }
  521. }
  522. //-----------------------------------------------------------------------------
  523. </script>