Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

microsoftCalendar.ts 19KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609
  1. import { Client } from '@microsoft/microsoft-graph-client';
  2. // eslint-disable-next-line lines-around-comment
  3. import base64js from 'base64-js';
  4. import { v4 as uuidV4 } from 'uuid';
  5. import { findWindows } from 'windows-iana';
  6. import { IanaName } from 'windows-iana/dist/enums';
  7. // @ts-expect-error
  8. import { createDeferred } from '../../../../modules/util/helpers';
  9. import { IStore } from '../../app/types';
  10. import { parseURLParams } from '../../base/util/parseURLParams';
  11. import { parseStandardURIString } from '../../base/util/uri';
  12. import { getShareInfoText } from '../../invite/functions';
  13. import { setCalendarAPIAuthState } from '../actions.web';
  14. /**
  15. * Constants used for interacting with the Microsoft API.
  16. *
  17. * @private
  18. * @type {object}
  19. */
  20. const MS_API_CONFIGURATION = {
  21. /**
  22. * The URL to use when authenticating using Microsoft API.
  23. *
  24. * @type {string}
  25. */
  26. AUTH_ENDPOINT:
  27. 'https://login.microsoftonline.com/common/oauth2/v2.0/authorize?',
  28. CALENDAR_ENDPOINT: '/me/calendars',
  29. /**
  30. * The Microsoft API scopes to request access for calendar.
  31. *
  32. * @type {string}
  33. */
  34. MS_API_SCOPES: 'openid profile Calendars.ReadWrite',
  35. /**
  36. * See https://docs.microsoft.com/en-us/azure/active-directory/develop/
  37. * v2-oauth2-implicit-grant-flow#send-the-sign-in-request. This value is
  38. * needed for passing in the proper domain_hint value when trying to refresh
  39. * a token silently.
  40. *
  41. * @type {string}
  42. */
  43. MS_CONSUMER_TENANT: '9188040d-6c67-4c5b-b112-36a304b66dad',
  44. /**
  45. * The redirect URL to be used by the Microsoft API on successful
  46. * authentication.
  47. *
  48. * @type {string}
  49. */
  50. REDIRECT_URI: `${window.location.origin}/static/msredirect.html`
  51. };
  52. /**
  53. * Store the window from an auth request. That way it can be reused if a new
  54. * request comes in and it can be used to indicate a request is in progress.
  55. *
  56. * @private
  57. * @type {Object|null}
  58. */
  59. let popupAuthWindow: Window | null = null;
  60. /**
  61. * A stateless collection of action creators that implements the expected
  62. * interface for interacting with the Microsoft API in order to get calendar
  63. * data.
  64. *
  65. * @type {Object}
  66. */
  67. export const microsoftCalendarApi = {
  68. /**
  69. * Retrieves the current calendar events.
  70. *
  71. * @param {number} fetchStartDays - The number of days to go back
  72. * when fetching.
  73. * @param {number} fetchEndDays - The number of days to fetch.
  74. * @returns {function(Dispatch<any>, Function): Promise<CalendarEntries>}
  75. */
  76. getCalendarEntries(fetchStartDays?: number, fetchEndDays?: number) {
  77. return (dispatch: IStore['dispatch'], getState: IStore['getState']): Promise<any> => {
  78. const state = getState()['features/calendar-sync'] || {};
  79. const token = state.msAuthState?.accessToken;
  80. if (!token) {
  81. return Promise.reject('Not authorized, please sign in!');
  82. }
  83. const client = Client.init({
  84. authProvider: done => done(null, token)
  85. });
  86. return client
  87. .api(MS_API_CONFIGURATION.CALENDAR_ENDPOINT)
  88. .get()
  89. .then(response => {
  90. const calendarIds = response.value.map((en: any) => en.id);
  91. const getEventsPromises = calendarIds.map((id: string) =>
  92. requestCalendarEvents(
  93. client, id, fetchStartDays, fetchEndDays));
  94. return Promise.all(getEventsPromises);
  95. })
  96. // get .value of every element from the array of results,
  97. // which is an array of events and flatten it to one array
  98. // of events
  99. .then(result => [].concat(...result))
  100. .then(entries => entries.map(e => formatCalendarEntry(e)));
  101. };
  102. },
  103. /**
  104. * Returns the email address for the currently logged in user.
  105. *
  106. * @returns {function(Dispatch<*, Function>): Promise<string>}
  107. */
  108. getCurrentEmail(): Function {
  109. return (dispatch: IStore['dispatch'], getState: IStore['getState']) => {
  110. const { msAuthState = {} }
  111. = getState()['features/calendar-sync'] || {};
  112. const email = msAuthState.userSigninName || '';
  113. return Promise.resolve(email);
  114. };
  115. },
  116. /**
  117. * Sets the application ID to use for interacting with the Microsoft API.
  118. *
  119. * @returns {function(): Promise<void>}
  120. */
  121. load() {
  122. return () => Promise.resolve();
  123. },
  124. /**
  125. * Prompts the participant to sign in to the Microsoft API Client Library.
  126. *
  127. * @returns {function(Dispatch<any>, Function): Promise<void>}
  128. */
  129. signIn() {
  130. return (dispatch: IStore['dispatch'], getState: IStore['getState']) => {
  131. // Ensure only one popup window at a time.
  132. if (popupAuthWindow) {
  133. popupAuthWindow.focus();
  134. return Promise.reject('Sign in already in progress.');
  135. }
  136. const signInDeferred = createDeferred();
  137. const guids = {
  138. authState: uuidV4(),
  139. authNonce: uuidV4()
  140. };
  141. dispatch(setCalendarAPIAuthState(guids));
  142. const { microsoftApiApplicationClientID }
  143. = getState()['features/base/config'];
  144. const authUrl = getAuthUrl(
  145. microsoftApiApplicationClientID ?? '',
  146. guids.authState,
  147. guids.authNonce);
  148. const h = 600;
  149. const w = 480;
  150. popupAuthWindow = window.open(
  151. authUrl,
  152. 'Auth M$',
  153. `width=${w}, height=${h}, top=${
  154. (screen.height / 2) - (h / 2)}, left=${
  155. (screen.width / 2) - (w / 2)}`);
  156. const windowCloseCheck = setInterval(() => {
  157. if (popupAuthWindow?.closed) {
  158. signInDeferred.reject(
  159. 'Popup closed before completing auth.');
  160. popupAuthWindow = null;
  161. window.removeEventListener('message', handleAuth);
  162. clearInterval(windowCloseCheck);
  163. } else if (!popupAuthWindow) {
  164. // This case probably happened because the user completed
  165. // auth.
  166. clearInterval(windowCloseCheck);
  167. }
  168. }, 500);
  169. /**
  170. * Callback with scope access to other variables that are part of
  171. * the sign in request.
  172. *
  173. * @param {Object} event - The event from the post message.
  174. * @private
  175. * @returns {void}
  176. */
  177. function handleAuth({ data }: any) {
  178. if (!data || data.type !== 'ms-login') {
  179. return;
  180. }
  181. window.removeEventListener('message', handleAuth);
  182. popupAuthWindow?.close();
  183. popupAuthWindow = null;
  184. const params = getParamsFromHash(data.url);
  185. const tokenParts = getValidatedTokenParts(
  186. params, guids, microsoftApiApplicationClientID ?? '');
  187. if (!tokenParts) {
  188. signInDeferred.reject('Invalid token received');
  189. return;
  190. }
  191. dispatch(setCalendarAPIAuthState({
  192. authState: undefined,
  193. accessToken: tokenParts.accessToken,
  194. idToken: tokenParts.idToken,
  195. tokenExpires: params.tokenExpires,
  196. userDomainType: tokenParts.userDomainType,
  197. userSigninName: tokenParts.userSigninName
  198. }));
  199. signInDeferred.resolve();
  200. }
  201. window.addEventListener('message', handleAuth);
  202. return signInDeferred.promise;
  203. };
  204. },
  205. /**
  206. * Returns whether or not the user is currently signed in.
  207. *
  208. * @returns {function(Dispatch<any>, Function): Promise<boolean>}
  209. */
  210. _isSignedIn() {
  211. return (dispatch: IStore['dispatch'], getState: IStore['getState']) => {
  212. const now = new Date().getTime();
  213. const state
  214. = getState()['features/calendar-sync'].msAuthState || {};
  215. const tokenExpires = parseInt(state.tokenExpires, 10);
  216. const isExpired = now > tokenExpires && !isNaN(tokenExpires);
  217. if (state.accessToken && isExpired) {
  218. // token expired, let's refresh it
  219. return dispatch(refreshAuthToken())
  220. .then(() => true)
  221. .catch(() => false);
  222. }
  223. return Promise.resolve(state.accessToken && !isExpired);
  224. };
  225. },
  226. /**
  227. * Updates calendar event by generating new invite URL and editing the event
  228. * adding some descriptive text and location.
  229. *
  230. * @param {string} id - The event id.
  231. * @param {string} calendarId - The id of the calendar to use.
  232. * @param {string} location - The location to save to the event.
  233. * @returns {function(Dispatch<any>): Promise<string|never>}
  234. */
  235. updateCalendarEvent(id: string, calendarId: string, location: string) {
  236. return (dispatch: IStore['dispatch'], getState: IStore['getState']) => {
  237. const state = getState()['features/calendar-sync'] || {};
  238. const token = state.msAuthState?.accessToken;
  239. if (!token) {
  240. return Promise.reject('Not authorized, please sign in!');
  241. }
  242. return getShareInfoText(getState(), location, true/* use html */)
  243. .then(text => {
  244. const client = Client.init({
  245. authProvider: done => done(null, token)
  246. });
  247. return client
  248. .api(`/me/events/${id}`)
  249. .get()
  250. .then(description => {
  251. const body = description.body;
  252. if (description.bodyPreview) {
  253. body.content
  254. = `${description.bodyPreview}<br><br>`;
  255. }
  256. // replace all new lines from the text with html
  257. // <br> to make it pretty
  258. body.content += text.split('\n').join('<br>');
  259. return client
  260. .api(`/me/calendar/events/${id}`)
  261. .patch({
  262. body,
  263. location: {
  264. 'displayName': location
  265. }
  266. });
  267. });
  268. });
  269. };
  270. }
  271. };
  272. /**
  273. * Parses the Microsoft calendar entries to a known format.
  274. *
  275. * @param {Object} entry - The Microsoft calendar entry.
  276. * @private
  277. * @returns {{
  278. * calendarId: string,
  279. * description: string,
  280. * endDate: string,
  281. * id: string,
  282. * location: string,
  283. * startDate: string,
  284. * title: string
  285. * }}
  286. */
  287. function formatCalendarEntry(entry: any) {
  288. return {
  289. calendarId: entry.calendarId,
  290. description: entry.body.content,
  291. endDate: entry.end.dateTime,
  292. id: entry.id,
  293. location: entry.location.displayName,
  294. startDate: entry.start.dateTime,
  295. title: entry.subject
  296. };
  297. }
  298. /**
  299. * Constructs and returns the URL to use for renewing an auth token.
  300. *
  301. * @param {string} appId - The Microsoft application id to log into.
  302. * @param {string} userDomainType - The domain type of the application as
  303. * provided by Microsoft.
  304. * @param {string} userSigninName - The email of the user signed into the
  305. * integration with Microsoft.
  306. * @private
  307. * @returns {string} - The auth URL.
  308. */
  309. function getAuthRefreshUrl(appId: string, userDomainType: string, userSigninName: string) {
  310. return [
  311. getAuthUrl(appId, 'undefined', 'undefined'),
  312. 'prompt=none',
  313. `domain_hint=${userDomainType}`,
  314. `login_hint=${userSigninName}`
  315. ].join('&');
  316. }
  317. /**
  318. * Constructs and returns the auth URL to use for login.
  319. *
  320. * @param {string} appId - The Microsoft application id to log into.
  321. * @param {string} authState - The authState guid to use.
  322. * @param {string} authNonce - The authNonce guid to use.
  323. * @private
  324. * @returns {string} - The auth URL.
  325. */
  326. function getAuthUrl(appId: string, authState: string, authNonce: string) {
  327. const authParams = [
  328. 'response_type=id_token+token',
  329. `client_id=${appId}`,
  330. `redirect_uri=${MS_API_CONFIGURATION.REDIRECT_URI}`,
  331. `scope=${MS_API_CONFIGURATION.MS_API_SCOPES}`,
  332. `state=${authState}`,
  333. `nonce=${authNonce}`,
  334. 'response_mode=fragment'
  335. ].join('&');
  336. return `${MS_API_CONFIGURATION.AUTH_ENDPOINT}${authParams}`;
  337. }
  338. /**
  339. * Converts a url from an auth redirect into an object of parameters passed
  340. * into the url.
  341. *
  342. * @param {string} url - The string to parse.
  343. * @private
  344. * @returns {Object}
  345. */
  346. function getParamsFromHash(url: string) {
  347. // @ts-ignore
  348. const params = parseURLParams(parseStandardURIString(url), true, 'hash');
  349. // Get the number of seconds the token is valid for, subtract 5 minutes
  350. // to account for differences in clock settings and convert to ms.
  351. const expiresIn = (parseInt(params.expires_in, 10) - 300) * 1000;
  352. const now = new Date();
  353. const expireDate = new Date(now.getTime() + expiresIn);
  354. params.tokenExpires = expireDate.getTime().toString();
  355. return params;
  356. }
  357. /**
  358. * Converts the parameters from a Microsoft auth redirect into an object of
  359. * token parts. The value "null" will be returned if the params do not produce
  360. * a valid token.
  361. *
  362. * @param {Object} tokenInfo - The token object.
  363. * @param {Object} guids - The guids for authState and authNonce that should
  364. * match in the token.
  365. * @param {Object} appId - The Microsoft application this token is for.
  366. * @private
  367. * @returns {Object|null}
  368. */
  369. function getValidatedTokenParts(tokenInfo: any, guids: any, appId: string) {
  370. // Make sure the token matches the request source by matching the GUID.
  371. if (tokenInfo.state !== guids.authState) {
  372. return null;
  373. }
  374. const idToken = tokenInfo.id_token;
  375. // A token must exist to be valid.
  376. if (!idToken) {
  377. return null;
  378. }
  379. const tokenParts = idToken.split('.');
  380. if (tokenParts.length !== 3) {
  381. return null;
  382. }
  383. let payload;
  384. try {
  385. payload = JSON.parse(b64utoutf8(tokenParts[1]));
  386. } catch (e) {
  387. return null;
  388. }
  389. if (payload.nonce !== guids.authNonce
  390. || payload.aud !== appId
  391. || payload.iss
  392. !== `https://login.microsoftonline.com/${payload.tid}/v2.0`) {
  393. return null;
  394. }
  395. const now = new Date();
  396. // Adjust by 5 minutes to allow for inconsistencies in system clocks.
  397. const notBefore = new Date((payload.nbf - 300) * 1000);
  398. const expires = new Date((payload.exp + 300) * 1000);
  399. if (now < notBefore || now > expires) {
  400. return null;
  401. }
  402. return {
  403. accessToken: tokenInfo.access_token,
  404. idToken,
  405. userDisplayName: payload.name,
  406. userDomainType:
  407. payload.tid === MS_API_CONFIGURATION.MS_CONSUMER_TENANT
  408. ? 'consumers' : 'organizations',
  409. userSigninName: payload.preferred_username
  410. };
  411. }
  412. /**
  413. * Renews an existing auth token so it can continue to be used.
  414. *
  415. * @private
  416. * @returns {function(Dispatch<any>, Function): Promise<void>}
  417. */
  418. function refreshAuthToken() {
  419. return (dispatch: IStore['dispatch'], getState: IStore['getState']) => {
  420. const { microsoftApiApplicationClientID }
  421. = getState()['features/base/config'];
  422. const { msAuthState = {} }
  423. = getState()['features/calendar-sync'] || {};
  424. const refreshAuthUrl = getAuthRefreshUrl(
  425. microsoftApiApplicationClientID ?? '',
  426. msAuthState.userDomainType,
  427. msAuthState.userSigninName);
  428. const iframe = document.createElement('iframe');
  429. iframe.setAttribute('id', 'auth-iframe');
  430. iframe.setAttribute('name', 'auth-iframe');
  431. iframe.setAttribute('style', 'display: none');
  432. iframe.setAttribute('src', refreshAuthUrl);
  433. const signInPromise = new Promise(resolve => {
  434. iframe.onload = () => {
  435. resolve(iframe.contentWindow?.location.hash);
  436. };
  437. });
  438. // The check for body existence is done for flow, which also runs
  439. // against native where document.body may not be defined.
  440. if (!document.body) {
  441. return Promise.reject(
  442. 'Cannot refresh auth token in this environment');
  443. }
  444. document.body.appendChild(iframe);
  445. return signInPromise.then(hash => {
  446. const params = getParamsFromHash(hash as string);
  447. dispatch(setCalendarAPIAuthState({
  448. accessToken: params.access_token,
  449. idToken: params.id_token,
  450. tokenExpires: params.tokenExpires
  451. }));
  452. });
  453. };
  454. }
  455. /**
  456. * Retrieves calendar entries from a specific calendar.
  457. *
  458. * @param {Object} client - The Microsoft-graph-client initialized.
  459. * @param {string} calendarId - The calendar ID to use.
  460. * @param {number} fetchStartDays - The number of days to go back
  461. * when fetching.
  462. * @param {number} fetchEndDays - The number of days to fetch.
  463. * @returns {Promise<any> | Promise}
  464. * @private
  465. */
  466. function requestCalendarEvents( // eslint-disable-line max-params
  467. client: any,
  468. calendarId: string,
  469. fetchStartDays?: number,
  470. fetchEndDays?: number): Promise<any> {
  471. const startDate = new Date();
  472. const endDate = new Date();
  473. startDate.setDate(startDate.getDate() + Number(fetchStartDays));
  474. endDate.setDate(endDate.getDate() + Number(fetchEndDays));
  475. const filter = `Start/DateTime ge '${
  476. startDate.toISOString()}' and End/DateTime lt '${
  477. endDate.toISOString()}'`;
  478. const ianaTimeZone = new Intl.DateTimeFormat().resolvedOptions().timeZone;
  479. const windowsTimeZone = findWindows(ianaTimeZone as IanaName);
  480. return client
  481. .api(`/me/calendars/${calendarId}/events`)
  482. .filter(filter)
  483. .header('Prefer', `outlook.timezone="${windowsTimeZone}"`)
  484. .select('id,subject,start,end,location,body')
  485. .orderby('createdDateTime DESC')
  486. .get()
  487. .then((result: any) => result.value.map((item: Object) => {
  488. return {
  489. ...item,
  490. calendarId
  491. };
  492. }));
  493. }
  494. /**
  495. * Convert a Base64URL encoded string to a UTF-8 encoded string including CJK or Latin.
  496. *
  497. * @param {string} str - The string that needs conversion.
  498. * @private
  499. * @returns {string} - The converted string.
  500. */
  501. function b64utoutf8(str: string) {
  502. let s = str;
  503. // Convert from Base64URL to Base64.
  504. if (s.length % 4 === 2) {
  505. s += '==';
  506. } else if (s.length % 4 === 3) {
  507. s += '=';
  508. }
  509. s = s.replace(/-/g, '+').replace(/_/g, '/');
  510. // Convert Base64 to a byte array.
  511. const bytes = base64js.toByteArray(s);
  512. // Convert bytes to hex.
  513. s = bytes.reduce((str_: any, byte: any) => str_ + byte.toString(16).padStart(2, '0'), '');
  514. // Convert a hexadecimal string to a URLComponent string
  515. s = s.replace(/(..)/g, '%$1');
  516. // Decodee the URI component
  517. return decodeURIComponent(s);
  518. }