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

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