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.

middleware.js 8.4KB

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