Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

SharedVideo.js 26KB

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