Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

middleware.js 8.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. // @flow
  2. import { NativeModules } from 'react-native';
  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. addKnownDomain,
  11. setCalendarAuthorization,
  12. setCalendarEvents
  13. } from './actions';
  14. import { REFRESH_CALENDAR } from './actionTypes';
  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. 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:
  30. _fetchCalendarEntries(store, true, action.forcePermission);
  31. break;
  32. case SET_ROOM:
  33. _parseAndAddKnownDomain(store);
  34. break;
  35. }
  36. return result;
  37. });
  38. /**
  39. * Clears the calendar access status when the app comes back from the
  40. * background. This is needed as some users may never quit the app, but puts it
  41. * into the background and we need to try to request for a permission as often
  42. * as possible, but not annoyingly often.
  43. *
  44. * @param {Object} store - The redux store.
  45. * @param {Object} action - The Redux action.
  46. * @private
  47. * @returns {void}
  48. */
  49. function _maybeClearAccessStatus(store, { appState }) {
  50. if (appState === 'background') {
  51. store.dispatch(setCalendarAuthorization(undefined));
  52. }
  53. }
  54. /**
  55. * Ensures calendar access if possible and resolves the promise if it's granted.
  56. *
  57. * @param {boolean} promptForPermission - Flag to tell the app if it should
  58. * prompt for a calendar permission if it wasn't granted yet.
  59. * @param {Function} dispatch - The Redux dispatch function.
  60. * @private
  61. * @returns {Promise}
  62. */
  63. function _ensureCalendarAccess(promptForPermission, dispatch) {
  64. return new Promise((resolve, reject) => {
  65. RNCalendarEvents.authorizationStatus()
  66. .then(status => {
  67. if (status === 'authorized') {
  68. resolve(true);
  69. } else if (promptForPermission) {
  70. RNCalendarEvents.authorizeEventStore()
  71. .then(result => {
  72. dispatch(setCalendarAuthorization(result));
  73. resolve(result === 'authorized');
  74. })
  75. .catch(reject);
  76. } else {
  77. resolve(false);
  78. }
  79. })
  80. .catch(reject);
  81. });
  82. }
  83. /**
  84. * Ensures presence of the default server in the known domains list.
  85. *
  86. * @param {Object} store - The redux store.
  87. * @private
  88. * @returns {Promise}
  89. */
  90. function _ensureDefaultServer({ dispatch, getState }) {
  91. const state = getState();
  92. const defaultURL
  93. = parseURIString(state['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. if (!_isCalendarEnabled()) {
  112. // The calendar feature is not enabled.
  113. return;
  114. }
  115. const state = getState()['features/calendar-sync'];
  116. const promptForPermission
  117. = (maybePromptForPermission && !state.authorization)
  118. || forcePermission;
  119. _ensureCalendarAccess(promptForPermission, dispatch)
  120. .then(accessGranted => {
  121. if (accessGranted) {
  122. const startDate = new Date();
  123. const endDate = new Date();
  124. startDate.setDate(startDate.getDate() + FETCH_START_DAYS);
  125. endDate.setDate(endDate.getDate() + FETCH_END_DAYS);
  126. RNCalendarEvents.fetchAllEvents(
  127. startDate.getTime(),
  128. endDate.getTime(),
  129. [])
  130. .then(events =>
  131. _updateCalendarEntries(
  132. events,
  133. state.knownDomains,
  134. dispatch))
  135. .catch(error =>
  136. logger.error('Error fetching calendar.', error));
  137. } else {
  138. logger.warn('Calendar access not granted.');
  139. }
  140. })
  141. .catch(reason => {
  142. logger.error('Error accessing calendar.', reason);
  143. });
  144. }
  145. /**
  146. * Retreives a jitsi URL from an event if present.
  147. *
  148. * @param {Object} event - The event to parse.
  149. * @param {Array<string>} knownDomains - The known domain names.
  150. * @private
  151. * @returns {string}
  152. */
  153. function _getURLFromEvent(event, knownDomains) {
  154. const linkTerminatorPattern = '[^\\s<>$]';
  155. const urlRegExp
  156. = new RegExp(
  157. `http(s)?://(${knownDomains.join('|')})/${linkTerminatorPattern}+`,
  158. 'gi');
  159. const schemeRegExp
  160. = new RegExp(`${APP_LINK_SCHEME}${linkTerminatorPattern}+`, 'gi');
  161. const fieldsToSearch = [
  162. event.title,
  163. event.url,
  164. event.location,
  165. event.notes,
  166. event.description
  167. ];
  168. for (const field of fieldsToSearch) {
  169. if (typeof field === 'string') {
  170. const matches = urlRegExp.exec(field) || schemeRegExp.exec(field);
  171. if (matches) {
  172. const url = parseURIString(matches[0]);
  173. if (url) {
  174. return url.toString();
  175. }
  176. }
  177. }
  178. }
  179. return null;
  180. }
  181. /**
  182. * Determines whether the calendar feature is enabled by the app. For
  183. * example, Apple through its App Store requires NSCalendarsUsageDescription in
  184. * the app's Info.plist or App Store rejects the app.
  185. *
  186. * @returns {boolean} If the app has enabled the calendar feature, {@code true};
  187. * otherwise, {@code false}.
  188. */
  189. export function _isCalendarEnabled() {
  190. const { calendarEnabled } = NativeModules.AppInfo;
  191. return typeof calendarEnabled === 'undefined' ? true : calendarEnabled;
  192. }
  193. /**
  194. * Retreives the domain name of a room upon join and stores it in the known
  195. * domain list, if not present yet.
  196. *
  197. * @param {Object} store - The redux store.
  198. * @private
  199. * @returns {Promise}
  200. */
  201. function _parseAndAddKnownDomain({ dispatch, getState }) {
  202. const { locationURL } = getState()['features/base/connection'];
  203. dispatch(addKnownDomain(locationURL.host));
  204. }
  205. /**
  206. * Updates the calendar entries in Redux when new list is received.
  207. *
  208. * @param {Object} event - An event returned from the native calendar.
  209. * @param {Array<string>} knownDomains - The known domain list.
  210. * @private
  211. * @returns {CalendarEntry}
  212. */
  213. function _parseCalendarEntry(event, knownDomains) {
  214. if (event) {
  215. const url = _getURLFromEvent(event, knownDomains);
  216. if (url) {
  217. const startDate = Date.parse(event.startDate);
  218. const endDate = Date.parse(event.endDate);
  219. if (isNaN(startDate) || isNaN(endDate)) {
  220. logger.warn(
  221. 'Skipping invalid calendar event',
  222. event.title,
  223. event.startDate,
  224. event.endDate
  225. );
  226. } else {
  227. return {
  228. endDate,
  229. id: event.id,
  230. startDate,
  231. title: event.title,
  232. url
  233. };
  234. }
  235. }
  236. }
  237. return null;
  238. }
  239. /**
  240. * Updates the calendar entries in Redux when new list is received.
  241. *
  242. * @param {Array<CalendarEntry>} events - The new event list.
  243. * @param {Array<string>} knownDomains - The known domain list.
  244. * @param {Function} dispatch - The Redux dispatch function.
  245. * @private
  246. * @returns {void}
  247. */
  248. function _updateCalendarEntries(events, knownDomains, dispatch) {
  249. if (events && events.length) {
  250. const eventList = [];
  251. for (const event of events) {
  252. const calendarEntry
  253. = _parseCalendarEntry(event, knownDomains);
  254. const now = Date.now();
  255. if (calendarEntry && calendarEntry.endDate > now) {
  256. eventList.push(calendarEntry);
  257. }
  258. }
  259. dispatch(
  260. setCalendarEvents(
  261. eventList
  262. .sort((a, b) => a.startDate - b.startDate)
  263. .slice(0, MAX_LIST_LENGTH)));
  264. }
  265. }