You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

SharedVideo.js 25KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811
  1. /* global $, APP, YT, interfaceConfig, onPlayerReady, onPlayerStateChange,
  2. onPlayerError */
  3. import Logger from 'jitsi-meet-logger';
  4. import {
  5. createSharedVideoEvent as createEvent,
  6. sendAnalytics
  7. } from '../../../react/features/analytics';
  8. import {
  9. participantJoined,
  10. participantLeft,
  11. pinParticipant
  12. } from '../../../react/features/base/participants';
  13. import {
  14. dockToolbox,
  15. getToolboxHeight,
  16. showToolbox
  17. } from '../../../react/features/toolbox';
  18. import { YOUTUBE_PARTICIPANT_NAME } from '../../../react/features/youtube-player';
  19. import UIEvents from '../../../service/UI/UIEvents';
  20. import UIUtil from '../util/UIUtil';
  21. import Filmstrip from '../videolayout/Filmstrip';
  22. import LargeContainer from '../videolayout/LargeContainer';
  23. import VideoLayout from '../videolayout/VideoLayout';
  24. const logger = Logger.getLogger(__filename);
  25. export const SHARED_VIDEO_CONTAINER_TYPE = 'sharedvideo';
  26. /**
  27. * Example shared video link.
  28. * @type {string}
  29. */
  30. const defaultSharedVideoLink = 'https://youtu.be/TB7LlM4erx8';
  31. const updateInterval = 5000; // milliseconds
  32. /**
  33. * The dialog for user input (video link).
  34. * @type {null}
  35. */
  36. let dialog = null;
  37. /**
  38. * Manager of shared video.
  39. */
  40. export default class SharedVideoManager {
  41. /**
  42. *
  43. */
  44. constructor(emitter) {
  45. this.emitter = emitter;
  46. this.isSharedVideoShown = false;
  47. this.isPlayerAPILoaded = false;
  48. this.mutedWithUserInteraction = false;
  49. }
  50. /**
  51. * Indicates if the player volume is currently on. This will return true if
  52. * we have an available player, which is currently in a PLAYING state,
  53. * which isn't muted and has it's volume greater than 0.
  54. *
  55. * @returns {boolean} indicating if the volume of the shared video is
  56. * currently on.
  57. */
  58. isSharedVideoVolumeOn() {
  59. return this.player
  60. && this.player.getPlayerState() === YT.PlayerState.PLAYING
  61. && !this.player.isMuted()
  62. && this.player.getVolume() > 0;
  63. }
  64. /**
  65. * Indicates if the local user is the owner of the shared video.
  66. * @returns {*|boolean}
  67. */
  68. isSharedVideoOwner() {
  69. return this.from && APP.conference.isLocalId(this.from);
  70. }
  71. /**
  72. * Starts shared video by asking user for url, or if its already working
  73. * asks whether the user wants to stop sharing the video.
  74. */
  75. toggleSharedVideo() {
  76. if (dialog) {
  77. return;
  78. }
  79. if (!this.isSharedVideoShown) {
  80. requestVideoLink().then(
  81. url => {
  82. this.emitter.emit(
  83. UIEvents.UPDATE_SHARED_VIDEO, url, 'start');
  84. sendAnalytics(createEvent('started'));
  85. },
  86. err => {
  87. logger.log('SHARED VIDEO CANCELED', err);
  88. sendAnalytics(createEvent('canceled'));
  89. }
  90. );
  91. return;
  92. }
  93. if (APP.conference.isLocalId(this.from)) {
  94. showStopVideoPropmpt().then(
  95. () => {
  96. // make sure we stop updates for playing before we send stop
  97. // if we stop it after receiving self presence, we can end
  98. // up sending stop playing, and on the other end it will not
  99. // stop
  100. if (this.intervalId) {
  101. clearInterval(this.intervalId);
  102. this.intervalId = null;
  103. }
  104. this.emitter.emit(
  105. UIEvents.UPDATE_SHARED_VIDEO, this.url, 'stop');
  106. sendAnalytics(createEvent('stopped'));
  107. },
  108. () => {}); // eslint-disable-line no-empty-function
  109. } else {
  110. APP.UI.messageHandler.showWarning({
  111. descriptionKey: 'dialog.alreadySharedVideoMsg',
  112. titleKey: 'dialog.alreadySharedVideoTitle'
  113. });
  114. sendAnalytics(createEvent('already.shared'));
  115. }
  116. }
  117. /**
  118. * Shows the player component and starts the process that will be sending
  119. * updates, if we are the one shared the video.
  120. *
  121. * @param id the id of the sender of the command
  122. * @param url the video url
  123. * @param attributes
  124. */
  125. onSharedVideoStart(id, url, attributes) {
  126. if (this.isSharedVideoShown) {
  127. return;
  128. }
  129. this.isSharedVideoShown = true;
  130. // the video url
  131. this.url = url;
  132. // the owner of the video
  133. this.from = id;
  134. this.mutedWithUserInteraction = APP.conference.isLocalAudioMuted();
  135. // listen for local audio mute events
  136. this.localAudioMutedListener = this.onLocalAudioMuted.bind(this);
  137. this.emitter.on(UIEvents.AUDIO_MUTED, this.localAudioMutedListener);
  138. // This code loads the IFrame Player API code asynchronously.
  139. const tag = document.createElement('script');
  140. tag.src = 'https://www.youtube.com/iframe_api';
  141. const firstScriptTag = document.getElementsByTagName('script')[0];
  142. firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
  143. // sometimes we receive errors like player not defined
  144. // or player.pauseVideo is not a function
  145. // we need to operate with player after start playing
  146. // self.player will be defined once it start playing
  147. // and will process any initial attributes if any
  148. this.initialAttributes = attributes;
  149. const self = this;
  150. if (self.isPlayerAPILoaded) {
  151. window.onYouTubeIframeAPIReady();
  152. } else {
  153. window.onYouTubeIframeAPIReady = function() {
  154. self.isPlayerAPILoaded = true;
  155. const showControls
  156. = APP.conference.isLocalId(self.from) ? 1 : 0;
  157. const p = new YT.Player('sharedVideoIFrame', {
  158. height: '100%',
  159. width: '100%',
  160. videoId: self.url,
  161. playerVars: {
  162. 'origin': location.origin,
  163. 'fs': '0',
  164. 'autoplay': 0,
  165. 'controls': showControls,
  166. 'rel': 0
  167. },
  168. events: {
  169. 'onReady': onPlayerReady,
  170. 'onStateChange': onPlayerStateChange,
  171. 'onError': onPlayerError
  172. }
  173. });
  174. // add listener for volume changes
  175. p.addEventListener(
  176. 'onVolumeChange', 'onVolumeChange');
  177. if (APP.conference.isLocalId(self.from)) {
  178. // adds progress listener that will be firing events
  179. // while we are paused and we change the progress of the
  180. // video (seeking forward or backward on the video)
  181. p.addEventListener(
  182. 'onVideoProgress', 'onVideoProgress');
  183. }
  184. };
  185. }
  186. /**
  187. * Indicates that a change in state has occurred for the shared video.
  188. * @param event the event notifying us of the change
  189. */
  190. window.onPlayerStateChange = function(event) {
  191. // eslint-disable-next-line eqeqeq
  192. if (event.data == YT.PlayerState.PLAYING) {
  193. self.player = event.target;
  194. if (self.initialAttributes) {
  195. // If a network update has occurred already now is the
  196. // time to process it.
  197. self.processVideoUpdate(
  198. self.player,
  199. self.initialAttributes);
  200. self.initialAttributes = null;
  201. }
  202. self.smartAudioMute();
  203. // eslint-disable-next-line eqeqeq
  204. } else if (event.data == YT.PlayerState.PAUSED) {
  205. self.smartAudioUnmute();
  206. sendAnalytics(createEvent('paused'));
  207. }
  208. // eslint-disable-next-line eqeqeq
  209. self.fireSharedVideoEvent(event.data == YT.PlayerState.PAUSED);
  210. };
  211. /**
  212. * Track player progress while paused.
  213. * @param event
  214. */
  215. window.onVideoProgress = function(event) {
  216. const state = event.target.getPlayerState();
  217. // eslint-disable-next-line eqeqeq
  218. if (state == YT.PlayerState.PAUSED) {
  219. self.fireSharedVideoEvent(true);
  220. }
  221. };
  222. /**
  223. * Gets notified for volume state changed.
  224. * @param event
  225. */
  226. window.onVolumeChange = function(event) {
  227. self.fireSharedVideoEvent();
  228. // let's check, if player is not muted lets mute locally
  229. if (event.data.volume > 0 && !event.data.muted) {
  230. self.smartAudioMute();
  231. } else if (event.data.volume <= 0 || event.data.muted) {
  232. self.smartAudioUnmute();
  233. }
  234. sendAnalytics(createEvent(
  235. 'volume.changed',
  236. {
  237. volume: event.data.volume,
  238. muted: event.data.muted
  239. }));
  240. };
  241. window.onPlayerReady = function(event) {
  242. const player = event.target;
  243. // do not relay on autoplay as it is not sending all of the events
  244. // in onPlayerStateChange
  245. player.playVideo();
  246. const iframe = player.getIframe();
  247. // eslint-disable-next-line no-use-before-define
  248. self.sharedVideo = new SharedVideoContainer(
  249. { url,
  250. iframe,
  251. player });
  252. // prevents pausing participants not sharing the video
  253. // to pause the video
  254. if (!APP.conference.isLocalId(self.from)) {
  255. $('#sharedVideo').css('pointer-events', 'none');
  256. }
  257. VideoLayout.addLargeVideoContainer(
  258. SHARED_VIDEO_CONTAINER_TYPE, self.sharedVideo);
  259. APP.store.dispatch(participantJoined({
  260. // FIXME The cat is out of the bag already or rather _room is
  261. // not private because it is used in multiple other places
  262. // already such as AbstractPageReloadOverlay.
  263. conference: APP.conference._room,
  264. id: self.url,
  265. isFakeParticipant: true,
  266. name: YOUTUBE_PARTICIPANT_NAME
  267. }));
  268. APP.store.dispatch(pinParticipant(self.url));
  269. // If we are sending the command and we are starting the player
  270. // we need to continuously send the player current time position
  271. if (APP.conference.isLocalId(self.from)) {
  272. self.intervalId = setInterval(
  273. self.fireSharedVideoEvent.bind(self),
  274. updateInterval);
  275. }
  276. };
  277. window.onPlayerError = function(event) {
  278. logger.error('Error in the player:', event.data);
  279. // store the error player, so we can remove it
  280. self.errorInPlayer = event.target;
  281. };
  282. }
  283. /**
  284. * Process attributes, whether player needs to be paused or seek.
  285. * @param player the player to operate over
  286. * @param attributes the attributes with the player state we want
  287. */
  288. processVideoUpdate(player, attributes) {
  289. if (!attributes) {
  290. return;
  291. }
  292. // eslint-disable-next-line eqeqeq
  293. if (attributes.state == 'playing') {
  294. const isPlayerPaused
  295. = this.player.getPlayerState() === YT.PlayerState.PAUSED;
  296. // If our player is currently paused force the seek.
  297. this.processTime(player, attributes, isPlayerPaused);
  298. // Process mute.
  299. const isAttrMuted = attributes.muted === 'true';
  300. if (player.isMuted() !== isAttrMuted) {
  301. this.smartPlayerMute(isAttrMuted, true);
  302. }
  303. // Process volume
  304. if (!isAttrMuted
  305. && attributes.volume !== undefined
  306. // eslint-disable-next-line eqeqeq
  307. && player.getVolume() != attributes.volume) {
  308. player.setVolume(attributes.volume);
  309. logger.info(`Player change of volume:${attributes.volume}`);
  310. }
  311. if (isPlayerPaused) {
  312. player.playVideo();
  313. }
  314. // eslint-disable-next-line eqeqeq
  315. } else if (attributes.state == 'pause') {
  316. // if its not paused, pause it
  317. player.pauseVideo();
  318. this.processTime(player, attributes, true);
  319. }
  320. }
  321. /**
  322. * Check for time in attributes and if needed seek in current player
  323. * @param player the player to operate over
  324. * @param attributes the attributes with the player state we want
  325. * @param forceSeek whether seek should be forced
  326. */
  327. processTime(player, attributes, forceSeek) {
  328. if (forceSeek) {
  329. logger.info('Player seekTo:', attributes.time);
  330. player.seekTo(attributes.time);
  331. return;
  332. }
  333. // check received time and current time
  334. const currentPosition = player.getCurrentTime();
  335. const diff = Math.abs(attributes.time - currentPosition);
  336. // if we drift more than the interval for checking
  337. // sync, the interval is in milliseconds
  338. if (diff > updateInterval / 1000) {
  339. logger.info('Player seekTo:', attributes.time,
  340. ' current time is:', currentPosition, ' diff:', diff);
  341. player.seekTo(attributes.time);
  342. }
  343. }
  344. /**
  345. * Checks current state of the player and fire an event with the values.
  346. */
  347. fireSharedVideoEvent(sendPauseEvent) {
  348. // ignore update checks if we are not the owner of the video
  349. // or there is still no player defined or we are stopped
  350. // (in a process of stopping)
  351. if (!APP.conference.isLocalId(this.from) || !this.player
  352. || !this.isSharedVideoShown) {
  353. return;
  354. }
  355. const state = this.player.getPlayerState();
  356. // if its paused and haven't been pause - send paused
  357. if (state === YT.PlayerState.PAUSED && sendPauseEvent) {
  358. this.emitter.emit(UIEvents.UPDATE_SHARED_VIDEO,
  359. this.url, 'pause', this.player.getCurrentTime());
  360. } else if (state === YT.PlayerState.PLAYING) {
  361. // if its playing and it was paused - send update with time
  362. // if its playing and was playing just send update with time
  363. this.emitter.emit(UIEvents.UPDATE_SHARED_VIDEO,
  364. this.url, 'playing',
  365. this.player.getCurrentTime(),
  366. this.player.isMuted(),
  367. this.player.getVolume());
  368. }
  369. }
  370. /**
  371. * Updates video, if it's not playing and needs starting or if it's playing
  372. * and needs to be paused.
  373. * @param id the id of the sender of the command
  374. * @param url the video url
  375. * @param attributes
  376. */
  377. onSharedVideoUpdate(id, url, attributes) {
  378. // if we are sending the event ignore
  379. if (APP.conference.isLocalId(this.from)) {
  380. return;
  381. }
  382. if (!this.isSharedVideoShown) {
  383. this.onSharedVideoStart(id, url, attributes);
  384. return;
  385. }
  386. // eslint-disable-next-line no-negated-condition
  387. if (!this.player) {
  388. this.initialAttributes = attributes;
  389. } else {
  390. this.processVideoUpdate(this.player, attributes);
  391. }
  392. }
  393. /**
  394. * Stop shared video if it is currently showed. If the user started the
  395. * shared video is the one in the id (called when user
  396. * left and we want to remove video if the user sharing it left).
  397. * @param id the id of the sender of the command
  398. */
  399. onSharedVideoStop(id, attributes) {
  400. if (!this.isSharedVideoShown) {
  401. return;
  402. }
  403. if (this.from !== id) {
  404. return;
  405. }
  406. if (!this.player) {
  407. // if there is no error in the player till now,
  408. // store the initial attributes
  409. if (!this.errorInPlayer) {
  410. this.initialAttributes = attributes;
  411. return;
  412. }
  413. }
  414. this.emitter.removeListener(UIEvents.AUDIO_MUTED,
  415. this.localAudioMutedListener);
  416. this.localAudioMutedListener = null;
  417. APP.store.dispatch(participantLeft(this.url, APP.conference._room));
  418. VideoLayout.showLargeVideoContainer(SHARED_VIDEO_CONTAINER_TYPE, false)
  419. .then(() => {
  420. VideoLayout.removeLargeVideoContainer(
  421. SHARED_VIDEO_CONTAINER_TYPE);
  422. if (this.player) {
  423. this.player.destroy();
  424. this.player = null;
  425. } else if (this.errorInPlayer) {
  426. // if there is an error in player, remove that instance
  427. this.errorInPlayer.destroy();
  428. this.errorInPlayer = null;
  429. }
  430. this.smartAudioUnmute();
  431. // revert to original behavior (prevents pausing
  432. // for participants not sharing the video to pause it)
  433. $('#sharedVideo').css('pointer-events', 'auto');
  434. this.emitter.emit(
  435. UIEvents.UPDATE_SHARED_VIDEO, null, 'removed');
  436. });
  437. this.url = null;
  438. this.isSharedVideoShown = false;
  439. this.initialAttributes = null;
  440. }
  441. /**
  442. * Receives events for local audio mute/unmute by local user.
  443. * @param muted boolena whether it is muted or not.
  444. * @param {boolean} indicates if this mute was a result of user interaction,
  445. * i.e. pressing the mute button or it was programatically triggerred
  446. */
  447. onLocalAudioMuted(muted, userInteraction) {
  448. if (!this.player) {
  449. return;
  450. }
  451. if (muted) {
  452. this.mutedWithUserInteraction = userInteraction;
  453. } else if (this.player.getPlayerState() !== YT.PlayerState.PAUSED) {
  454. this.smartPlayerMute(true, false);
  455. // Check if we need to update other participants
  456. this.fireSharedVideoEvent();
  457. }
  458. }
  459. /**
  460. * Mutes / unmutes the player.
  461. * @param mute true to mute the shared video, false - otherwise.
  462. * @param {boolean} Indicates if this mute is a consequence of a network
  463. * video update or is called locally.
  464. */
  465. smartPlayerMute(mute, isVideoUpdate) {
  466. if (!this.player.isMuted() && mute) {
  467. this.player.mute();
  468. if (isVideoUpdate) {
  469. this.smartAudioUnmute();
  470. }
  471. } else if (this.player.isMuted() && !mute) {
  472. this.player.unMute();
  473. if (isVideoUpdate) {
  474. this.smartAudioMute();
  475. }
  476. }
  477. }
  478. /**
  479. * Smart mike unmute. If the mike is currently muted and it wasn't muted
  480. * by the user via the mike button and the volume of the shared video is on
  481. * we're unmuting the mike automatically.
  482. */
  483. smartAudioUnmute() {
  484. if (APP.conference.isLocalAudioMuted()
  485. && !this.mutedWithUserInteraction
  486. && !this.isSharedVideoVolumeOn()) {
  487. sendAnalytics(createEvent('audio.unmuted'));
  488. logger.log('Shared video: audio unmuted');
  489. this.emitter.emit(UIEvents.AUDIO_MUTED, false, false);
  490. }
  491. }
  492. /**
  493. * Smart mike mute. If the mike isn't currently muted and the shared video
  494. * volume is on we mute the mike.
  495. */
  496. smartAudioMute() {
  497. if (!APP.conference.isLocalAudioMuted()
  498. && this.isSharedVideoVolumeOn()) {
  499. sendAnalytics(createEvent('audio.muted'));
  500. logger.log('Shared video: audio muted');
  501. this.emitter.emit(UIEvents.AUDIO_MUTED, true, false);
  502. }
  503. }
  504. }
  505. /**
  506. * Container for shared video iframe.
  507. */
  508. class SharedVideoContainer extends LargeContainer {
  509. /**
  510. *
  511. */
  512. constructor({ url, iframe, player }) {
  513. super();
  514. this.$iframe = $(iframe);
  515. this.url = url;
  516. this.player = player;
  517. }
  518. /**
  519. *
  520. */
  521. show() {
  522. const self = this;
  523. return new Promise(resolve => {
  524. this.$iframe.fadeIn(300, () => {
  525. self.bodyBackground = document.body.style.background;
  526. document.body.style.background = 'black';
  527. this.$iframe.css({ opacity: 1 });
  528. APP.store.dispatch(dockToolbox(true));
  529. resolve();
  530. });
  531. });
  532. }
  533. /**
  534. *
  535. */
  536. hide() {
  537. const self = this;
  538. APP.store.dispatch(dockToolbox(false));
  539. return new Promise(resolve => {
  540. this.$iframe.fadeOut(300, () => {
  541. document.body.style.background = self.bodyBackground;
  542. this.$iframe.css({ opacity: 0 });
  543. resolve();
  544. });
  545. });
  546. }
  547. /**
  548. *
  549. */
  550. onHoverIn() {
  551. APP.store.dispatch(showToolbox());
  552. }
  553. /**
  554. *
  555. */
  556. get id() {
  557. return this.url;
  558. }
  559. /**
  560. *
  561. */
  562. resize(containerWidth, containerHeight) {
  563. let height, width;
  564. if (interfaceConfig.VERTICAL_FILMSTRIP) {
  565. height = containerHeight - getToolboxHeight();
  566. width = containerWidth - Filmstrip.getVerticalFilmstripWidth();
  567. } else {
  568. height = containerHeight - Filmstrip.getFilmstripHeight();
  569. width = containerWidth;
  570. }
  571. this.$iframe.width(width).height(height);
  572. }
  573. /**
  574. * @return {boolean} do not switch on dominant speaker event if on stage.
  575. */
  576. stayOnStage() {
  577. return false;
  578. }
  579. }
  580. /**
  581. * Checks if given string is youtube url.
  582. * @param {string} url string to check.
  583. * @returns {boolean}
  584. */
  585. function getYoutubeLink(url) {
  586. const p = /^(?:https?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))((\w|-){11})(?:\S+)?$/;// eslint-disable-line max-len
  587. return url.match(p) ? RegExp.$1 : false;
  588. }
  589. /**
  590. * Ask user if he want to close shared video.
  591. */
  592. function showStopVideoPropmpt() {
  593. return new Promise((resolve, reject) => {
  594. const submitFunction = function(e, v) {
  595. if (v) {
  596. resolve();
  597. } else {
  598. reject();
  599. }
  600. };
  601. const closeFunction = function() {
  602. dialog = null;
  603. };
  604. dialog = APP.UI.messageHandler.openTwoButtonDialog({
  605. titleKey: 'dialog.removeSharedVideoTitle',
  606. msgKey: 'dialog.removeSharedVideoMsg',
  607. leftButtonKey: 'dialog.Remove',
  608. submitFunction,
  609. closeFunction
  610. });
  611. });
  612. }
  613. /**
  614. * Ask user for shared video url to share with others.
  615. * Dialog validates client input to allow only youtube urls.
  616. */
  617. function requestVideoLink() {
  618. const i18n = APP.translation;
  619. const cancelButton = i18n.generateTranslationHTML('dialog.Cancel');
  620. const shareButton = i18n.generateTranslationHTML('dialog.Share');
  621. const backButton = i18n.generateTranslationHTML('dialog.Back');
  622. const linkError
  623. = i18n.generateTranslationHTML('dialog.shareVideoLinkError');
  624. return new Promise((resolve, reject) => {
  625. dialog = APP.UI.messageHandler.openDialogWithStates({
  626. state0: {
  627. titleKey: 'dialog.shareVideoTitle',
  628. html: `
  629. <input name='sharedVideoUrl' type='text'
  630. class='input-control'
  631. data-i18n='[placeholder]defaultLink'
  632. autofocus>`,
  633. persistent: false,
  634. buttons: [
  635. { title: cancelButton,
  636. value: false },
  637. { title: shareButton,
  638. value: true }
  639. ],
  640. focus: ':input:first',
  641. defaultButton: 1,
  642. submit(e, v, m, f) { // eslint-disable-line max-params
  643. e.preventDefault();
  644. if (!v) {
  645. reject('cancelled');
  646. dialog.close();
  647. return;
  648. }
  649. const sharedVideoUrl = f.sharedVideoUrl;
  650. if (!sharedVideoUrl) {
  651. return;
  652. }
  653. const urlValue
  654. = encodeURI(UIUtil.escapeHtml(sharedVideoUrl));
  655. const yVideoId = getYoutubeLink(urlValue);
  656. if (!yVideoId) {
  657. dialog.goToState('state1');
  658. return false;
  659. }
  660. resolve(yVideoId);
  661. dialog.close();
  662. }
  663. },
  664. state1: {
  665. titleKey: 'dialog.shareVideoTitle',
  666. html: linkError,
  667. persistent: false,
  668. buttons: [
  669. { title: cancelButton,
  670. value: false },
  671. { title: backButton,
  672. value: true }
  673. ],
  674. focus: ':input:first',
  675. defaultButton: 1,
  676. submit(e, v) {
  677. e.preventDefault();
  678. if (v === 0) {
  679. reject();
  680. dialog.close();
  681. } else {
  682. dialog.goToState('state0');
  683. }
  684. }
  685. }
  686. }, {
  687. close() {
  688. dialog = null;
  689. }
  690. }, {
  691. url: defaultSharedVideoLink
  692. });
  693. });
  694. }