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.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  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 defaultURL
  92. = parseURIString(getState()['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. if (!_isCalendarEnabled()) {
  111. // The calendar feature is not enabled.
  112. return;
  113. }
  114. const state = getState()['features/calendar-sync'];
  115. const promptForPermission
  116. = (maybePromptForPermission && !state.authorization)
  117. || forcePermission;
  118. _ensureCalendarAccess(promptForPermission, dispatch)
  119. .then(accessGranted => {
  120. if (accessGranted) {
  121. const startDate = new Date();
  122. const endDate = new Date();
  123. startDate.setDate(startDate.getDate() + FETCH_START_DAYS);
  124. endDate.setDate(endDate.getDate() + FETCH_END_DAYS);
  125. RNCalendarEvents.fetchAllEvents(
  126. startDate.getTime(),
  127. endDate.getTime(),
  128. [])
  129. .then(events =>
  130. _updateCalendarEntries(
  131. events,
  132. state.knownDomains,
  133. dispatch))
  134. .catch(error =>
  135. logger.error('Error fetching calendar.', error));
  136. } else {
  137. logger.warn('Calendar access not granted.');
  138. }
  139. })
  140. .catch(reason => {
  141. logger.error('Error accessing calendar.', reason);
  142. });
  143. }
  144. /**
  145. * Retrieves a Jitsi Meet URL from an event if present.
  146. *
  147. * @param {Object} event - The event to parse.
  148. * @param {Array<string>} knownDomains - The known domain names.
  149. * @private
  150. * @returns {string}
  151. */
  152. function _getURLFromEvent(event, knownDomains) {
  153. const linkTerminatorPattern = '[^\\s<>$]';
  154. const urlRegExp
  155. = new RegExp(
  156. `http(s)?://(${knownDomains.join('|')})/${linkTerminatorPattern}+`,
  157. 'gi');
  158. const schemeRegExp
  159. = new RegExp(`${APP_LINK_SCHEME}${linkTerminatorPattern}+`, 'gi');
  160. const fieldsToSearch = [
  161. event.title,
  162. event.url,
  163. event.location,
  164. event.notes,
  165. event.description
  166. ];
  167. for (const field of fieldsToSearch) {
  168. if (typeof field === 'string') {
  169. const matches = urlRegExp.exec(field) || schemeRegExp.exec(field);
  170. if (matches) {
  171. const url = parseURIString(matches[0]);
  172. if (url) {
  173. return url.toString();
  174. }
  175. }
  176. }
  177. }
  178. return null;
  179. }
  180. /**
  181. * Determines whether the calendar feature is enabled by the app. For
  182. * example, Apple through its App Store requires NSCalendarsUsageDescription in
  183. * the app's Info.plist or App Store rejects the app.
  184. *
  185. * @returns {boolean} If the app has enabled the calendar feature, {@code true};
  186. * otherwise, {@code false}.
  187. */
  188. export function _isCalendarEnabled() {
  189. const { calendarEnabled } = NativeModules.AppInfo;
  190. return typeof calendarEnabled === 'undefined' ? true : calendarEnabled;
  191. }
  192. /**
  193. * Retrieves the domain name of a room upon join and stores it in the known
  194. * domain list, if not present yet.
  195. *
  196. * @param {Object} store - The redux store.
  197. * @private
  198. * @returns {Promise}
  199. */
  200. function _parseAndAddKnownDomain({ dispatch, getState }) {
  201. const { locationURL } = getState()['features/base/connection'];
  202. dispatch(addKnownDomain(locationURL.host));
  203. }
  204. /**
  205. * Updates the calendar entries in Redux when new list is received.
  206. *
  207. * @param {Object} event - An event returned from the native calendar.
  208. * @param {Array<string>} knownDomains - The known domain list.
  209. * @private
  210. * @returns {CalendarEntry}
  211. */
  212. function _parseCalendarEntry(event, knownDomains) {
  213. if (event) {
  214. const url = _getURLFromEvent(event, knownDomains);
  215. if (url) {
  216. const startDate = Date.parse(event.startDate);
  217. const endDate = Date.parse(event.endDate);
  218. if (isNaN(startDate) || isNaN(endDate)) {
  219. logger.warn(
  220. 'Skipping invalid calendar event',
  221. event.title,
  222. event.startDate,
  223. event.endDate
  224. );
  225. } else {
  226. return {
  227. endDate,
  228. id: event.id,
  229. startDate,
  230. title: event.title,
  231. url
  232. };
  233. }
  234. }
  235. }
  236. return null;
  237. }
  238. /**
  239. * Updates the calendar entries in Redux when new list is received.
  240. *
  241. * @param {Array<CalendarEntry>} events - The new event list.
  242. * @param {Array<string>} knownDomains - The known domain list.
  243. * @param {Function} dispatch - The Redux dispatch function.
  244. * @private
  245. * @returns {void}
  246. */
  247. function _updateCalendarEntries(events, knownDomains, dispatch) {
  248. if (events && events.length) {
  249. const eventList = [];
  250. for (const event of events) {
  251. const calendarEntry
  252. = _parseCalendarEntry(event, knownDomains);
  253. const now = Date.now();
  254. if (calendarEntry && calendarEntry.endDate > now) {
  255. eventList.push(calendarEntry);
  256. }
  257. }
  258. dispatch(
  259. setCalendarEvents(
  260. eventList
  261. .sort((a, b) => a.startDate - b.startDate)
  262. .slice(0, MAX_LIST_LENGTH)));
  263. }
  264. }