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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845
  1. /* global $, APP, YT, interfaceConfig, onPlayerReady, onPlayerStateChange,
  2. onPlayerError */
  3. const logger = require('jitsi-meet-logger').getLogger(__filename);
  4. import UIUtil from '../util/UIUtil';
  5. import UIEvents from '../../../service/UI/UIEvents';
  6. import VideoLayout from '../videolayout/VideoLayout';
  7. import LargeContainer from '../videolayout/LargeContainer';
  8. import Filmstrip from '../videolayout/Filmstrip';
  9. import {
  10. createSharedVideoEvent as createEvent,
  11. sendAnalytics
  12. } from '../../../react/features/analytics';
  13. import {
  14. participantJoined,
  15. participantLeft
  16. } from '../../../react/features/base/participants';
  17. import { dockToolbox, showToolbox } from '../../../react/features/toolbox';
  18. import SharedVideoThumb from './SharedVideoThumb';
  19. export const SHARED_VIDEO_CONTAINER_TYPE = 'sharedvideo';
  20. /**
  21. * Example shared video link.
  22. * @type {string}
  23. */
  24. const defaultSharedVideoLink = 'https://www.youtube.com/watch?v=xNXN7CZk8X0';
  25. const updateInterval = 5000; // milliseconds
  26. /**
  27. * The dialog for user input (video link).
  28. * @type {null}
  29. */
  30. let dialog = null;
  31. /**
  32. * Manager of shared video.
  33. */
  34. export default class SharedVideoManager {
  35. /**
  36. *
  37. */
  38. constructor(emitter) {
  39. this.emitter = emitter;
  40. this.isSharedVideoShown = false;
  41. this.isPlayerAPILoaded = false;
  42. this.mutedWithUserInteraction = false;
  43. }
  44. /**
  45. * Indicates if the player volume is currently on. This will return true if
  46. * we have an available player, which is currently in a PLAYING state,
  47. * which isn't muted and has it's volume greater than 0.
  48. *
  49. * @returns {boolean} indicating if the volume of the shared video is
  50. * currently on.
  51. */
  52. isSharedVideoVolumeOn() {
  53. return this.player
  54. && this.player.getPlayerState() === YT.PlayerState.PLAYING
  55. && !this.player.isMuted()
  56. && this.player.getVolume() > 0;
  57. }
  58. /**
  59. * Indicates if the local user is the owner of the shared video.
  60. * @returns {*|boolean}
  61. */
  62. isSharedVideoOwner() {
  63. return this.from && APP.conference.isLocalId(this.from);
  64. }
  65. /**
  66. * Starts shared video by asking user for url, or if its already working
  67. * asks whether the user wants to stop sharing the video.
  68. */
  69. toggleSharedVideo() {
  70. if (dialog) {
  71. return;
  72. }
  73. if (!this.isSharedVideoShown) {
  74. requestVideoLink().then(
  75. url => {
  76. this.emitter.emit(
  77. UIEvents.UPDATE_SHARED_VIDEO, url, 'start');
  78. sendAnalytics(createEvent('started'));
  79. },
  80. err => {
  81. logger.log('SHARED VIDEO CANCELED', err);
  82. sendAnalytics(createEvent('canceled'));
  83. }
  84. );
  85. return;
  86. }
  87. if (APP.conference.isLocalId(this.from)) {
  88. showStopVideoPropmpt().then(
  89. () => {
  90. // make sure we stop updates for playing before we send stop
  91. // if we stop it after receiving self presence, we can end
  92. // up sending stop playing, and on the other end it will not
  93. // stop
  94. if (this.intervalId) {
  95. clearInterval(this.intervalId);
  96. this.intervalId = null;
  97. }
  98. this.emitter.emit(
  99. UIEvents.UPDATE_SHARED_VIDEO, this.url, 'stop');
  100. sendAnalytics(createEvent('stopped'));
  101. },
  102. () => {}); // eslint-disable-line no-empty-function
  103. } else {
  104. APP.UI.messageHandler.showWarning({
  105. descriptionKey: 'dialog.alreadySharedVideoMsg',
  106. titleKey: 'dialog.alreadySharedVideoTitle'
  107. });
  108. sendAnalytics(createEvent('already.shared'));
  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. sendAnalytics(createEvent('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. sendAnalytics(createEvent(
  229. 'volume.changed',
  230. {
  231. volume: event.data.volume,
  232. muted: event.data.muted
  233. }));
  234. };
  235. window.onPlayerReady = function(event) {
  236. const player = event.target;
  237. // do not relay on autoplay as it is not sending all of the events
  238. // in onPlayerStateChange
  239. player.playVideo();
  240. const thumb = new SharedVideoThumb(
  241. self.url, SHARED_VIDEO_CONTAINER_TYPE, VideoLayout);
  242. thumb.setDisplayName('YouTube');
  243. VideoLayout.addRemoteVideoContainer(self.url, thumb);
  244. VideoLayout.resizeThumbnails(false, true);
  245. const iframe = player.getIframe();
  246. // eslint-disable-next-line no-use-before-define
  247. self.sharedVideo = new SharedVideoContainer(
  248. { url,
  249. iframe,
  250. player });
  251. // prevents pausing participants not sharing the video
  252. // to pause the video
  253. if (!APP.conference.isLocalId(self.from)) {
  254. $('#sharedVideo').css('pointer-events', 'none');
  255. }
  256. VideoLayout.addLargeVideoContainer(
  257. SHARED_VIDEO_CONTAINER_TYPE, self.sharedVideo);
  258. APP.store.dispatch(participantJoined({
  259. id: self.url,
  260. isBot: true,
  261. name: 'YouTube'
  262. }));
  263. VideoLayout.handleVideoThumbClicked(self.url);
  264. // If we are sending the command and we are starting the player
  265. // we need to continuously send the player current time position
  266. if (APP.conference.isLocalId(self.from)) {
  267. self.intervalId = setInterval(
  268. self.fireSharedVideoEvent.bind(self),
  269. updateInterval);
  270. }
  271. };
  272. window.onPlayerError = function(event) {
  273. logger.error('Error in the player:', event.data);
  274. // store the error player, so we can remove it
  275. self.errorInPlayer = event.target;
  276. };
  277. }
  278. /**
  279. * Process attributes, whether player needs to be paused or seek.
  280. * @param player the player to operate over
  281. * @param attributes the attributes with the player state we want
  282. */
  283. processVideoUpdate(player, attributes) {
  284. if (!attributes) {
  285. return;
  286. }
  287. // eslint-disable-next-line eqeqeq
  288. if (attributes.state == 'playing') {
  289. const isPlayerPaused
  290. = this.player.getPlayerState() === YT.PlayerState.PAUSED;
  291. // If our player is currently paused force the seek.
  292. this.processTime(player, attributes, isPlayerPaused);
  293. // Process mute.
  294. const isAttrMuted = attributes.muted === 'true';
  295. if (player.isMuted() !== isAttrMuted) {
  296. this.smartPlayerMute(isAttrMuted, true);
  297. }
  298. // Process volume
  299. if (!isAttrMuted
  300. && attributes.volume !== undefined
  301. // eslint-disable-next-line eqeqeq
  302. && player.getVolume() != attributes.volume) {
  303. player.setVolume(attributes.volume);
  304. logger.info(`Player change of volume:${attributes.volume}`);
  305. this.showSharedVideoMutedPopup(false);
  306. }
  307. if (isPlayerPaused) {
  308. player.playVideo();
  309. }
  310. // eslint-disable-next-line eqeqeq
  311. } else if (attributes.state == 'pause') {
  312. // if its not paused, pause it
  313. player.pauseVideo();
  314. this.processTime(player, attributes, true);
  315. }
  316. }
  317. /**
  318. * Check for time in attributes and if needed seek in current player
  319. * @param player the player to operate over
  320. * @param attributes the attributes with the player state we want
  321. * @param forceSeek whether seek should be forced
  322. */
  323. processTime(player, attributes, forceSeek) {
  324. if (forceSeek) {
  325. logger.info('Player seekTo:', attributes.time);
  326. player.seekTo(attributes.time);
  327. return;
  328. }
  329. // check received time and current time
  330. const currentPosition = player.getCurrentTime();
  331. const diff = Math.abs(attributes.time - currentPosition);
  332. // if we drift more than the interval for checking
  333. // sync, the interval is in milliseconds
  334. if (diff > updateInterval / 1000) {
  335. logger.info('Player seekTo:', attributes.time,
  336. ' current time is:', currentPosition, ' diff:', diff);
  337. player.seekTo(attributes.time);
  338. }
  339. }
  340. /**
  341. * Checks current state of the player and fire an event with the values.
  342. */
  343. fireSharedVideoEvent(sendPauseEvent) {
  344. // ignore update checks if we are not the owner of the video
  345. // or there is still no player defined or we are stopped
  346. // (in a process of stopping)
  347. if (!APP.conference.isLocalId(this.from) || !this.player
  348. || !this.isSharedVideoShown) {
  349. return;
  350. }
  351. const state = this.player.getPlayerState();
  352. // if its paused and haven't been pause - send paused
  353. if (state === YT.PlayerState.PAUSED && sendPauseEvent) {
  354. this.emitter.emit(UIEvents.UPDATE_SHARED_VIDEO,
  355. this.url, 'pause', this.player.getCurrentTime());
  356. } else if (state === YT.PlayerState.PLAYING) {
  357. // if its playing and it was paused - send update with time
  358. // if its playing and was playing just send update with time
  359. this.emitter.emit(UIEvents.UPDATE_SHARED_VIDEO,
  360. this.url, 'playing',
  361. this.player.getCurrentTime(),
  362. this.player.isMuted(),
  363. this.player.getVolume());
  364. }
  365. }
  366. /**
  367. * Updates video, if it's not playing and needs starting or if it's playing
  368. * and needs to be paused.
  369. * @param id the id of the sender of the command
  370. * @param url the video url
  371. * @param attributes
  372. */
  373. onSharedVideoUpdate(id, url, attributes) {
  374. // if we are sending the event ignore
  375. if (APP.conference.isLocalId(this.from)) {
  376. return;
  377. }
  378. if (!this.isSharedVideoShown) {
  379. this.onSharedVideoStart(id, url, attributes);
  380. return;
  381. }
  382. // eslint-disable-next-line no-negated-condition
  383. if (!this.player) {
  384. this.initialAttributes = attributes;
  385. } else {
  386. this.processVideoUpdate(this.player, attributes);
  387. }
  388. }
  389. /**
  390. * Stop shared video if it is currently showed. If the user started the
  391. * shared video is the one in the id (called when user
  392. * left and we want to remove video if the user sharing it left).
  393. * @param id the id of the sender of the command
  394. */
  395. onSharedVideoStop(id, attributes) {
  396. if (!this.isSharedVideoShown) {
  397. return;
  398. }
  399. if (this.from !== id) {
  400. return;
  401. }
  402. if (!this.player) {
  403. // if there is no error in the player till now,
  404. // store the initial attributes
  405. if (!this.errorInPlayer) {
  406. this.initialAttributes = attributes;
  407. return;
  408. }
  409. }
  410. this.emitter.removeListener(UIEvents.AUDIO_MUTED,
  411. this.localAudioMutedListener);
  412. this.localAudioMutedListener = null;
  413. VideoLayout.removeParticipantContainer(this.url);
  414. VideoLayout.showLargeVideoContainer(SHARED_VIDEO_CONTAINER_TYPE, false)
  415. .then(() => {
  416. VideoLayout.removeLargeVideoContainer(
  417. SHARED_VIDEO_CONTAINER_TYPE);
  418. if (this.player) {
  419. this.player.destroy();
  420. this.player = null;
  421. } else if (this.errorInPlayer) {
  422. // if there is an error in player, remove that instance
  423. this.errorInPlayer.destroy();
  424. this.errorInPlayer = null;
  425. }
  426. this.smartAudioUnmute();
  427. // revert to original behavior (prevents pausing
  428. // for participants not sharing the video to pause it)
  429. $('#sharedVideo').css('pointer-events', 'auto');
  430. this.emitter.emit(
  431. UIEvents.UPDATE_SHARED_VIDEO, null, 'removed');
  432. });
  433. APP.store.dispatch(participantLeft(this.url));
  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. this.showSharedVideoMutedPopup(mute);
  475. }
  476. /**
  477. * Smart mike unmute. If the mike is currently muted and it wasn't muted
  478. * by the user via the mike button and the volume of the shared video is on
  479. * we're unmuting the mike automatically.
  480. */
  481. smartAudioUnmute() {
  482. if (APP.conference.isLocalAudioMuted()
  483. && !this.mutedWithUserInteraction
  484. && !this.isSharedVideoVolumeOn()) {
  485. sendAnalytics(createEvent('audio.unmuted'));
  486. logger.log('Shared video: audio unmuted');
  487. this.emitter.emit(UIEvents.AUDIO_MUTED, false, false);
  488. this.showMicMutedPopup(false);
  489. }
  490. }
  491. /**
  492. * Smart mike mute. If the mike isn't currently muted and the shared video
  493. * volume is on we mute the mike.
  494. */
  495. smartAudioMute() {
  496. if (!APP.conference.isLocalAudioMuted()
  497. && this.isSharedVideoVolumeOn()) {
  498. sendAnalytics(createEvent('audio.muted'));
  499. logger.log('Shared video: audio muted');
  500. this.emitter.emit(UIEvents.AUDIO_MUTED, true, false);
  501. this.showMicMutedPopup(true);
  502. }
  503. }
  504. /**
  505. * Shows a popup under the microphone toolbar icon that notifies the user
  506. * of automatic mute after a shared video has started.
  507. * @param show boolean, show or hide the notification
  508. */
  509. showMicMutedPopup(show) {
  510. if (show) {
  511. this.showSharedVideoMutedPopup(false);
  512. }
  513. APP.UI.showCustomToolbarPopup(
  514. 'microphone', 'micMutedPopup', show, 5000);
  515. }
  516. /**
  517. * Shows a popup under the shared video toolbar icon that notifies the user
  518. * of automatic mute of the shared video after the user has unmuted their
  519. * mic.
  520. * @param show boolean, show or hide the notification
  521. */
  522. showSharedVideoMutedPopup(show) {
  523. if (show) {
  524. this.showMicMutedPopup(false);
  525. }
  526. APP.UI.showCustomToolbarPopup(
  527. 'sharedvideo', 'sharedVideoMutedPopup', show, 5000);
  528. }
  529. }
  530. /**
  531. * Container for shared video iframe.
  532. */
  533. class SharedVideoContainer extends LargeContainer {
  534. /**
  535. *
  536. */
  537. constructor({ url, iframe, player }) {
  538. super();
  539. this.$iframe = $(iframe);
  540. this.url = url;
  541. this.player = player;
  542. }
  543. /**
  544. *
  545. */
  546. show() {
  547. const self = this;
  548. return new Promise(resolve => {
  549. this.$iframe.fadeIn(300, () => {
  550. self.bodyBackground = document.body.style.background;
  551. document.body.style.background = 'black';
  552. this.$iframe.css({ opacity: 1 });
  553. APP.store.dispatch(dockToolbox(true));
  554. resolve();
  555. });
  556. });
  557. }
  558. /**
  559. *
  560. */
  561. hide() {
  562. const self = this;
  563. APP.store.dispatch(dockToolbox(false));
  564. return new Promise(resolve => {
  565. this.$iframe.fadeOut(300, () => {
  566. document.body.style.background = self.bodyBackground;
  567. this.$iframe.css({ opacity: 0 });
  568. resolve();
  569. });
  570. });
  571. }
  572. /**
  573. *
  574. */
  575. onHoverIn() {
  576. APP.store.dispatch(showToolbox());
  577. }
  578. /**
  579. *
  580. */
  581. get id() {
  582. return this.url;
  583. }
  584. /**
  585. *
  586. */
  587. resize(containerWidth, containerHeight) {
  588. let height, width;
  589. if (interfaceConfig.VERTICAL_FILMSTRIP) {
  590. height = containerHeight;
  591. width = containerWidth - Filmstrip.getFilmstripWidth();
  592. } else {
  593. height = containerHeight - Filmstrip.getFilmstripHeight();
  594. width = containerWidth;
  595. }
  596. this.$iframe.width(width).height(height);
  597. }
  598. /**
  599. * @return {boolean} do not switch on dominant speaker event if on stage.
  600. */
  601. stayOnStage() {
  602. return false;
  603. }
  604. }
  605. /**
  606. * Checks if given string is youtube url.
  607. * @param {string} url string to check.
  608. * @returns {boolean}
  609. */
  610. function getYoutubeLink(url) {
  611. const p = /^(?:https?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))((\w|-){11})(?:\S+)?$/;// eslint-disable-line max-len
  612. return url.match(p) ? RegExp.$1 : false;
  613. }
  614. /**
  615. * Ask user if he want to close shared video.
  616. */
  617. function showStopVideoPropmpt() {
  618. return new Promise((resolve, reject) => {
  619. const submitFunction = function(e, v) {
  620. if (v) {
  621. resolve();
  622. } else {
  623. reject();
  624. }
  625. };
  626. const closeFunction = function() {
  627. dialog = null;
  628. };
  629. dialog = APP.UI.messageHandler.openTwoButtonDialog({
  630. titleKey: 'dialog.removeSharedVideoTitle',
  631. msgKey: 'dialog.removeSharedVideoMsg',
  632. leftButtonKey: 'dialog.Remove',
  633. submitFunction,
  634. closeFunction
  635. });
  636. });
  637. }
  638. /**
  639. * Ask user for shared video url to share with others.
  640. * Dialog validates client input to allow only youtube urls.
  641. */
  642. function requestVideoLink() {
  643. const i18n = APP.translation;
  644. const cancelButton = i18n.generateTranslationHTML('dialog.Cancel');
  645. const shareButton = i18n.generateTranslationHTML('dialog.Share');
  646. const backButton = i18n.generateTranslationHTML('dialog.Back');
  647. const linkError
  648. = i18n.generateTranslationHTML('dialog.shareVideoLinkError');
  649. return new Promise((resolve, reject) => {
  650. dialog = APP.UI.messageHandler.openDialogWithStates({
  651. state0: {
  652. titleKey: 'dialog.shareVideoTitle',
  653. html: `
  654. <input name='sharedVideoUrl' type='text'
  655. class='input-control'
  656. data-i18n='[placeholder]defaultLink'
  657. autofocus>`,
  658. persistent: false,
  659. buttons: [
  660. { title: cancelButton,
  661. value: false },
  662. { title: shareButton,
  663. value: true }
  664. ],
  665. focus: ':input:first',
  666. defaultButton: 1,
  667. submit(e, v, m, f) { // eslint-disable-line max-params
  668. e.preventDefault();
  669. if (!v) {
  670. reject('cancelled');
  671. dialog.close();
  672. return;
  673. }
  674. const sharedVideoUrl = f.sharedVideoUrl;
  675. if (!sharedVideoUrl) {
  676. return;
  677. }
  678. const urlValue
  679. = encodeURI(UIUtil.escapeHtml(sharedVideoUrl));
  680. const yVideoId = getYoutubeLink(urlValue);
  681. if (!yVideoId) {
  682. dialog.goToState('state1');
  683. return false;
  684. }
  685. resolve(yVideoId);
  686. dialog.close();
  687. }
  688. },
  689. state1: {
  690. titleKey: 'dialog.shareVideoTitle',
  691. html: linkError,
  692. persistent: false,
  693. buttons: [
  694. { title: cancelButton,
  695. value: false },
  696. { title: backButton,
  697. value: true }
  698. ],
  699. focus: ':input:first',
  700. defaultButton: 1,
  701. submit(e, v) {
  702. e.preventDefault();
  703. if (v === 0) {
  704. reject();
  705. dialog.close();
  706. } else {
  707. dialog.goToState('state0');
  708. }
  709. }
  710. }
  711. }, {
  712. close() {
  713. dialog = null;
  714. }
  715. }, {
  716. url: defaultSharedVideoLink
  717. });
  718. });
  719. }