Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

SharedVideo.js 26KB

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