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

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