您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

googleApi.js 6.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. import { GOOGLE_API_SCOPES } 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. scope: GOOGLE_API_SCOPES.join(' ')
  63. })
  64. .then(resolve)
  65. .catch(reject);
  66. }, 500);
  67. }));
  68. },
  69. /**
  70. * Checks whether a user is currently authenticated with Google through an
  71. * initialized Google API Client Library.
  72. *
  73. * @returns {Promise}
  74. */
  75. isSignedIn() {
  76. return this.get()
  77. .then(api => Boolean(api
  78. && api.auth2
  79. && api.auth2.getAuthInstance
  80. && api.auth2.getAuthInstance().isSignedIn
  81. && api.auth2.getAuthInstance().isSignedIn.get()));
  82. },
  83. /**
  84. * Generates a script tag and downloads the Google API Client Library.
  85. *
  86. * @returns {Promise}
  87. */
  88. load() {
  89. if (googleClientLoadPromise) {
  90. return googleClientLoadPromise;
  91. }
  92. googleClientLoadPromise = new Promise((resolve, reject) => {
  93. const scriptTag = document.createElement('script');
  94. scriptTag.async = true;
  95. scriptTag.addEventListener('error', () => {
  96. scriptTag.remove();
  97. googleClientLoadPromise = null;
  98. reject();
  99. });
  100. scriptTag.addEventListener('load', resolve);
  101. scriptTag.type = 'text/javascript';
  102. scriptTag.src = GOOGLE_API_CLIENT_LIBRARY_URL;
  103. document.head.appendChild(scriptTag);
  104. })
  105. .then(() => new Promise((resolve, reject) =>
  106. this._getGoogleApiClient().load('client:auth2', {
  107. callback: resolve,
  108. onerror: reject
  109. })))
  110. .then(() => this._getGoogleApiClient());
  111. return googleClientLoadPromise;
  112. },
  113. /**
  114. * Executes a request for a list of all YouTube broadcasts associated with
  115. * user currently signed in to the Google API Client Library.
  116. *
  117. * @returns {Promise}
  118. */
  119. requestAvailableYouTubeBroadcasts() {
  120. const url = this._getURLForLiveBroadcasts();
  121. return this.get()
  122. .then(api => api.client.request(url));
  123. },
  124. /**
  125. * Executes a request to get all live streams associated with a broadcast
  126. * in YouTube.
  127. *
  128. * @param {string} boundStreamID - The bound stream ID associated with a
  129. * broadcast in YouTube.
  130. * @returns {Promise}
  131. */
  132. requestLiveStreamsForYouTubeBroadcast(boundStreamID) {
  133. const url = this._getURLForLiveStreams(boundStreamID);
  134. return this.get()
  135. .then(api => api.client.request(url));
  136. },
  137. /**
  138. * Prompts the participant to sign in to the Google API Client Library, even
  139. * if already signed in.
  140. *
  141. * @returns {Promise}
  142. */
  143. showAccountSelection() {
  144. return this.get()
  145. .then(api => api.auth2.getAuthInstance().signIn());
  146. },
  147. /**
  148. * Prompts the participant to sign in to the Google API Client Library, if
  149. * not already signed in.
  150. *
  151. * @returns {Promise}
  152. */
  153. signInIfNotSignedIn() {
  154. return this.get()
  155. .then(() => this.isSignedIn())
  156. .then(isSignedIn => {
  157. if (!isSignedIn) {
  158. return this.showAccountSelection();
  159. }
  160. });
  161. },
  162. /**
  163. * Returns the global Google API Client Library object. Direct use of this
  164. * method is discouraged; instead use the {@link get} method.
  165. *
  166. * @private
  167. * @returns {Object|undefined}
  168. */
  169. _getGoogleApiClient() {
  170. return window.gapi;
  171. },
  172. /**
  173. * Returns the URL to the Google API endpoint for retrieving the currently
  174. * signed in user's YouTube broadcasts.
  175. *
  176. * @private
  177. * @returns {string}
  178. */
  179. _getURLForLiveBroadcasts() {
  180. return [
  181. 'https://content.googleapis.com/youtube/v3/liveBroadcasts',
  182. '?broadcastType=all',
  183. '&mine=true&part=id%2Csnippet%2CcontentDetails%2Cstatus'
  184. ].join('');
  185. },
  186. /**
  187. * Returns the URL to the Google API endpoint for retrieving the live
  188. * streams associated with a YouTube broadcast's bound stream.
  189. *
  190. * @param {string} boundStreamID - The bound stream ID associated with a
  191. * broadcast in YouTube.
  192. * @returns {string}
  193. */
  194. _getURLForLiveStreams(boundStreamID) {
  195. return [
  196. 'https://content.googleapis.com/youtube/v3/liveStreams',
  197. '?part=id%2Csnippet%2Ccdn%2Cstatus',
  198. `&id=${boundStreamID}`
  199. ].join('');
  200. }
  201. };
  202. export default googleApi;