您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

SharedVideo.js 26KB

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