Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

middleware.js 7.7KB

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