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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835
  1. /* global $, APP, YT, onPlayerReady, onPlayerStateChange, onPlayerError */
  2. import UIUtil from '../util/UIUtil';
  3. import UIEvents from '../../../service/UI/UIEvents';
  4. import VideoLayout from "../videolayout/VideoLayout";
  5. import LargeContainer from '../videolayout/LargeContainer';
  6. import SmallVideo from '../videolayout/SmallVideo';
  7. import FilmStrip from '../videolayout/FilmStrip';
  8. import ToolbarToggler from "../toolbars/ToolbarToggler";
  9. import AnalyticsAdapter from '../../statistics/AnalyticsAdapter';
  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. AnalyticsAdapter.sendEvent('sharedvideo.started');
  66. },
  67. err => {
  68. console.log('SHARED VIDEO CANCELED', err);
  69. AnalyticsAdapter.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. AnalyticsAdapter.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. AnalyticsAdapter.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. AnalyticsAdapter.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. AnalyticsAdapter.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.addParticipantContainer(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. get $video () {
  490. return this.$iframe;
  491. }
  492. show () {
  493. let self = this;
  494. return new Promise(resolve => {
  495. this.$iframe.fadeIn(300, () => {
  496. self.bodyBackground = document.body.style.background;
  497. document.body.style.background = 'black';
  498. this.$iframe.css({opacity: 1});
  499. ToolbarToggler.dockToolbar(true);
  500. resolve();
  501. });
  502. });
  503. }
  504. hide () {
  505. let self = this;
  506. ToolbarToggler.dockToolbar(false);
  507. return new Promise(resolve => {
  508. this.$iframe.fadeOut(300, () => {
  509. document.body.style.background = self.bodyBackground;
  510. this.$iframe.css({opacity: 0});
  511. resolve();
  512. });
  513. });
  514. }
  515. onHoverIn () {
  516. ToolbarToggler.showToolbar();
  517. }
  518. get id () {
  519. return this.url;
  520. }
  521. resize (containerWidth, containerHeight) {
  522. let height = containerHeight - FilmStrip.getFilmStripHeight();
  523. let width = containerWidth;
  524. this.$iframe.width(width).height(height);
  525. }
  526. /**
  527. * @return {boolean} do not switch on dominant speaker event if on stage.
  528. */
  529. stayOnStage () {
  530. return false;
  531. }
  532. }
  533. function SharedVideoThumb (url)
  534. {
  535. this.id = url;
  536. this.url = url;
  537. this.setVideoType(SHARED_VIDEO_CONTAINER_TYPE);
  538. this.videoSpanId = "sharedVideoContainer";
  539. this.container = this.createContainer(this.videoSpanId);
  540. this.container.onclick = this.videoClick.bind(this);
  541. SmallVideo.call(this, VideoLayout);
  542. this.isVideoMuted = true;
  543. }
  544. SharedVideoThumb.prototype = Object.create(SmallVideo.prototype);
  545. SharedVideoThumb.prototype.constructor = SharedVideoThumb;
  546. /**
  547. * hide display name
  548. */
  549. SharedVideoThumb.prototype.setDeviceAvailabilityIcons = function () {};
  550. SharedVideoThumb.prototype.avatarChanged = function () {};
  551. SharedVideoThumb.prototype.createContainer = function (spanId) {
  552. var container = document.createElement('span');
  553. container.id = spanId;
  554. container.className = 'videocontainer';
  555. // add the avatar
  556. var avatar = document.createElement('img');
  557. avatar.className = 'sharedVideoAvatar';
  558. avatar.src = "https://img.youtube.com/vi/" + this.url + "/0.jpg";
  559. container.appendChild(avatar);
  560. var remotes = document.getElementById('remoteVideos');
  561. return remotes.appendChild(container);
  562. };
  563. /**
  564. * The thumb click handler.
  565. */
  566. SharedVideoThumb.prototype.videoClick = function () {
  567. VideoLayout.handleVideoThumbClicked(this.url);
  568. };
  569. /**
  570. * Removes RemoteVideo from the page.
  571. */
  572. SharedVideoThumb.prototype.remove = function () {
  573. console.log("Remove shared video thumb", this.id);
  574. // Make sure that the large video is updated if are removing its
  575. // corresponding small video.
  576. this.VideoLayout.updateAfterThumbRemoved(this.id);
  577. // Remove whole container
  578. if (this.container.parentNode) {
  579. this.container.parentNode.removeChild(this.container);
  580. }
  581. };
  582. /**
  583. * Sets the display name for the thumb.
  584. */
  585. SharedVideoThumb.prototype.setDisplayName = function(displayName) {
  586. if (!this.container) {
  587. console.warn( "Unable to set displayName - " + this.videoSpanId +
  588. " does not exist");
  589. return;
  590. }
  591. var nameSpan = $('#' + this.videoSpanId + '>span.displayname');
  592. // If we already have a display name for this video.
  593. if (nameSpan.length > 0) {
  594. if (displayName && displayName.length > 0) {
  595. $('#' + this.videoSpanId + '_name').text(displayName);
  596. }
  597. } else {
  598. nameSpan = document.createElement('span');
  599. nameSpan.className = 'displayname';
  600. $('#' + this.videoSpanId)[0].appendChild(nameSpan);
  601. if (displayName && displayName.length > 0)
  602. $(nameSpan).text(displayName);
  603. nameSpan.id = this.videoSpanId + '_name';
  604. }
  605. };
  606. /**
  607. * Checks if given string is youtube url.
  608. * @param {string} url string to check.
  609. * @returns {boolean}
  610. */
  611. function getYoutubeLink(url) {
  612. let p = /^(?:https?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))((\w|-){11})(?:\S+)?$/;//jshint ignore:line
  613. return (url.match(p)) ? RegExp.$1 : false;
  614. }
  615. /**
  616. * Ask user if he want to close shared video.
  617. */
  618. function showStopVideoPropmpt() {
  619. return new Promise(function (resolve, reject) {
  620. dialog = APP.UI.messageHandler.openTwoButtonDialog(
  621. "dialog.removeSharedVideoTitle",
  622. null,
  623. "dialog.removeSharedVideoMsg",
  624. null,
  625. false,
  626. "dialog.Remove",
  627. function(e,v,m,f) {
  628. if (v) {
  629. resolve();
  630. } else {
  631. reject();
  632. }
  633. },
  634. null,
  635. function () {
  636. dialog = null;
  637. }
  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 title = i18n.generateTranslationHTML("dialog.shareVideoTitle");
  648. const cancelButton = i18n.generateTranslationHTML("dialog.Cancel");
  649. const shareButton = i18n.generateTranslationHTML("dialog.Share");
  650. const backButton = i18n.generateTranslationHTML("dialog.Back");
  651. const linkError
  652. = i18n.generateTranslationHTML("dialog.shareVideoLinkError");
  653. const i18nOptions = {url: defaultSharedVideoLink};
  654. const defaultUrl = i18n.translateString("defaultLink", i18nOptions);
  655. return new Promise(function (resolve, reject) {
  656. dialog = APP.UI.messageHandler.openDialogWithStates({
  657. state0: {
  658. html: `
  659. <h2>${title}</h2>
  660. <input name="sharedVideoUrl" type="text"
  661. data-i18n="[placeholder]defaultLink"
  662. data-i18n-options="${JSON.stringify(i18nOptions)}"
  663. placeholder="${defaultUrl}"
  664. autofocus>`,
  665. persistent: false,
  666. buttons: [
  667. {title: cancelButton, value: false},
  668. {title: shareButton, value: true}
  669. ],
  670. focus: ':input:first',
  671. defaultButton: 1,
  672. submit: function (e, v, m, f) {
  673. e.preventDefault();
  674. if (!v) {
  675. reject('cancelled');
  676. dialog.close();
  677. return;
  678. }
  679. let sharedVideoUrl = f.sharedVideoUrl;
  680. if (!sharedVideoUrl) {
  681. return;
  682. }
  683. let urlValue = encodeURI(UIUtil.escapeHtml(sharedVideoUrl));
  684. let yVideoId = getYoutubeLink(urlValue);
  685. if (!yVideoId) {
  686. dialog.goToState('state1');
  687. return false;
  688. }
  689. resolve(yVideoId);
  690. dialog.close();
  691. }
  692. },
  693. state1: {
  694. html: `<h2>${title}</h2> ${linkError}`,
  695. persistent: false,
  696. buttons: [
  697. {title: cancelButton, value: false},
  698. {title: backButton, value: true}
  699. ],
  700. focus: ':input:first',
  701. defaultButton: 1,
  702. submit: function (e, v, m, f) {
  703. e.preventDefault();
  704. if (v === 0) {
  705. reject();
  706. dialog.close();
  707. } else {
  708. dialog.goToState('state0');
  709. }
  710. }
  711. }
  712. }, {
  713. close: function () {
  714. dialog = null;
  715. }
  716. });
  717. });
  718. }