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 26KB

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