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

microsoftCalendar.ts 19KB

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