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.js 8.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. // @flow
  2. import { jitsiLocalStorage } from '@jitsi/js-utils';
  3. import md5 from 'js-md5';
  4. import logger from './logger';
  5. declare var __DEV__;
  6. /**
  7. * The name of the {@code localStorage} store where the app persists its values.
  8. */
  9. const PERSISTED_STATE_NAME = 'jitsi-state';
  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: string;
  26. _defaultStates: { [name: string ]: ?Object} = {};
  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 retreive anymore. The next {@link #persistState} will remove such
  32. * values.
  33. *
  34. * @returns {Object}
  35. */
  36. getPersistedState() {
  37. let filteredPersistedState = {};
  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. // TODO We'll need to introduce functions later that can control the
  43. // persist key's name. Similar to control serialization and
  44. // deserialization. But that should be a straightforward change.
  45. const persistedSubtree
  46. = this._getPersistedSubtree(
  47. subtreeName,
  48. this._elements[subtreeName],
  49. this._defaultStates[subtreeName]);
  50. if (persistedSubtree !== undefined) {
  51. filteredPersistedState[subtreeName] = persistedSubtree;
  52. }
  53. }
  54. // legacy
  55. if (Object.keys(filteredPersistedState).length === 0) {
  56. let persistedState = jitsiLocalStorage.getItem(PERSISTED_STATE_NAME);
  57. if (persistedState) {
  58. try {
  59. persistedState = JSON.parse(persistedState);
  60. } catch (error) {
  61. logger.error(
  62. 'Error parsing persisted state',
  63. persistedState,
  64. error);
  65. persistedState = {};
  66. }
  67. filteredPersistedState = this._getFilteredState(persistedState);
  68. // Store into the new format and delete the old format so that
  69. // it's not used again.
  70. this.persistState(filteredPersistedState);
  71. jitsiLocalStorage.removeItem(PERSISTED_STATE_NAME);
  72. }
  73. }
  74. // Initialize the checksum.
  75. this._checksum = this._calculateChecksum(filteredPersistedState);
  76. if (typeof __DEV__ !== 'undefined' && __DEV__) {
  77. logger.info('redux state rehydrated as', filteredPersistedState);
  78. }
  79. return filteredPersistedState;
  80. }
  81. /**
  82. * Initiates a persist operation, but its execution will depend on the
  83. * current checksums (checks changes).
  84. *
  85. * @param {Object} state - The redux state.
  86. * @returns {void}
  87. */
  88. persistState(state: Object) {
  89. const filteredState = this._getFilteredState(state);
  90. const checksum = this._calculateChecksum(filteredState);
  91. if (checksum !== this._checksum) {
  92. for (const subtreeName of Object.keys(filteredState)) {
  93. try {
  94. jitsiLocalStorage.setItem(subtreeName, JSON.stringify(filteredState[subtreeName]));
  95. } catch (error) {
  96. logger.error('Error persisting redux subtree', subtreeName, error);
  97. }
  98. }
  99. logger.info(`redux state persisted. ${this._checksum} -> ${checksum}`);
  100. this._checksum = checksum;
  101. }
  102. }
  103. /**
  104. * Registers a new subtree config to be used for the persistency.
  105. *
  106. * @param {string} name - The name of the subtree the config belongs to.
  107. * @param {ElementConfig} config - The config {@code Object}, or
  108. * {@code boolean} if the entire subtree needs to be persisted.
  109. * @param {Object} defaultState - The default state of the component. If
  110. * it's provided, the rehydrated state will be merged with it before it gets
  111. * pushed into Redux.
  112. * @returns {void}
  113. */
  114. register(
  115. name: string,
  116. config?: ElementConfig = true,
  117. defaultState?: Object) {
  118. this._elements[name] = config;
  119. this._defaultStates[name] = defaultState;
  120. }
  121. /**
  122. * Calculates the checksum of a specific state.
  123. *
  124. * @param {Object} state - The redux state to calculate the checksum of.
  125. * @private
  126. * @returns {string} The checksum of the specified {@code state}.
  127. */
  128. _calculateChecksum(state: Object) {
  129. try {
  130. return md5.hex(JSON.stringify(state) || '');
  131. } catch (error) {
  132. logger.error('Error calculating checksum for state', error);
  133. return '';
  134. }
  135. }
  136. /**
  137. * Prepares a filtered state from the actual or the persisted redux state,
  138. * based on this registry.
  139. *
  140. * @param {Object} state - The actual or persisted redux state.
  141. * @private
  142. * @returns {Object}
  143. */
  144. _getFilteredState(state: Object) {
  145. const filteredState = {};
  146. for (const name of Object.keys(this._elements)) {
  147. if (state[name]) {
  148. filteredState[name]
  149. = this._getFilteredSubtree(
  150. state[name],
  151. this._elements[name]);
  152. }
  153. }
  154. return filteredState;
  155. }
  156. /**
  157. * Prepares a filtered subtree based on the config for persisting or for
  158. * retrieval.
  159. *
  160. * @param {Object} subtree - The redux state subtree.
  161. * @param {ElementConfig} subtreeConfig - The related config.
  162. * @private
  163. * @returns {Object}
  164. */
  165. _getFilteredSubtree(subtree, subtreeConfig) {
  166. let filteredSubtree;
  167. if (typeof subtreeConfig === 'object') {
  168. // Only a filtered subtree gets persisted as specified by
  169. // subtreeConfig.
  170. filteredSubtree = {};
  171. for (const persistedKey of Object.keys(subtree)) {
  172. if (subtreeConfig[persistedKey]) {
  173. filteredSubtree[persistedKey] = subtree[persistedKey];
  174. }
  175. }
  176. } else if (subtreeConfig) {
  177. // Persist the entire subtree.
  178. filteredSubtree = subtree;
  179. }
  180. return filteredSubtree;
  181. }
  182. /**
  183. * Retreives a persisted subtree from the storage.
  184. *
  185. * @param {string} subtreeName - The name of the subtree.
  186. * @param {Object} subtreeConfig - The config of the subtree from
  187. * {@link #_elements}.
  188. * @param {Object} subtreeDefaults - The defaults of the persisted subtree.
  189. * @private
  190. * @returns {Object}
  191. */
  192. _getPersistedSubtree(subtreeName, subtreeConfig, subtreeDefaults) {
  193. let persistedSubtree = jitsiLocalStorage.getItem(subtreeName);
  194. if (persistedSubtree) {
  195. try {
  196. persistedSubtree = JSON.parse(persistedSubtree);
  197. const filteredSubtree
  198. = this._getFilteredSubtree(persistedSubtree, subtreeConfig);
  199. if (filteredSubtree !== undefined) {
  200. return this._mergeDefaults(
  201. filteredSubtree, subtreeDefaults);
  202. }
  203. } catch (error) {
  204. logger.error(
  205. 'Error parsing persisted subtree',
  206. subtreeName,
  207. persistedSubtree,
  208. error);
  209. }
  210. }
  211. return undefined;
  212. }
  213. /**
  214. * Merges the persisted subtree with its defaults before rehydrating the
  215. * values.
  216. *
  217. * @private
  218. * @param {Object} subtree - The Redux subtree.
  219. * @param {?Object} defaults - The defaults, if any.
  220. * @returns {Object}
  221. */
  222. _mergeDefaults(subtree: Object, defaults: ?Object) {
  223. if (!defaults) {
  224. return subtree;
  225. }
  226. // If the subtree is an array, we don't need to merge it with the
  227. // defaults, because if it has a value, it will overwrite it, and if
  228. // it's undefined, it won't be even returned, and Redux will natively
  229. // use the default values instead.
  230. if (!Array.isArray(subtree)) {
  231. return {
  232. ...defaults,
  233. ...subtree
  234. };
  235. }
  236. }
  237. }
  238. export default new PersistenceRegistry();