您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

middleware.js 8.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. // @flow
  2. import RNCalendarEvents from 'react-native-calendar-events';
  3. import { APP_WILL_MOUNT } from '../app';
  4. import { SET_ROOM } from '../base/conference';
  5. import { MiddlewareRegistry } from '../base/redux';
  6. import { APP_LINK_SCHEME, parseURIString } from '../base/util';
  7. import { APP_STATE_CHANGED } from '../mobile/background';
  8. import {
  9. addKnownDomain,
  10. setCalendarAuthorization,
  11. setCalendarEvents
  12. } from './actions';
  13. import { REFRESH_CALENDAR } from './actionTypes';
  14. const logger = require('jitsi-meet-logger').getLogger(__filename);
  15. const FETCH_END_DAYS = 10;
  16. const FETCH_START_DAYS = -1;
  17. const MAX_LIST_LENGTH = 10;
  18. MiddlewareRegistry.register(store => next => action => {
  19. const result = next(action);
  20. switch (action.type) {
  21. case APP_STATE_CHANGED:
  22. _maybeClearAccessStatus(store, action);
  23. break;
  24. case APP_WILL_MOUNT:
  25. _ensureDefaultServer(store);
  26. _fetchCalendarEntries(store, false, false);
  27. break;
  28. case REFRESH_CALENDAR:
  29. _fetchCalendarEntries(store, true, action.forcePermission);
  30. break;
  31. case SET_ROOM:
  32. _parseAndAddKnownDomain(store);
  33. break;
  34. }
  35. return result;
  36. });
  37. /**
  38. * Clears the calendar access status when the app comes back from the
  39. * background. This is needed as some users may never quit the app, but puts it
  40. * into the background and we need to try to request for a permission as often
  41. * as possible, but not annoyingly often.
  42. *
  43. * @param {Object} store - The redux store.
  44. * @param {Object} action - The Redux action.
  45. * @private
  46. * @returns {void}
  47. */
  48. function _maybeClearAccessStatus(store, { appState }) {
  49. if (appState === 'background') {
  50. store.dispatch(setCalendarAuthorization(undefined));
  51. }
  52. }
  53. /**
  54. * Ensures calendar access if possible and resolves the promise if it's granted.
  55. *
  56. * @param {boolean} promptForPermission - Flag to tell the app if it should
  57. * prompt for a calendar permission if it wasn't granted yet.
  58. * @param {Function} dispatch - The Redux dispatch function.
  59. * @private
  60. * @returns {Promise}
  61. */
  62. function _ensureCalendarAccess(promptForPermission, dispatch) {
  63. return new Promise((resolve, reject) => {
  64. RNCalendarEvents.authorizationStatus()
  65. .then(status => {
  66. if (status === 'authorized') {
  67. resolve(true);
  68. } else if (promptForPermission) {
  69. RNCalendarEvents.authorizeEventStore()
  70. .then(result => {
  71. dispatch(setCalendarAuthorization(result));
  72. resolve(result === 'authorized');
  73. })
  74. .catch(reject);
  75. } else {
  76. resolve(false);
  77. }
  78. })
  79. .catch(reject);
  80. });
  81. }
  82. /**
  83. * Ensures presence of the default server in the known domains list.
  84. *
  85. * @param {Object} store - The redux store.
  86. * @private
  87. * @returns {Promise}
  88. */
  89. function _ensureDefaultServer({ dispatch, getState }) {
  90. const state = getState();
  91. const defaultURL
  92. = parseURIString(state['features/app'].app._getDefaultURL());
  93. dispatch(addKnownDomain(defaultURL.host));
  94. }
  95. /**
  96. * Reads the user's calendar and updates the stored entries if need be.
  97. *
  98. * @param {Object} store - The redux store.
  99. * @param {boolean} maybePromptForPermission - Flag to tell the app if it should
  100. * prompt for a calendar permission if it wasn't granted yet.
  101. * @param {boolean|undefined} forcePermission - Whether to force to re-ask for
  102. * the permission or not.
  103. * @private
  104. * @returns {void}
  105. */
  106. function _fetchCalendarEntries(
  107. { dispatch, getState },
  108. maybePromptForPermission,
  109. forcePermission) {
  110. const state = getState()['features/calendar-sync'];
  111. const promptForPermission
  112. = (maybePromptForPermission && !state.authorization)
  113. || forcePermission;
  114. _ensureCalendarAccess(promptForPermission, dispatch)
  115. .then(accessGranted => {
  116. if (accessGranted) {
  117. const startDate = new Date();
  118. const endDate = new Date();
  119. startDate.setDate(startDate.getDate() + FETCH_START_DAYS);
  120. endDate.setDate(endDate.getDate() + FETCH_END_DAYS);
  121. RNCalendarEvents.fetchAllEvents(
  122. startDate.getTime(),
  123. endDate.getTime(),
  124. [])
  125. .then(events =>
  126. _updateCalendarEntries(
  127. events,
  128. state.knownDomains,
  129. dispatch))
  130. .catch(error =>
  131. logger.error('Error fetching calendar.', error));
  132. } else {
  133. logger.warn('Calendar access not granted.');
  134. }
  135. })
  136. .catch(reason => {
  137. logger.error('Error accessing calendar.', reason);
  138. });
  139. }
  140. /**
  141. * Retreives a jitsi URL from an event if present.
  142. *
  143. * @param {Object} event - The event to parse.
  144. * @param {Array<string>} knownDomains - The known domain names.
  145. * @private
  146. * @returns {string}
  147. */
  148. function _getURLFromEvent(event, knownDomains) {
  149. const linkTerminatorPattern = '[^\\s<>$]';
  150. const urlRegExp
  151. = new RegExp(
  152. `http(s)?://(${knownDomains.join('|')})/${linkTerminatorPattern}+`,
  153. 'gi');
  154. const schemeRegExp
  155. = new RegExp(`${APP_LINK_SCHEME}${linkTerminatorPattern}+`, 'gi');
  156. const fieldsToSearch = [
  157. event.title,
  158. event.url,
  159. event.location,
  160. event.notes,
  161. event.description
  162. ];
  163. for (const field of fieldsToSearch) {
  164. if (typeof field === 'string') {
  165. const matches = urlRegExp.exec(field) || schemeRegExp.exec(field);
  166. if (matches) {
  167. return matches[0];
  168. }
  169. }
  170. }
  171. return null;
  172. }
  173. /**
  174. * Retreives the domain name of a room upon join and stores it in the known
  175. * domain list, if not present yet.
  176. *
  177. * @param {Object} store - The redux store.
  178. * @private
  179. * @returns {Promise}
  180. */
  181. function _parseAndAddKnownDomain({ dispatch, getState }) {
  182. const { locationURL } = getState()['features/base/connection'];
  183. dispatch(addKnownDomain(locationURL.host));
  184. }
  185. /**
  186. * Updates the calendar entries in Redux when new list is received.
  187. *
  188. * @param {Object} event - An event returned from the native calendar.
  189. * @param {Array<string>} knownDomains - The known domain list.
  190. * @private
  191. * @returns {CalendarEntry}
  192. */
  193. function _parseCalendarEntry(event, knownDomains) {
  194. if (event) {
  195. const url = _getURLFromEvent(event, knownDomains);
  196. if (url) {
  197. const startDate = Date.parse(event.startDate);
  198. const endDate = Date.parse(event.endDate);
  199. if (isNaN(startDate) || isNaN(endDate)) {
  200. logger.warn(
  201. 'Skipping invalid calendar event',
  202. event.title,
  203. event.startDate,
  204. event.endDate
  205. );
  206. } else {
  207. return {
  208. endDate,
  209. id: event.id,
  210. startDate,
  211. title: event.title,
  212. url
  213. };
  214. }
  215. }
  216. }
  217. return null;
  218. }
  219. /**
  220. * Updates the calendar entries in Redux when new list is received.
  221. *
  222. * @param {Array<CalendarEntry>} events - The new event list.
  223. * @param {Array<string>} knownDomains - The known domain list.
  224. * @param {Function} dispatch - The Redux dispatch function.
  225. * @private
  226. * @returns {void}
  227. */
  228. function _updateCalendarEntries(events, knownDomains, dispatch) {
  229. if (events && events.length) {
  230. const eventList = [];
  231. for (const event of events) {
  232. const calendarEntry
  233. = _parseCalendarEntry(event, knownDomains);
  234. const now = Date.now();
  235. if (calendarEntry && calendarEntry.endDate > now) {
  236. eventList.push(calendarEntry);
  237. }
  238. }
  239. dispatch(
  240. setCalendarEvents(
  241. eventList
  242. .sort((a, b) => a.startDate - b.startDate)
  243. .slice(0, MAX_LIST_LENGTH)));
  244. }
  245. }