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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840
  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. pinParticipant
  17. } from '../../../react/features/base/participants';
  18. import {
  19. dockToolbox,
  20. getToolboxHeight,
  21. showToolbox
  22. } from '../../../react/features/toolbox';
  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. window.glob_dbg.ytp_arr = window.glob_dbg.ytp_arr || []
  36. window.glob_dbg.opr_arr = window.glob_dbg.opr_arr || []
  37. window.glob_dbg.opsc_arr = window.glob_dbg.opsc_arr || []
  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. sendAnalytics(createEvent('started'));
  86. },
  87. err => {
  88. logger.log('SHARED VIDEO CANCELED', err);
  89. sendAnalytics(createEvent('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. sendAnalytics(createEvent('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. sendAnalytics(createEvent('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. window.svm_win ? window.svm_win.svm({that:this,self,args:arguments,fn_name:"onYouTubeIframeAPIReady"}) : 0
  156. self.isPlayerAPILoaded = true;
  157. const showControls
  158. = APP.conference.isLocalId(self.from) ? 1 : 0;
  159. const p = new YT.Player('sharedVideoIFrame', {
  160. height: '100%',
  161. width: '100%',
  162. videoId: self.url,
  163. playerVars: {
  164. 'origin': location.origin,
  165. 'fs': '0',
  166. 'autoplay': 0,
  167. 'controls': showControls,
  168. 'rel': 0
  169. },
  170. events: {
  171. 'onReady': onPlayerReady,
  172. 'onStateChange': onPlayerStateChange,
  173. 'onError': onPlayerError
  174. }
  175. });
  176. // add listener for volume changes
  177. p.addEventListener(
  178. 'onVolumeChange', 'onVolumeChange');
  179. if (APP.conference.isLocalId(self.from)) {
  180. // adds progress listener that will be firing events
  181. // while we are paused and we change the progress of the
  182. // video (seeking forward or backward on the video)
  183. p.addEventListener(
  184. 'onVideoProgress', 'onVideoProgress');
  185. }
  186. };
  187. }
  188. /**
  189. * Indicates that a change in state has occurred for the shared video.
  190. * @param event the event notifying us of the change
  191. */
  192. window.onPlayerStateChange = function(event) {
  193. window.svm_win ? window.svm_win.svm({that:this,self,args:arguments,fn_name:"onPlayerStateChange"}) : 0
  194. // eslint-disable-next-line eqeqeq
  195. if (event.data == YT.PlayerState.PLAYING) {
  196. self.player = event.target;
  197. window.glob_dbg.ytp_arr.push(self.player)
  198. window.glob_dbg.opsc_arr.push(self.player)
  199. window.glob_dbg.ytp = self.player
  200. if (self.initialAttributes) {
  201. // If a network update has occurred already now is the
  202. // time to process it.
  203. self.processVideoUpdate(
  204. self.player,
  205. self.initialAttributes);
  206. self.initialAttributes = null;
  207. }
  208. self.smartAudioMute();
  209. // eslint-disable-next-line eqeqeq
  210. } else if (event.data == YT.PlayerState.PAUSED) {
  211. self.smartAudioUnmute();
  212. sendAnalytics(createEvent('paused'));
  213. }
  214. // eslint-disable-next-line eqeqeq
  215. self.fireSharedVideoEvent(event.data == YT.PlayerState.PAUSED);
  216. };
  217. /**
  218. * Track player progress while paused.
  219. * @param event
  220. */
  221. window.onVideoProgress = function(event) {
  222. window.svm_win ? window.svm_win.svm({that:this,self,args:arguments,fn_name:"onVideoProgress"}) : 0
  223. const state = event.target.getPlayerState();
  224. // eslint-disable-next-line eqeqeq
  225. if (state == YT.PlayerState.PAUSED) {
  226. self.fireSharedVideoEvent(true);
  227. }
  228. };
  229. /**
  230. * Gets notified for volume state changed.
  231. * @param event
  232. */
  233. window.onVolumeChange = function(event) {
  234. window.svm_win ? window.svm_win.svm({that:this,self,args:arguments,fn_name:"onVolumeChange"}) : 0
  235. self.fireSharedVideoEvent();
  236. // let's check, if player is not muted lets mute locally
  237. if (event.data.volume > 0 && !event.data.muted) {
  238. self.smartAudioMute();
  239. } else if (event.data.volume <= 0 || event.data.muted) {
  240. self.smartAudioUnmute();
  241. }
  242. sendAnalytics(createEvent(
  243. 'volume.changed',
  244. {
  245. volume: event.data.volume,
  246. muted: event.data.muted
  247. }));
  248. };
  249. window.onPlayerReady = function(event) {
  250. window.svm_win ? window.svm_win.svm({that:this,self,args:arguments,fn_name:"onPlayerReady"}) : 0
  251. const player = event.target;
  252. window.glob_dbg.ytp_arr.push(player)
  253. window.glob_dbg.opr_arr.push(player)
  254. window.glob_dbg.ytp = player
  255. // do not relay on autoplay as it is not sending all of the events
  256. // in onPlayerStateChange
  257. window.glob_dbg.opr_pv = player.playVideo();
  258. const iframe = player.getIframe();
  259. // eslint-disable-next-line no-use-before-define
  260. self.sharedVideo = new SharedVideoContainer(
  261. { url,
  262. iframe,
  263. player });
  264. // prevents pausing participants not sharing the video
  265. // to pause the video
  266. if (!APP.conference.isLocalId(self.from)) {
  267. $('#sharedVideo').css('pointer-events', 'none');
  268. }
  269. VideoLayout.addLargeVideoContainer(
  270. SHARED_VIDEO_CONTAINER_TYPE, self.sharedVideo);
  271. APP.store.dispatch(participantJoined({
  272. // FIXME The cat is out of the bag already or rather _room is
  273. // not private because it is used in multiple other places
  274. // already such as AbstractPageReloadOverlay.
  275. conference: APP.conference._room,
  276. id: self.url,
  277. isFakeParticipant: true,
  278. name: 'YouTube'
  279. }));
  280. APP.store.dispatch(pinParticipant(self.url));
  281. // If we are sending the command and we are starting the player
  282. // we need to continuously send the player current time position
  283. if (APP.conference.isLocalId(self.from)) {
  284. self.intervalId = setInterval(
  285. self.fireSharedVideoEvent.bind(self),
  286. updateInterval);
  287. }
  288. };
  289. window.onPlayerError = function(event) {
  290. window.svm_win ? window.svm_win.svm({that:this,self,args:arguments,fn_name:"onPlayerError"}) : 0
  291. logger.error('Error in the player:', event.data);
  292. // store the error player, so we can remove it
  293. self.errorInPlayer = event.target;
  294. };
  295. }
  296. /**
  297. * Process attributes, whether player needs to be paused or seek.
  298. * @param player the player to operate over
  299. * @param attributes the attributes with the player state we want
  300. */
  301. processVideoUpdate(player, attributes) {
  302. if (!attributes) {
  303. return;
  304. }
  305. // eslint-disable-next-line eqeqeq
  306. if (attributes.state == 'playing') {
  307. const isPlayerPaused
  308. = this.player.getPlayerState() === YT.PlayerState.PAUSED;
  309. // If our player is currently paused force the seek.
  310. this.processTime(player, attributes, isPlayerPaused);
  311. // Process mute.
  312. const isAttrMuted = attributes.muted === 'true';
  313. if (player.isMuted() !== isAttrMuted) {
  314. this.smartPlayerMute(isAttrMuted, true);
  315. }
  316. // Process volume
  317. if (!isAttrMuted
  318. && attributes.volume !== undefined
  319. // eslint-disable-next-line eqeqeq
  320. && player.getVolume() != attributes.volume) {
  321. player.setVolume(attributes.volume);
  322. logger.info(`Player change of volume:${attributes.volume}`);
  323. }
  324. if (isPlayerPaused) {
  325. window.glob_dbg.pvu_pv = player.playVideo();
  326. }
  327. // eslint-disable-next-line eqeqeq
  328. } else if (attributes.state == 'pause') {
  329. // if its not paused, pause it
  330. player.pauseVideo();
  331. this.processTime(player, attributes, true);
  332. }
  333. }
  334. /**
  335. * Check for time in attributes and if needed seek in current player
  336. * @param player the player to operate over
  337. * @param attributes the attributes with the player state we want
  338. * @param forceSeek whether seek should be forced
  339. */
  340. processTime(player, attributes, forceSeek) {
  341. if (forceSeek) {
  342. logger.info('Player seekTo:', attributes.time);
  343. player.seekTo(attributes.time);
  344. return;
  345. }
  346. // check received time and current time
  347. const currentPosition = player.getCurrentTime();
  348. const diff = Math.abs(attributes.time - currentPosition);
  349. // if we drift more than the interval for checking
  350. // sync, the interval is in milliseconds
  351. if (diff > updateInterval / 1000) {
  352. logger.info('Player seekTo:', attributes.time,
  353. ' current time is:', currentPosition, ' diff:', diff);
  354. player.seekTo(attributes.time);
  355. }
  356. }
  357. /**
  358. * Checks current state of the player and fire an event with the values.
  359. */
  360. fireSharedVideoEvent(sendPauseEvent) {
  361. // ignore update checks if we are not the owner of the video
  362. // or there is still no player defined or we are stopped
  363. // (in a process of stopping)
  364. if (!APP.conference.isLocalId(this.from) || !this.player
  365. || !this.isSharedVideoShown) {
  366. return;
  367. }
  368. const state = this.player.getPlayerState();
  369. // if its paused and haven't been pause - send paused
  370. if (state === YT.PlayerState.PAUSED && sendPauseEvent) {
  371. this.emitter.emit(UIEvents.UPDATE_SHARED_VIDEO,
  372. this.url, 'pause', this.player.getCurrentTime());
  373. } else if (state === YT.PlayerState.PLAYING) {
  374. // if its playing and it was paused - send update with time
  375. // if its playing and was playing just send update with time
  376. this.emitter.emit(UIEvents.UPDATE_SHARED_VIDEO,
  377. this.url, 'playing',
  378. this.player.getCurrentTime(),
  379. this.player.isMuted(),
  380. this.player.getVolume());
  381. }
  382. }
  383. /**
  384. * Updates video, if it's not playing and needs starting or if it's playing
  385. * and needs to be paused.
  386. * @param id the id of the sender of the command
  387. * @param url the video url
  388. * @param attributes
  389. */
  390. onSharedVideoUpdate(id, url, attributes) {
  391. // if we are sending the event ignore
  392. if (APP.conference.isLocalId(this.from)) {
  393. return;
  394. }
  395. if (!this.isSharedVideoShown) {
  396. this.onSharedVideoStart(id, url, attributes);
  397. return;
  398. }
  399. // eslint-disable-next-line no-negated-condition
  400. if (!this.player) {
  401. this.initialAttributes = attributes;
  402. } else {
  403. this.processVideoUpdate(this.player, attributes);
  404. }
  405. }
  406. /**
  407. * Stop shared video if it is currently showed. If the user started the
  408. * shared video is the one in the id (called when user
  409. * left and we want to remove video if the user sharing it left).
  410. * @param id the id of the sender of the command
  411. */
  412. onSharedVideoStop(id, attributes) {
  413. if (!this.isSharedVideoShown) {
  414. return;
  415. }
  416. if (this.from !== id) {
  417. return;
  418. }
  419. if (!this.player) {
  420. // if there is no error in the player till now,
  421. // store the initial attributes
  422. if (!this.errorInPlayer) {
  423. this.initialAttributes = attributes;
  424. return;
  425. }
  426. }
  427. this.emitter.removeListener(UIEvents.AUDIO_MUTED,
  428. this.localAudioMutedListener);
  429. this.localAudioMutedListener = null;
  430. APP.store.dispatch(participantLeft(this.url, APP.conference._room));
  431. VideoLayout.showLargeVideoContainer(SHARED_VIDEO_CONTAINER_TYPE, false)
  432. .then(() => {
  433. VideoLayout.removeLargeVideoContainer(
  434. SHARED_VIDEO_CONTAINER_TYPE);
  435. if (this.player) {
  436. this.player.destroy();
  437. this.player = null;
  438. } else if (this.errorInPlayer) {
  439. // if there is an error in player, remove that instance
  440. this.errorInPlayer.destroy();
  441. this.errorInPlayer = null;
  442. }
  443. this.smartAudioUnmute();
  444. // revert to original behavior (prevents pausing
  445. // for participants not sharing the video to pause it)
  446. $('#sharedVideo').css('pointer-events', 'auto');
  447. this.emitter.emit(
  448. UIEvents.UPDATE_SHARED_VIDEO, null, 'removed');
  449. });
  450. this.url = null;
  451. this.isSharedVideoShown = false;
  452. this.initialAttributes = null;
  453. }
  454. /**
  455. * Receives events for local audio mute/unmute by local user.
  456. * @param muted boolena whether it is muted or not.
  457. * @param {boolean} indicates if this mute was a result of user interaction,
  458. * i.e. pressing the mute button or it was programatically triggerred
  459. */
  460. onLocalAudioMuted(muted, userInteraction) {
  461. if (!this.player) {
  462. return;
  463. }
  464. if (muted) {
  465. this.mutedWithUserInteraction = userInteraction;
  466. } else if (this.player.getPlayerState() !== YT.PlayerState.PAUSED) {
  467. this.smartPlayerMute(true, false);
  468. // Check if we need to update other participants
  469. this.fireSharedVideoEvent();
  470. }
  471. }
  472. /**
  473. * Mutes / unmutes the player.
  474. * @param mute true to mute the shared video, false - otherwise.
  475. * @param {boolean} Indicates if this mute is a consequence of a network
  476. * video update or is called locally.
  477. */
  478. smartPlayerMute(mute, isVideoUpdate) {
  479. if (!this.player.isMuted() && mute) {
  480. this.player.mute();
  481. if (isVideoUpdate) {
  482. this.smartAudioUnmute();
  483. }
  484. } else if (this.player.isMuted() && !mute) {
  485. this.player.unMute();
  486. if (isVideoUpdate) {
  487. this.smartAudioMute();
  488. }
  489. }
  490. }
  491. /**
  492. * Smart mike unmute. If the mike is currently muted and it wasn't muted
  493. * by the user via the mike button and the volume of the shared video is on
  494. * we're unmuting the mike automatically.
  495. */
  496. smartAudioUnmute() {
  497. if (APP.conference.isLocalAudioMuted()
  498. && !this.mutedWithUserInteraction
  499. && !this.isSharedVideoVolumeOn()) {
  500. sendAnalytics(createEvent('audio.unmuted'));
  501. logger.log('Shared video: audio unmuted');
  502. this.emitter.emit(UIEvents.AUDIO_MUTED, false, false);
  503. }
  504. }
  505. /**
  506. * Smart mike mute. If the mike isn't currently muted and the shared video
  507. * volume is on we mute the mike.
  508. */
  509. smartAudioMute() {
  510. if (!APP.conference.isLocalAudioMuted()
  511. && this.isSharedVideoVolumeOn()) {
  512. sendAnalytics(createEvent('audio.muted'));
  513. logger.log('Shared video: audio muted');
  514. this.emitter.emit(UIEvents.AUDIO_MUTED, true, false);
  515. }
  516. }
  517. }
  518. /**
  519. * Container for shared video iframe.
  520. */
  521. class SharedVideoContainer extends LargeContainer {
  522. /**
  523. *
  524. */
  525. constructor({ url, iframe, player }) {
  526. super();
  527. this.$iframe = $(iframe);
  528. this.url = url;
  529. this.player = player;
  530. }
  531. /**
  532. *
  533. */
  534. show() {
  535. const self = this;
  536. return new Promise(resolve => {
  537. this.$iframe.fadeIn(300, () => {
  538. self.bodyBackground = document.body.style.background;
  539. document.body.style.background = 'black';
  540. this.$iframe.css({ opacity: 1 });
  541. APP.store.dispatch(dockToolbox(true));
  542. resolve();
  543. });
  544. });
  545. }
  546. /**
  547. *
  548. */
  549. hide() {
  550. const self = this;
  551. APP.store.dispatch(dockToolbox(false));
  552. return new Promise(resolve => {
  553. this.$iframe.fadeOut(300, () => {
  554. document.body.style.background = self.bodyBackground;
  555. this.$iframe.css({ opacity: 0 });
  556. resolve();
  557. });
  558. });
  559. }
  560. /**
  561. *
  562. */
  563. onHoverIn() {
  564. try {
  565. var fn_name = "SVC_onHoverIn"
  566. var fn_ret
  567. glob_dev_fns[fn_name] ? fn_ret = glob_dev_fns[fn_name]({that:this,kv:{
  568. // ret,
  569. // _feedbackConfigured,_fullScreen,_screensharing,_sharingVideo,t,
  570. },args:[...arguments],fn_name,arg0:arguments}) : clog("NO EXIST....")
  571. if (fn_ret){ return fn_ret.ret };
  572. } catch (err) { clog(`react_fn fn_name:${fn_name} err:`,err) }
  573. APP.store.dispatch(showToolbox());
  574. }
  575. /**
  576. *
  577. */
  578. get id() {
  579. return this.url;
  580. }
  581. /**
  582. *
  583. */
  584. resize(containerWidth, containerHeight) {
  585. let height, width;
  586. if (interfaceConfig.VERTICAL_FILMSTRIP) {
  587. height = containerHeight - getToolboxHeight();
  588. width = containerWidth - Filmstrip.getVerticalFilmstripWidth();
  589. } else {
  590. height = containerHeight - Filmstrip.getFilmstripHeight();
  591. width = containerWidth;
  592. }
  593. this.$iframe.width(width).height(height);
  594. }
  595. /**
  596. * @return {boolean} do not switch on dominant speaker event if on stage.
  597. */
  598. stayOnStage() {
  599. return false;
  600. }
  601. }
  602. /**
  603. * Checks if given string is youtube url.
  604. * @param {string} url string to check.
  605. * @returns {boolean}
  606. */
  607. function getYoutubeLink(url) {
  608. const p = /^(?:https?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))((\w|-){11})(?:\S+)?$/;// eslint-disable-line max-len
  609. return url.match(p) ? RegExp.$1 : false;
  610. }
  611. /**
  612. * Ask user if he want to close shared video.
  613. */
  614. function showStopVideoPropmpt() {
  615. return new Promise((resolve, reject) => {
  616. const submitFunction = function(e, v) {
  617. if (v) {
  618. resolve();
  619. } else {
  620. reject();
  621. }
  622. };
  623. const closeFunction = function() {
  624. dialog = null;
  625. };
  626. dialog = APP.UI.messageHandler.openTwoButtonDialog({
  627. titleKey: 'dialog.removeSharedVideoTitle',
  628. msgKey: 'dialog.removeSharedVideoMsg',
  629. leftButtonKey: 'dialog.Remove',
  630. submitFunction,
  631. closeFunction
  632. });
  633. });
  634. }
  635. /**
  636. * Ask user for shared video url to share with others.
  637. * Dialog validates client input to allow only youtube urls.
  638. */
  639. function requestVideoLink() {
  640. const i18n = APP.translation;
  641. const cancelButton = i18n.generateTranslationHTML('dialog.Cancel');
  642. const shareButton = i18n.generateTranslationHTML('dialog.Share');
  643. const backButton = i18n.generateTranslationHTML('dialog.Back');
  644. const linkError
  645. = i18n.generateTranslationHTML('dialog.shareVideoLinkError');
  646. return new Promise((resolve, reject) => {
  647. dialog = APP.UI.messageHandler.openDialogWithStates({
  648. state0: {
  649. titleKey: 'dialog.shareVideoTitle',
  650. html: `
  651. <input name='sharedVideoUrl' type='text'
  652. class='input-control'
  653. data-i18n='[placeholder]defaultLink'
  654. autofocus>`,
  655. persistent: false,
  656. buttons: [
  657. { title: cancelButton,
  658. value: false },
  659. { title: shareButton,
  660. value: true }
  661. ],
  662. focus: ':input:first',
  663. defaultButton: 1,
  664. submit(e, v, m, f) { // eslint-disable-line max-params
  665. e.preventDefault();
  666. if (!v) {
  667. reject('cancelled');
  668. dialog.close();
  669. return;
  670. }
  671. const sharedVideoUrl = f.sharedVideoUrl;
  672. if (!sharedVideoUrl) {
  673. return;
  674. }
  675. const urlValue
  676. = encodeURI(UIUtil.escapeHtml(sharedVideoUrl));
  677. const yVideoId = getYoutubeLink(urlValue);
  678. if (!yVideoId) {
  679. dialog.goToState('state1');
  680. return false;
  681. }
  682. resolve(yVideoId);
  683. dialog.close();
  684. }
  685. },
  686. state1: {
  687. titleKey: 'dialog.shareVideoTitle',
  688. html: linkError,
  689. persistent: false,
  690. buttons: [
  691. { title: cancelButton,
  692. value: false },
  693. { title: backButton,
  694. value: true }
  695. ],
  696. focus: ':input:first',
  697. defaultButton: 1,
  698. submit(e, v) {
  699. e.preventDefault();
  700. if (v === 0) {
  701. reject();
  702. dialog.close();
  703. } else {
  704. dialog.goToState('state0');
  705. }
  706. }
  707. }
  708. }, {
  709. close() {
  710. dialog = null;
  711. }
  712. }, {
  713. url: defaultSharedVideoLink
  714. });
  715. });
  716. }