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 27KB

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