Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

googleApi.web.js 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  1. import {
  2. API_URL_BROADCAST_STREAMS,
  3. API_URL_LIVE_BROADCASTS,
  4. DISCOVERY_DOCS,
  5. GOOGLE_SCOPE_CALENDAR,
  6. GOOGLE_SCOPE_USERINFO,
  7. GOOGLE_SCOPE_YOUTUBE
  8. } from './constants';
  9. import logger from './logger';
  10. const GOOGLE_API_CLIENT_LIBRARY_URL = 'https://apis.google.com/js/api.js';
  11. const GOOGLE_GIS_LIBRARY_URL = 'https://accounts.google.com/gsi/client';
  12. /**
  13. * A promise for dynamically loading the Google API Client Library.
  14. *
  15. * @private
  16. * @type {Promise}
  17. */
  18. let googleClientLoadPromise;
  19. /**
  20. * A singleton for loading and interacting with the Google API.
  21. */
  22. const googleApi = {
  23. /**
  24. * Obtains Google API Client Library, loading the library dynamically if
  25. * needed.
  26. *
  27. * @returns {Promise}
  28. */
  29. get() {
  30. const globalGoogleApi = this._getGoogleApiClient();
  31. if (!globalGoogleApi) {
  32. return this.load();
  33. }
  34. return Promise.resolve(globalGoogleApi);
  35. },
  36. /**
  37. * Gets the profile for the user signed in to the Google API Client Library.
  38. *
  39. * @returns {Promise}
  40. */
  41. getCurrentUserProfile() {
  42. return this.get()
  43. .then(() => this.isSignedIn())
  44. .then(isSignedIn => {
  45. if (!isSignedIn) {
  46. return null;
  47. }
  48. return this._getGoogleApiClient()
  49. .client.oauth2
  50. .userinfo.get().getPromise()
  51. .then(r => r.result);
  52. });
  53. },
  54. /**
  55. * Sets the Google Web Client ID used for authenticating with Google and
  56. * making Google API requests.
  57. *
  58. * @param {string} clientId - The client ID to be used with the API library.
  59. * @param {boolean} enableYoutube - Whether youtube scope is enabled.
  60. * @param {boolean} enableCalendar - Whether calendar scope is enabled.
  61. * @returns {Promise}
  62. */
  63. initializeClient(clientId, enableYoutube, enableCalendar) {
  64. return this.get()
  65. .then(api => new Promise((resolve, reject) => {
  66. // setTimeout is used as a workaround for api.client.init not
  67. // resolving consistently when the Google API Client Library is
  68. // loaded asynchronously. See:
  69. // github.com/google/google-api-javascript-client/issues/399
  70. setTimeout(() => {
  71. api.client.init({})
  72. .then(() => {
  73. if (enableCalendar) {
  74. api.client.load(DISCOVERY_DOCS);
  75. }
  76. })
  77. .then(() => {
  78. api.client.load('https://www.googleapis.com/discovery/v1/apis/oauth2/v1/rest');
  79. })
  80. .then(resolve)
  81. .catch(reject);
  82. }, 500);
  83. }))
  84. .then(() => new Promise((resolve, reject) => {
  85. try {
  86. const scope
  87. = `${enableYoutube ? GOOGLE_SCOPE_YOUTUBE : ''} ${enableCalendar ? GOOGLE_SCOPE_CALENDAR : ''}`
  88. .trim();
  89. this.tokenClient = this._getGoogleGISApiClient().accounts.oauth2.initTokenClient({
  90. // eslint-disable-next-line camelcase
  91. client_id: clientId,
  92. scope: `${scope} ${GOOGLE_SCOPE_USERINFO}`,
  93. callback: '' // defined at request time in await/promise scope.
  94. });
  95. resolve();
  96. } catch (err) {
  97. reject(err);
  98. }
  99. }));
  100. },
  101. /**
  102. * Checks whether a user is currently authenticated with Google through an
  103. * initialized Google API Client Library.
  104. *
  105. * @returns {Promise}
  106. */
  107. isSignedIn() {
  108. return new Promise((resolve, _) => {
  109. const te = parseInt(this.tokenExpires, 10);
  110. const isExpired = isNaN(this.tokenExpires) ? true : new Date().getTime() > te;
  111. resolve(Boolean(!isExpired));
  112. });
  113. },
  114. /**
  115. * Generates a script tag.
  116. *
  117. * @param {string} src - The source for the script tag.
  118. * @returns {Promise<unknown>}
  119. * @private
  120. */
  121. _loadScriptTag(src) {
  122. return new Promise((resolve, reject) => {
  123. const scriptTag = document.createElement('script');
  124. scriptTag.async = true;
  125. scriptTag.addEventListener('error', () => {
  126. scriptTag.remove();
  127. reject();
  128. });
  129. scriptTag.addEventListener('load', resolve);
  130. scriptTag.type = 'text/javascript';
  131. scriptTag.src = src;
  132. document.head.appendChild(scriptTag);
  133. });
  134. },
  135. /**
  136. * Generates a script tag and downloads the Google API Client Library.
  137. *
  138. * @returns {Promise}
  139. */
  140. load() {
  141. if (googleClientLoadPromise) {
  142. return googleClientLoadPromise;
  143. }
  144. googleClientLoadPromise = this._loadScriptTag(GOOGLE_API_CLIENT_LIBRARY_URL)
  145. .catch(() => {
  146. googleClientLoadPromise = null;
  147. })
  148. .then(() => new Promise((resolve, reject) =>
  149. this._getGoogleApiClient().load('client', {
  150. callback: resolve,
  151. onerror: reject
  152. })))
  153. .then(this._loadScriptTag(GOOGLE_GIS_LIBRARY_URL))
  154. .catch(() => {
  155. googleClientLoadPromise = null;
  156. })
  157. .then(() => this._getGoogleApiClient());
  158. return googleClientLoadPromise;
  159. },
  160. /**
  161. * Executes a request for a list of all YouTube broadcasts associated with
  162. * user currently signed in to the Google API Client Library.
  163. *
  164. * @returns {Promise}
  165. */
  166. requestAvailableYouTubeBroadcasts() {
  167. return this.get()
  168. .then(api => api.client.request(API_URL_LIVE_BROADCASTS));
  169. },
  170. /**
  171. * Executes a request to get all live streams associated with a broadcast
  172. * in YouTube.
  173. *
  174. * @param {string} boundStreamID - The bound stream ID associated with a
  175. * broadcast in YouTube.
  176. * @returns {Promise}
  177. */
  178. requestLiveStreamsForYouTubeBroadcast(boundStreamID) {
  179. return this.get()
  180. .then(api => api.client.request(
  181. `${API_URL_BROADCAST_STREAMS}${boundStreamID}`));
  182. },
  183. /**
  184. * Prompts the participant to sign in to the Google API Client Library, even
  185. * if already signed in.
  186. *
  187. * @param {boolean} consent - Whether to show account selection dialog.
  188. * @returns {Promise}
  189. */
  190. showAccountSelection(consent) {
  191. return this.get()
  192. .then(api => new Promise((resolve, reject) => {
  193. try {
  194. // Settle this promise in the response callback for requestAccessToken()
  195. this.tokenClient.callback = resp => {
  196. if (resp.error !== undefined) {
  197. reject(resp);
  198. }
  199. // Get the number of seconds the token is valid for, subtract 5 minutes
  200. // to account for differences in clock settings and convert to ms.
  201. const expiresIn = (parseInt(api.client.getToken().expires_in, 10) - 300) * 1000;
  202. const now = new Date();
  203. const expireDate = new Date(now.getTime() + expiresIn);
  204. this.tokenExpires = expireDate.getTime().toString();
  205. resolve(resp);
  206. };
  207. this.tokenClient.requestAccessToken({ prompt: consent ? 'consent' : '' });
  208. } catch (err) {
  209. logger.error('Error requesting token', err);
  210. }
  211. }));
  212. },
  213. /**
  214. * Prompts the participant to sign in to the Google API Client Library, if
  215. * not already signed in.
  216. *
  217. * @param {boolean} consent - Whether to show account selection dialog.
  218. * @returns {Promise}
  219. */
  220. signInIfNotSignedIn(consent) {
  221. return this.get()
  222. .then(() => this.isSignedIn())
  223. .then(isSignedIn => {
  224. if (!isSignedIn) {
  225. return this.showAccountSelection(consent);
  226. }
  227. });
  228. },
  229. /**
  230. * Sign out from the Google API Client Library.
  231. *
  232. * @returns {Promise}
  233. */
  234. signOut() {
  235. return this.get()
  236. .then(() => {
  237. this.tokenClient = undefined;
  238. this.tokenExpires = undefined;
  239. });
  240. },
  241. /**
  242. * Parses the google calendar entries to a known format.
  243. *
  244. * @param {Object} entry - The google calendar entry.
  245. * @returns {{
  246. * calendarId: string,
  247. * description: string,
  248. * endDate: string,
  249. * id: string,
  250. * location: string,
  251. * startDate: string,
  252. * title: string}}
  253. * @private
  254. */
  255. _convertCalendarEntry(entry) {
  256. return {
  257. calendarId: entry.calendarId,
  258. description: entry.description,
  259. endDate: entry.end.dateTime,
  260. id: entry.id,
  261. location: entry.location,
  262. startDate: entry.start.dateTime,
  263. title: entry.summary,
  264. url: this._getConferenceDataVideoUri(entry.conferenceData)
  265. };
  266. },
  267. /**
  268. * Checks conference data for jitsi conference solution and returns
  269. * its video url.
  270. *
  271. * @param {Object} conferenceData - The conference data of the event.
  272. * @returns {string|undefined} Returns the found video uri or undefined.
  273. */
  274. _getConferenceDataVideoUri(conferenceData = {}) {
  275. try {
  276. // check conference data coming from calendar addons
  277. if (conferenceData.parameters.addOnParameters.parameters
  278. .conferenceSolutionType === 'jitsi') {
  279. const videoEntry = conferenceData.entryPoints.find(
  280. e => e.entryPointType === 'video');
  281. if (videoEntry) {
  282. return videoEntry.uri;
  283. }
  284. }
  285. } catch (error) {
  286. // we don't care about undefined fields
  287. }
  288. },
  289. /**
  290. * Retrieves calendar entries from all available calendars.
  291. *
  292. * @param {number} fetchStartDays - The number of days to go back
  293. * when fetching.
  294. * @param {number} fetchEndDays - The number of days to fetch.
  295. * @returns {Promise<CalendarEntry>}
  296. * @private
  297. */
  298. _getCalendarEntries(fetchStartDays, fetchEndDays) {
  299. return this.get()
  300. .then(() => this.isSignedIn())
  301. .then(isSignedIn => {
  302. if (!isSignedIn) {
  303. return null;
  304. }
  305. // user can edit the events, so we want only those that
  306. // can be edited
  307. return this._getGoogleApiClient()
  308. .client.calendar.calendarList.list();
  309. })
  310. .then(calendarList => {
  311. // no result, maybe not signed in
  312. if (!calendarList) {
  313. return Promise.resolve();
  314. }
  315. const calendarIds
  316. = calendarList.result.items.map(en => {
  317. return {
  318. id: en.id,
  319. accessRole: en.accessRole
  320. };
  321. });
  322. const promises = calendarIds.map(({ id, accessRole }) => {
  323. const startDate = new Date();
  324. const endDate = new Date();
  325. startDate.setDate(startDate.getDate() + fetchStartDays);
  326. endDate.setDate(endDate.getDate() + fetchEndDays);
  327. // retrieve the events and adds to the result the calendarId
  328. return this._getGoogleApiClient()
  329. .client.calendar.events.list({
  330. 'calendarId': id,
  331. 'timeMin': startDate.toISOString(),
  332. 'timeMax': endDate.toISOString(),
  333. 'showDeleted': false,
  334. 'singleEvents': true,
  335. 'orderBy': 'startTime'
  336. })
  337. .then(result => result.result.items
  338. .map(item => {
  339. const resultItem = { ...item };
  340. // add the calendarId only for the events
  341. // we can edit
  342. if (accessRole === 'writer'
  343. || accessRole === 'owner') {
  344. resultItem.calendarId = id;
  345. }
  346. return resultItem;
  347. }));
  348. });
  349. return Promise.all(promises)
  350. .then(results => [].concat(...results))
  351. .then(entries =>
  352. entries.map(e => this._convertCalendarEntry(e)));
  353. });
  354. },
  355. /**
  356. * Updates the calendar event and adds a location and text.
  357. *
  358. * @param {string} id - The event id to update.
  359. * @param {string} calendarId - The calendar id to use.
  360. * @param {string} location - The location to add to the event.
  361. * @param {string} text - The description text to set/append.
  362. * @returns {Promise<T | never>}
  363. * @private
  364. */
  365. _updateCalendarEntry(id, calendarId, location, text) {
  366. return this.get()
  367. .then(() => this.isSignedIn())
  368. .then(isSignedIn => {
  369. if (!isSignedIn) {
  370. return null;
  371. }
  372. return this._getGoogleApiClient()
  373. .client.calendar.events.get({
  374. 'calendarId': calendarId,
  375. 'eventId': id
  376. }).then(event => {
  377. let newDescription = text;
  378. if (event.result.description) {
  379. newDescription = `${event.result.description}\n\n${
  380. text}`;
  381. }
  382. return this._getGoogleApiClient()
  383. .client.calendar.events.patch({
  384. 'calendarId': calendarId,
  385. 'eventId': id,
  386. 'description': newDescription,
  387. 'location': location
  388. });
  389. });
  390. });
  391. },
  392. /**
  393. * Returns the global Google API Client Library object. Direct use of this
  394. * method is discouraged; instead use the {@link get} method.
  395. *
  396. * @private
  397. * @returns {Object|undefined}
  398. */
  399. _getGoogleApiClient() {
  400. return window.gapi;
  401. },
  402. /**
  403. * Returns the global Google Identity Services Library object.
  404. *
  405. * @private
  406. * @returns {Object|undefined}
  407. */
  408. _getGoogleGISApiClient() {
  409. return window.google;
  410. }
  411. };
  412. export default googleApi;