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

StartLiveStreamDialog.web.js 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  1. /* globals APP, interfaceConfig */
  2. import Spinner from '@atlaskit/spinner';
  3. import PropTypes from 'prop-types';
  4. import React, { Component } from 'react';
  5. import { connect } from 'react-redux';
  6. import { Dialog } from '../../../base/dialog';
  7. import { translate } from '../../../base/i18n';
  8. import googleApi from '../../googleApi';
  9. import BroadcastsDropdown from './BroadcastsDropdown';
  10. import GoogleSignInButton from './GoogleSignInButton';
  11. import StreamKeyForm from './StreamKeyForm';
  12. /**
  13. * An enumeration of the different states the Google API can be in while
  14. * interacting with {@code StartLiveStreamDialog}.
  15. *
  16. * @private
  17. * @type {Object}
  18. */
  19. const GOOGLE_API_STATES = {
  20. /**
  21. * The state in which the Google API still needs to be loaded.
  22. */
  23. NEEDS_LOADING: 0,
  24. /**
  25. * The state in which the Google API is loaded and ready for use.
  26. */
  27. LOADED: 1,
  28. /**
  29. * The state in which a user has been logged in through the Google API.
  30. */
  31. SIGNED_IN: 2,
  32. /**
  33. * The state in which the Google API encountered an error either loading
  34. * or with an API request.
  35. */
  36. ERROR: 3
  37. };
  38. /**
  39. * A React Component for requesting a YouTube stream key to use for live
  40. * streaming of the current conference.
  41. *
  42. * @extends Component
  43. */
  44. class StartLiveStreamDialog extends Component {
  45. /**
  46. * {@code StartLiveStreamDialog} component's property types.
  47. *
  48. * @static
  49. */
  50. static propTypes = {
  51. /**
  52. * The ID for the Google web client application used for making stream
  53. * key related requests.
  54. */
  55. _googleApiApplicationClientID: PropTypes.string,
  56. /**
  57. * Callback to invoke when the dialog is dismissed without submitting a
  58. * stream key.
  59. */
  60. onCancel: PropTypes.func,
  61. /**
  62. * Callback to invoke when a stream key is submitted for use.
  63. */
  64. onSubmit: PropTypes.func,
  65. /**
  66. * Invoked to obtain translated strings.
  67. */
  68. t: PropTypes.func
  69. };
  70. /**
  71. * {@code StartLiveStreamDialog} component's local state.
  72. *
  73. * @property {boolean} googleAPIState - The current state of interactions
  74. * with the Google API. Determines what Google related UI should display.
  75. * @property {Object[]|undefined} broadcasts - Details about the broadcasts
  76. * available for use for the logged in Google user's YouTube account.
  77. * @property {string} googleProfileEmail - The email of the user currently
  78. * logged in to the Google web client application.
  79. * @property {string} selectedBoundStreamID - The boundStreamID of the
  80. * broadcast currently selected in the broadcast dropdown.
  81. * @property {string} streamKey - The selected or entered stream key to use
  82. * for YouTube live streaming.
  83. */
  84. state = {
  85. broadcasts: undefined,
  86. googleAPIState: GOOGLE_API_STATES.NEEDS_LOADING,
  87. googleProfileEmail: '',
  88. selectedBoundStreamID: undefined,
  89. streamKey: ''
  90. };
  91. /**
  92. * Initializes a new {@code StartLiveStreamDialog} instance.
  93. *
  94. * @param {Props} props - The React {@code Component} props to initialize
  95. * the new {@code StartLiveStreamDialog} instance with.
  96. */
  97. constructor(props) {
  98. super(props);
  99. /**
  100. * Instance variable used to flag whether the component is or is not
  101. * mounted. Used as a hack to avoid setting state on an unmounted
  102. * component.
  103. *
  104. * @private
  105. * @type {boolean}
  106. */
  107. this._isMounted = false;
  108. // Bind event handlers so they are only bound once per instance.
  109. this._onCancel = this._onCancel.bind(this);
  110. this._onGetYouTubeBroadcasts = this._onGetYouTubeBroadcasts.bind(this);
  111. this._onInitializeGoogleApi = this._onInitializeGoogleApi.bind(this);
  112. this._onRequestGoogleSignIn = this._onRequestGoogleSignIn.bind(this);
  113. this._onStreamKeyChange = this._onStreamKeyChange.bind(this);
  114. this._onSubmit = this._onSubmit.bind(this);
  115. this._onYouTubeBroadcastIDSelected
  116. = this._onYouTubeBroadcastIDSelected.bind(this);
  117. }
  118. /**
  119. * Implements {@link Component#componentDidMount()}. Invoked immediately
  120. * after this component is mounted.
  121. *
  122. * @inheritdoc
  123. * @returns {void}
  124. */
  125. componentDidMount() {
  126. this._isMounted = true;
  127. if (this.props._googleApiApplicationClientID) {
  128. this._onInitializeGoogleApi();
  129. }
  130. }
  131. /**
  132. * Implements React's {@link Component#componentWillUnmount()}. Invoked
  133. * immediately before this component is unmounted and destroyed.
  134. *
  135. * @inheritdoc
  136. */
  137. componentWillUnmount() {
  138. this._isMounted = false;
  139. }
  140. /**
  141. * Implements React's {@link Component#render()}.
  142. *
  143. * @inheritdoc
  144. * @returns {ReactElement}
  145. */
  146. render() {
  147. const { _googleApiApplicationClientID } = this.props;
  148. return (
  149. <Dialog
  150. cancelTitleKey = 'dialog.Cancel'
  151. okTitleKey = 'dialog.startLiveStreaming'
  152. onCancel = { this._onCancel }
  153. onSubmit = { this._onSubmit }
  154. titleKey = 'liveStreaming.start'
  155. width = { 'small' }>
  156. <div className = 'live-stream-dialog'>
  157. { _googleApiApplicationClientID
  158. ? this._renderYouTubePanel() : null }
  159. <StreamKeyForm
  160. helpURL = { interfaceConfig.LIVE_STREAMING_HELP_LINK }
  161. onChange = { this._onStreamKeyChange }
  162. value = { this.state.streamKey } />
  163. </div>
  164. </Dialog>
  165. );
  166. }
  167. /**
  168. * Loads the Google web client application used for fetching stream keys.
  169. * If the user is already logged in, then a request for available YouTube
  170. * broadcasts is also made.
  171. *
  172. * @private
  173. * @returns {Promise}
  174. */
  175. _onInitializeGoogleApi() {
  176. return googleApi.get()
  177. .then(() => googleApi.initializeClient(
  178. this.props._googleApiApplicationClientID))
  179. .then(() => this._setStateIfMounted({
  180. googleAPIState: GOOGLE_API_STATES.LOADED
  181. }))
  182. .then(() => googleApi.isSignedIn())
  183. .then(isSignedIn => {
  184. if (isSignedIn) {
  185. return this._onGetYouTubeBroadcasts();
  186. }
  187. })
  188. .catch(() => {
  189. this._setStateIfMounted({
  190. googleAPIState: GOOGLE_API_STATES.ERROR
  191. });
  192. });
  193. }
  194. /**
  195. * Invokes the passed in {@link onCancel} callback and closes
  196. * {@code StartLiveStreamDialog}.
  197. *
  198. * @private
  199. * @returns {boolean} True is returned to close the modal.
  200. */
  201. _onCancel() {
  202. this.props.onCancel(APP.UI.messageHandler.CANCEL);
  203. return true;
  204. }
  205. /**
  206. * Asks the user to sign in, if not already signed in, and then requests a
  207. * list of the user's YouTube broadcasts.
  208. *
  209. * @private
  210. * @returns {Promise}
  211. */
  212. _onGetYouTubeBroadcasts() {
  213. return googleApi.get()
  214. .then(() => googleApi.signInIfNotSignedIn())
  215. .then(() => googleApi.getCurrentUserProfile())
  216. .then(profile => {
  217. this._setStateIfMounted({
  218. googleProfileEmail: profile.getEmail(),
  219. googleAPIState: GOOGLE_API_STATES.SIGNED_IN
  220. });
  221. })
  222. .then(() => googleApi.requestAvailableYouTubeBroadcasts())
  223. .then(response => {
  224. const broadcasts = this._parseBroadcasts(response.result.items);
  225. this._setStateIfMounted({
  226. broadcasts
  227. });
  228. if (broadcasts.length === 1 && !this.state.streamKey) {
  229. const broadcast = broadcasts[0];
  230. this._onYouTubeBroadcastIDSelected(broadcast.boundStreamID);
  231. }
  232. })
  233. .catch(response => {
  234. // Only show an error if an external request was made with the
  235. // Google api. Do not error if the login in canceled.
  236. if (response && response.result) {
  237. this._setStateIfMounted({
  238. googleAPIState: GOOGLE_API_STATES.ERROR
  239. });
  240. }
  241. });
  242. }
  243. /**
  244. * Forces the Google web client application to prompt for a sign in, such as
  245. * when changing account, and will then fetch available YouTube broadcasts.
  246. *
  247. * @private
  248. * @returns {Promise}
  249. */
  250. _onRequestGoogleSignIn() {
  251. return googleApi.showAccountSelection()
  252. .then(() => this._setStateIfMounted({ broadcasts: undefined }))
  253. .then(() => this._onGetYouTubeBroadcasts());
  254. }
  255. /**
  256. * Callback invoked to update the {@code StartLiveStreamDialog} component's
  257. * display of the entered YouTube stream key.
  258. *
  259. * @param {Object} event - DOM Event for value change.
  260. * @private
  261. * @returns {void}
  262. */
  263. _onStreamKeyChange(event) {
  264. this._setStateIfMounted({
  265. streamKey: event.target.value,
  266. selectedBoundStreamID: undefined
  267. });
  268. }
  269. /**
  270. * Invokes the passed in {@link onSubmit} callback with the entered stream
  271. * key, and then closes {@code StartLiveStreamDialog}.
  272. *
  273. * @private
  274. * @returns {boolean} False if no stream key is entered to preventing
  275. * closing, true to close the modal.
  276. */
  277. _onSubmit() {
  278. const { streamKey, selectedBoundStreamID } = this.state;
  279. if (!streamKey) {
  280. return false;
  281. }
  282. let selectedBroadcastID = null;
  283. if (selectedBoundStreamID) {
  284. const selectedBroadcast = this.state.broadcasts.find(
  285. broadcast => broadcast.boundStreamID === selectedBoundStreamID);
  286. selectedBroadcastID = selectedBroadcast && selectedBroadcast.id;
  287. }
  288. this.props.onSubmit(streamKey, selectedBroadcastID);
  289. return true;
  290. }
  291. /**
  292. * Fetches the stream key for a YouTube broadcast and updates the internal
  293. * state to display the associated stream key as being entered.
  294. *
  295. * @param {string} boundStreamID - The bound stream ID associated with the
  296. * broadcast from which to get the stream key.
  297. * @private
  298. * @returns {Promise}
  299. */
  300. _onYouTubeBroadcastIDSelected(boundStreamID) {
  301. return googleApi.requestLiveStreamsForYouTubeBroadcast(boundStreamID)
  302. .then(response => {
  303. const broadcasts = response.result.items;
  304. const streamName = broadcasts
  305. && broadcasts[0]
  306. && broadcasts[0].cdn.ingestionInfo.streamName;
  307. const streamKey = streamName || '';
  308. this._setStateIfMounted({
  309. streamKey,
  310. selectedBoundStreamID: boundStreamID
  311. });
  312. });
  313. }
  314. /**
  315. * Takes in a list of broadcasts from the YouTube API, removes dupes,
  316. * removes broadcasts that cannot get a stream key, and parses the
  317. * broadcasts into flat objects.
  318. *
  319. * @param {Array} broadcasts - Broadcast descriptions as obtained from
  320. * calling the YouTube API.
  321. * @private
  322. * @returns {Array} An array of objects describing each unique broadcast.
  323. */
  324. _parseBroadcasts(broadcasts) {
  325. const parsedBroadcasts = {};
  326. for (let i = 0; i < broadcasts.length; i++) {
  327. const broadcast = broadcasts[i];
  328. const boundStreamID = broadcast.contentDetails.boundStreamId;
  329. if (boundStreamID && !parsedBroadcasts[boundStreamID]) {
  330. parsedBroadcasts[boundStreamID] = {
  331. boundStreamID,
  332. id: broadcast.id,
  333. status: broadcast.status.lifeCycleStatus,
  334. title: broadcast.snippet.title
  335. };
  336. }
  337. }
  338. return Object.values(parsedBroadcasts);
  339. }
  340. /**
  341. * Renders a React Element for authenticating with the Google web client.
  342. *
  343. * @private
  344. * @returns {ReactElement}
  345. */
  346. _renderYouTubePanel() {
  347. const { t } = this.props;
  348. const {
  349. broadcasts,
  350. googleProfileEmail,
  351. selectedBoundStreamID
  352. } = this.state;
  353. let googleContent, helpText;
  354. switch (this.state.googleAPIState) {
  355. case GOOGLE_API_STATES.LOADED:
  356. googleContent = ( // eslint-disable-line no-extra-parens
  357. <GoogleSignInButton
  358. onClick = { this._onGetYouTubeBroadcasts }
  359. text = { t('liveStreaming.signIn') } />
  360. );
  361. helpText = t('liveStreaming.signInCTA');
  362. break;
  363. case GOOGLE_API_STATES.SIGNED_IN:
  364. googleContent = ( // eslint-disable-line no-extra-parens
  365. <BroadcastsDropdown
  366. broadcasts = { broadcasts }
  367. onBroadcastSelected = { this._onYouTubeBroadcastIDSelected }
  368. selectedBoundStreamID = { selectedBoundStreamID } />
  369. );
  370. /**
  371. * FIXME: Ideally this help text would be one translation string
  372. * that also accepts the anchor. This can be done using the Trans
  373. * component of react-i18next but I couldn't get it working...
  374. */
  375. helpText = ( // eslint-disable-line no-extra-parens
  376. <div>
  377. { `${t('liveStreaming.chooseCTA',
  378. { email: googleProfileEmail })} ` }
  379. <a onClick = { this._onRequestGoogleSignIn }>
  380. { t('liveStreaming.changeSignIn') }
  381. </a>
  382. </div>
  383. );
  384. break;
  385. case GOOGLE_API_STATES.ERROR:
  386. googleContent = ( // eslint-disable-line no-extra-parens
  387. <GoogleSignInButton
  388. onClick = { this._onRequestGoogleSignIn }
  389. text = { t('liveStreaming.signIn') } />
  390. );
  391. helpText = t('liveStreaming.errorAPI');
  392. break;
  393. case GOOGLE_API_STATES.NEEDS_LOADING:
  394. default:
  395. googleContent = ( // eslint-disable-line no-extra-parens
  396. <Spinner
  397. isCompleting = { false }
  398. size = 'medium' />
  399. );
  400. break;
  401. }
  402. return (
  403. <div className = 'google-panel'>
  404. <div className = 'live-stream-cta'>
  405. { helpText }
  406. </div>
  407. <div className = 'google-api'>
  408. { googleContent }
  409. </div>
  410. </div>
  411. );
  412. }
  413. /**
  414. * Updates the internal state if the component is still mounted. This is a
  415. * workaround for all the state setting that occurs after ajax.
  416. *
  417. * @param {Object} newState - The new state to merge into the existing
  418. * state.
  419. * @private
  420. * @returns {void}
  421. */
  422. _setStateIfMounted(newState) {
  423. if (this._isMounted) {
  424. this.setState(newState);
  425. }
  426. }
  427. }
  428. /**
  429. * Maps (parts of) the redux state to the React {@code Component} props of
  430. * {@code StartLiveStreamDialog}.
  431. *
  432. * @param {Object} state - The redux state.
  433. * @protected
  434. * @returns {{
  435. * _googleApiApplicationClientID: string
  436. * }}
  437. */
  438. function _mapStateToProps(state) {
  439. return {
  440. _googleApiApplicationClientID:
  441. state['features/base/config'].googleApiApplicationClientID
  442. };
  443. }
  444. export default translate(connect(_mapStateToProps)(StartLiveStreamDialog));