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

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