You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

PersistenceRegistry.ts 7.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  1. /* eslint-disable import/order */
  2. // @ts-ignore
  3. import Bourne from '@hapi/bourne';
  4. // @ts-ignore
  5. import { jitsiLocalStorage } from '@jitsi/js-utils';
  6. import md5 from 'js-md5';
  7. // @ts-ignore
  8. import logger from './logger';
  9. declare let __DEV__: any;
  10. /**
  11. * Mixed type of the element (subtree) config. If it's a {@code boolean} (and is
  12. * {@code true}), we persist the entire subtree. If it's an {@code Object}, we
  13. * perist a filtered subtree based on the properties of the config object.
  14. */
  15. declare type ElementConfig = boolean | Object;
  16. /**
  17. * The type of the name-config pairs stored in {@code PersistenceRegistry}.
  18. */
  19. declare type PersistencyConfigMap = { [name: string]: ElementConfig };
  20. /**
  21. * A registry to allow features to register their redux store subtree to be
  22. * persisted and also handles the persistency calls too.
  23. */
  24. class PersistenceRegistry {
  25. _checksum = '';
  26. _defaultStates: { [name: string ]: Object|undefined} = {};
  27. _elements: PersistencyConfigMap = {};
  28. /**
  29. * Returns the persisted redux state. Takes the {@link #_elements} into
  30. * account as we may have persisted something in the past that we don't want
  31. * to retrieve anymore. The next {@link #persistState} will remove such
  32. * values.
  33. *
  34. * @returns {Object}
  35. */
  36. getPersistedState() {
  37. const filteredPersistedState: any = {};
  38. // localStorage key per feature
  39. for (const subtreeName of Object.keys(this._elements)) {
  40. // Assumes that the persisted value is stored under the same key as
  41. // the feature's redux state name.
  42. const persistedSubtree
  43. = this._getPersistedSubtree(
  44. subtreeName,
  45. this._elements[subtreeName],
  46. this._defaultStates[subtreeName]);
  47. if (persistedSubtree !== undefined) {
  48. filteredPersistedState[subtreeName] = persistedSubtree;
  49. }
  50. }
  51. // Initialize the checksum.
  52. this._checksum = this._calculateChecksum(filteredPersistedState);
  53. if (typeof __DEV__ !== 'undefined' && __DEV__) {
  54. logger.info('redux state rehydrated as', filteredPersistedState);
  55. }
  56. return filteredPersistedState;
  57. }
  58. /**
  59. * Initiates a persist operation, but its execution will depend on the
  60. * current checksums (checks changes).
  61. *
  62. * @param {Object} state - The redux state.
  63. * @returns {void}
  64. */
  65. persistState(state: Object) {
  66. const filteredState = this._getFilteredState(state);
  67. const checksum = this._calculateChecksum(filteredState);
  68. if (checksum !== this._checksum) {
  69. for (const subtreeName of Object.keys(filteredState)) {
  70. try {
  71. jitsiLocalStorage.setItem(subtreeName, JSON.stringify(filteredState[subtreeName]));
  72. } catch (error) {
  73. logger.error('Error persisting redux subtree', subtreeName, error);
  74. }
  75. }
  76. logger.info(`redux state persisted. ${this._checksum} -> ${checksum}`);
  77. this._checksum = checksum;
  78. }
  79. }
  80. /**
  81. * Registers a new subtree config to be used for the persistency.
  82. *
  83. * @param {string} name - The name of the subtree the config belongs to.
  84. * @param {ElementConfig} config - The config {@code Object}, or
  85. * {@code boolean} if the entire subtree needs to be persisted.
  86. * @param {Object} defaultState - The default state of the component. If
  87. * it's provided, the rehydrated state will be merged with it before it gets
  88. * pushed into Redux.
  89. * @returns {void}
  90. */
  91. register(
  92. name: string,
  93. config: ElementConfig = true,
  94. defaultState?: Object) {
  95. this._elements[name] = config;
  96. this._defaultStates[name] = defaultState;
  97. }
  98. /**
  99. * Calculates the checksum of a specific state.
  100. *
  101. * @param {Object} state - The redux state to calculate the checksum of.
  102. * @private
  103. * @returns {string} The checksum of the specified {@code state}.
  104. */
  105. _calculateChecksum(state: Object) {
  106. try {
  107. return md5.hex(JSON.stringify(state) || '');
  108. } catch (error) {
  109. logger.error('Error calculating checksum for state', error);
  110. return '';
  111. }
  112. }
  113. /**
  114. * Prepares a filtered state from the actual or the persisted redux state,
  115. * based on this registry.
  116. *
  117. * @param {Object} state - The actual or persisted redux state.
  118. * @private
  119. * @returns {Object}
  120. */
  121. _getFilteredState(state: any): any {
  122. const filteredState: any = {};
  123. for (const name of Object.keys(this._elements)) {
  124. if (state[name]) {
  125. filteredState[name]
  126. = this._getFilteredSubtree(
  127. state[name],
  128. this._elements[name]);
  129. }
  130. }
  131. return filteredState;
  132. }
  133. /**
  134. * Prepares a filtered subtree based on the config for persisting or for
  135. * retrieval.
  136. *
  137. * @param {Object} subtree - The redux state subtree.
  138. * @param {ElementConfig} subtreeConfig - The related config.
  139. * @private
  140. * @returns {Object}
  141. */
  142. _getFilteredSubtree(subtree: any, subtreeConfig: any) {
  143. let filteredSubtree: any;
  144. if (typeof subtreeConfig === 'object') {
  145. // Only a filtered subtree gets persisted as specified by
  146. // subtreeConfig.
  147. filteredSubtree = {};
  148. for (const persistedKey of Object.keys(subtree)) {
  149. if (subtreeConfig[persistedKey]) {
  150. filteredSubtree[persistedKey] = subtree[persistedKey];
  151. }
  152. }
  153. } else if (subtreeConfig) {
  154. // Persist the entire subtree.
  155. filteredSubtree = subtree;
  156. }
  157. return filteredSubtree;
  158. }
  159. /**
  160. * Retrieves a persisted subtree from the storage.
  161. *
  162. * @param {string} subtreeName - The name of the subtree.
  163. * @param {Object} subtreeConfig - The config of the subtree from
  164. * {@link #_elements}.
  165. * @param {Object} subtreeDefaults - The defaults of the persisted subtree.
  166. * @private
  167. * @returns {Object}
  168. */
  169. _getPersistedSubtree(subtreeName: string, subtreeConfig: Object, subtreeDefaults?: Object) {
  170. let persistedSubtree = jitsiLocalStorage.getItem(subtreeName);
  171. if (persistedSubtree) {
  172. try {
  173. persistedSubtree = Bourne.parse(persistedSubtree);
  174. const filteredSubtree
  175. = this._getFilteredSubtree(persistedSubtree, subtreeConfig);
  176. if (filteredSubtree !== undefined) {
  177. return this._mergeDefaults(
  178. filteredSubtree, subtreeDefaults);
  179. }
  180. } catch (error) {
  181. logger.error(
  182. 'Error parsing persisted subtree',
  183. subtreeName,
  184. persistedSubtree,
  185. error);
  186. }
  187. }
  188. return undefined;
  189. }
  190. /**
  191. * Merges the persisted subtree with its defaults before rehydrating the
  192. * values.
  193. *
  194. * @private
  195. * @param {Object} subtree - The Redux subtree.
  196. * @param {?Object} defaults - The defaults, if any.
  197. * @returns {Object}
  198. */
  199. _mergeDefaults(subtree: Object, defaults?: Object) {
  200. if (!defaults) {
  201. return subtree;
  202. }
  203. // If the subtree is an array, we don't need to merge it with the
  204. // defaults, because if it has a value, it will overwrite it, and if
  205. // it's undefined, it won't be even returned, and Redux will natively
  206. // use the default values instead.
  207. if (!Array.isArray(subtree)) {
  208. return {
  209. ...defaults,
  210. ...subtree
  211. };
  212. }
  213. }
  214. }
  215. export default new PersistenceRegistry();