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

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