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