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