Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

SharedVideo.js 26KB

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