Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

middleware.js 8.4KB

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