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

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