Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

googleApi.js 9.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  1. import { GOOGLE_API_SCOPES, DISCOVERY_DOCS } from './constants';
  2. const GOOGLE_API_CLIENT_LIBRARY_URL = 'https://apis.google.com/js/api.js';
  3. /**
  4. * A promise for dynamically loading the Google API Client Library.
  5. *
  6. * @private
  7. * @type {Promise}
  8. */
  9. let googleClientLoadPromise;
  10. /**
  11. * A singleton for loading and interacting with the Google API.
  12. */
  13. const googleApi = {
  14. /**
  15. * Obtains Google API Client Library, loading the library dynamically if
  16. * needed.
  17. *
  18. * @returns {Promise}
  19. */
  20. get() {
  21. const globalGoogleApi = this._getGoogleApiClient();
  22. if (!globalGoogleApi) {
  23. return this.load();
  24. }
  25. return Promise.resolve(globalGoogleApi);
  26. },
  27. /**
  28. * Gets the profile for the user signed in to the Google API Client Library.
  29. *
  30. * @returns {Promise}
  31. */
  32. getCurrentUserProfile() {
  33. return this.get()
  34. .then(() => this.isSignedIn())
  35. .then(isSignedIn => {
  36. if (!isSignedIn) {
  37. return null;
  38. }
  39. return this._getGoogleApiClient()
  40. .auth2.getAuthInstance()
  41. .currentUser.get()
  42. .getBasicProfile();
  43. });
  44. },
  45. /**
  46. * Sets the Google Web Client ID used for authenticating with Google and
  47. * making Google API requests.
  48. *
  49. * @param {string} clientId - The client ID to be used with the API library.
  50. * @returns {Promise}
  51. */
  52. initializeClient(clientId) {
  53. return this.get()
  54. .then(api => new Promise((resolve, reject) => {
  55. // setTimeout is used as a workaround for api.client.init not
  56. // resolving consistently when the Google API Client Library is
  57. // loaded asynchronously. See:
  58. // github.com/google/google-api-javascript-client/issues/399
  59. setTimeout(() => {
  60. api.client.init({
  61. clientId,
  62. discoveryDocs: DISCOVERY_DOCS,
  63. scope: GOOGLE_API_SCOPES.join(' ')
  64. })
  65. .then(resolve)
  66. .catch(reject);
  67. }, 500);
  68. }));
  69. },
  70. /**
  71. * Checks whether a user is currently authenticated with Google through an
  72. * initialized Google API Client Library.
  73. *
  74. * @returns {Promise}
  75. */
  76. isSignedIn() {
  77. return this.get()
  78. .then(api => Boolean(api
  79. && api.auth2
  80. && api.auth2.getAuthInstance
  81. && api.auth2.getAuthInstance()
  82. && api.auth2.getAuthInstance().isSignedIn
  83. && api.auth2.getAuthInstance().isSignedIn.get()));
  84. },
  85. /**
  86. * Generates a script tag and downloads the Google API Client Library.
  87. *
  88. * @returns {Promise}
  89. */
  90. load() {
  91. if (googleClientLoadPromise) {
  92. return googleClientLoadPromise;
  93. }
  94. googleClientLoadPromise = new Promise((resolve, reject) => {
  95. const scriptTag = document.createElement('script');
  96. scriptTag.async = true;
  97. scriptTag.addEventListener('error', () => {
  98. scriptTag.remove();
  99. googleClientLoadPromise = null;
  100. reject();
  101. });
  102. scriptTag.addEventListener('load', resolve);
  103. scriptTag.type = 'text/javascript';
  104. scriptTag.src = GOOGLE_API_CLIENT_LIBRARY_URL;
  105. document.head.appendChild(scriptTag);
  106. })
  107. .then(() => new Promise((resolve, reject) =>
  108. this._getGoogleApiClient().load('client:auth2', {
  109. callback: resolve,
  110. onerror: reject
  111. })))
  112. .then(() => this._getGoogleApiClient());
  113. return googleClientLoadPromise;
  114. },
  115. /**
  116. * Executes a request for a list of all YouTube broadcasts associated with
  117. * user currently signed in to the Google API Client Library.
  118. *
  119. * @returns {Promise}
  120. */
  121. requestAvailableYouTubeBroadcasts() {
  122. const url = this._getURLForLiveBroadcasts();
  123. return this.get()
  124. .then(api => api.client.request(url));
  125. },
  126. /**
  127. * Executes a request to get all live streams associated with a broadcast
  128. * in YouTube.
  129. *
  130. * @param {string} boundStreamID - The bound stream ID associated with a
  131. * broadcast in YouTube.
  132. * @returns {Promise}
  133. */
  134. requestLiveStreamsForYouTubeBroadcast(boundStreamID) {
  135. const url = this._getURLForLiveStreams(boundStreamID);
  136. return this.get()
  137. .then(api => api.client.request(url));
  138. },
  139. /**
  140. * Prompts the participant to sign in to the Google API Client Library, even
  141. * if already signed in.
  142. *
  143. * @returns {Promise}
  144. */
  145. showAccountSelection() {
  146. return this.get()
  147. .then(api => api.auth2.getAuthInstance().signIn());
  148. },
  149. /**
  150. * Prompts the participant to sign in to the Google API Client Library, if
  151. * not already signed in.
  152. *
  153. * @returns {Promise}
  154. */
  155. signInIfNotSignedIn() {
  156. return this.get()
  157. .then(() => this.isSignedIn())
  158. .then(isSignedIn => {
  159. if (!isSignedIn) {
  160. return this.showAccountSelection();
  161. }
  162. });
  163. },
  164. /**
  165. * Sign out from the Google API Client Library.
  166. *
  167. * @returns {Promise}
  168. */
  169. signOut() {
  170. return this.get()
  171. .then(api =>
  172. api.auth2
  173. && api.auth2.getAuthInstance
  174. && api.auth2.getAuthInstance()
  175. && api.auth2.getAuthInstance().signOut());
  176. },
  177. /**
  178. * Parses the google calendar entries to a known format.
  179. *
  180. * @param {Object} entry - The google calendar entry.
  181. * @returns {{
  182. * id: string,
  183. * startDate: string,
  184. * endDate: string,
  185. * title: string,
  186. * location: string,
  187. * description: string}}
  188. * @private
  189. */
  190. _convertCalendarEntry(entry) {
  191. return {
  192. id: entry.id,
  193. startDate: entry.start.dateTime,
  194. endDate: entry.end.dateTime,
  195. title: entry.summary,
  196. location: entry.location,
  197. description: entry.description
  198. };
  199. },
  200. /**
  201. * Retrieves calendar entries from all available calendars.
  202. *
  203. * @param {number} fetchStartDays - The number of days to go back
  204. * when fetching.
  205. * @param {number} fetchEndDays - The number of days to fetch.
  206. * @returns {Promise<CalendarEntry>}
  207. * @private
  208. */
  209. _getCalendarEntries(fetchStartDays, fetchEndDays) {
  210. return this.get()
  211. .then(() => this.isSignedIn())
  212. .then(isSignedIn => {
  213. if (!isSignedIn) {
  214. return null;
  215. }
  216. return this._getGoogleApiClient()
  217. .client.calendar.calendarList.list();
  218. })
  219. .then(calendarList => {
  220. // no result, maybe not signed in
  221. if (!calendarList) {
  222. return Promise.resolve();
  223. }
  224. const calendarIds
  225. = calendarList.result.items.map(en => en.id);
  226. const promises = calendarIds.map(id => {
  227. const startDate = new Date();
  228. const endDate = new Date();
  229. startDate.setDate(startDate.getDate() + fetchStartDays);
  230. endDate.setDate(endDate.getDate() + fetchEndDays);
  231. return this._getGoogleApiClient()
  232. .client.calendar.events.list({
  233. 'calendarId': id,
  234. 'timeMin': startDate.toISOString(),
  235. 'timeMax': endDate.toISOString(),
  236. 'showDeleted': false,
  237. 'singleEvents': true,
  238. 'orderBy': 'startTime'
  239. });
  240. });
  241. return Promise.all(promises)
  242. .then(results =>
  243. [].concat(...results.map(rItem => rItem.result.items)))
  244. .then(entries =>
  245. entries.map(e => this._convertCalendarEntry(e)));
  246. });
  247. },
  248. /**
  249. * Returns the global Google API Client Library object. Direct use of this
  250. * method is discouraged; instead use the {@link get} method.
  251. *
  252. * @private
  253. * @returns {Object|undefined}
  254. */
  255. _getGoogleApiClient() {
  256. return window.gapi;
  257. },
  258. /**
  259. * Returns the URL to the Google API endpoint for retrieving the currently
  260. * signed in user's YouTube broadcasts.
  261. *
  262. * @private
  263. * @returns {string}
  264. */
  265. _getURLForLiveBroadcasts() {
  266. return [
  267. 'https://content.googleapis.com/youtube/v3/liveBroadcasts',
  268. '?broadcastType=all',
  269. '&mine=true&part=id%2Csnippet%2CcontentDetails%2Cstatus'
  270. ].join('');
  271. },
  272. /**
  273. * Returns the URL to the Google API endpoint for retrieving the live
  274. * streams associated with a YouTube broadcast's bound stream.
  275. *
  276. * @param {string} boundStreamID - The bound stream ID associated with a
  277. * broadcast in YouTube.
  278. * @returns {string}
  279. */
  280. _getURLForLiveStreams(boundStreamID) {
  281. return [
  282. 'https://content.googleapis.com/youtube/v3/liveStreams',
  283. '?part=id%2Csnippet%2Ccdn%2Cstatus',
  284. `&id=${boundStreamID}`
  285. ].join('');
  286. }
  287. };
  288. export default googleApi;