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

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