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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  1. /* global $, APP, YT, onPlayerReady, onPlayerStateChange, onPlayerError */
  2. import messageHandler from '../util/MessageHandler';
  3. import UIUtil from '../util/UIUtil';
  4. import UIEvents from '../../../service/UI/UIEvents';
  5. import VideoLayout from "../videolayout/VideoLayout";
  6. import LargeContainer from '../videolayout/LargeContainer';
  7. import SmallVideo from '../videolayout/SmallVideo';
  8. import FilmStrip from '../videolayout/FilmStrip';
  9. import ToolbarToggler from "../toolbars/ToolbarToggler";
  10. export const SHARED_VIDEO_CONTAINER_TYPE = "sharedvideo";
  11. /**
  12. * Example shared video link.
  13. * @type {string}
  14. */
  15. const defaultSharedVideoLink = "https://www.youtube.com/watch?v=xNXN7CZk8X0";
  16. /**
  17. * Manager of shared video.
  18. */
  19. export default class SharedVideoManager {
  20. constructor (emitter) {
  21. this.emitter = emitter;
  22. this.isSharedVideoShown = false;
  23. this.isPlayerAPILoaded = false;
  24. this.updateInterval = 5000; // milliseconds
  25. }
  26. /**
  27. * Starts shared video by asking user for url, or if its already working
  28. * asks whether the user wants to stop sharing the video.
  29. */
  30. toggleSharedVideo () {
  31. if(!this.isSharedVideoShown) {
  32. requestVideoLink().then(
  33. url => this.emitter.emit(
  34. UIEvents.UPDATE_SHARED_VIDEO, url, 'start'),
  35. err => console.error('SHARED VIDEO CANCELED', err)
  36. );
  37. return;
  38. }
  39. showStopVideoPropmpt().then(() =>
  40. this.emitter.emit(UIEvents.UPDATE_SHARED_VIDEO, null, 'stop'));
  41. }
  42. /**
  43. * Shows the player component and starts the checking function
  44. * that will be sending updates, if we are the one shared the video
  45. * @param url the video url
  46. * @param attributes
  47. */
  48. showSharedVideo (url, attributes) {
  49. if (this.isSharedVideoShown)
  50. return;
  51. // the video url
  52. this.url = url;
  53. // the owner of the video
  54. this.from = attributes.from;
  55. // This code loads the IFrame Player API code asynchronously.
  56. var tag = document.createElement('script');
  57. tag.src = "https://www.youtube.com/iframe_api";
  58. var firstScriptTag = document.getElementsByTagName('script')[0];
  59. firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
  60. var self = this;
  61. if(self.isPlayerAPILoaded)
  62. window.onYouTubeIframeAPIReady();
  63. else
  64. window.onYouTubeIframeAPIReady = function() {
  65. self.isPlayerAPILoaded = true;
  66. let showControls = APP.conference.isLocalId(self.from) ? 1 : 0;
  67. self.player = new YT.Player('sharedVideoIFrame', {
  68. height: '100%',
  69. width: '100%',
  70. videoId: self.url,
  71. playerVars: {
  72. 'origin': location.origin,
  73. 'fs': '0',
  74. 'autoplay': 1,
  75. 'controls': showControls,
  76. 'rel' : 0
  77. },
  78. events: {
  79. 'onReady': onPlayerReady,
  80. 'onStateChange': onPlayerStateChange,
  81. 'onError': onPlayerError
  82. }
  83. });
  84. };
  85. // whether we should pause the player as initial status
  86. // sometimes if we try to pause the player before it starts playing
  87. // we can end up with player in buffering mode
  88. this.initialPause = false;
  89. window.onPlayerStateChange = function(event) {
  90. if (event.data == YT.PlayerState.PLAYING) {
  91. self.playerPaused = false;
  92. // check for initial pause
  93. if(self.initialPause) {
  94. self.initialPause = false;
  95. self.player.pauseVideo();
  96. }
  97. self.updateCheck();
  98. } else if (event.data == YT.PlayerState.PAUSED) {
  99. self.playerPaused = true;
  100. self.updateCheck(true);
  101. }
  102. };
  103. window.onPlayerReady = function(event) {
  104. let player = event.target;
  105. player.playVideo();
  106. let thumb = new SharedVideoThumb(self.url);
  107. thumb.setDisplayName(player.getVideoData().title);
  108. VideoLayout.addParticipantContainer(self.url, thumb);
  109. let iframe = player.getIframe();
  110. self.sharedVideo = new SharedVideoContainer(
  111. {url, iframe, player});
  112. VideoLayout.addLargeVideoContainer(
  113. SHARED_VIDEO_CONTAINER_TYPE, self.sharedVideo);
  114. VideoLayout.handleVideoThumbClicked(self.url);
  115. self.isSharedVideoShown = true;
  116. // If we are sending the command and we are starting the player
  117. // we need to continuously send the player current time position
  118. if(APP.conference.isLocalId(self.from)) {
  119. self.intervalId = setInterval(
  120. self.updateCheck.bind(self),
  121. self.updateInterval);
  122. }
  123. // set initial state of the player if there is enough information
  124. if(attributes.state === 'pause')
  125. self.initialPause = true;
  126. else if(attributes.time > 0) {
  127. console.log("Player seekTo:", attributes.time);
  128. player.seekTo(attributes.time);
  129. }
  130. };
  131. window.onPlayerError = function(event) {
  132. console.error("Error in the player:" + event.data);
  133. };
  134. }
  135. /**
  136. * Checks current state of the player and fire an event with the values.
  137. */
  138. updateCheck(sendPauseEvent)
  139. {
  140. // ignore update checks if we are not the owner of the video
  141. if(!APP.conference.isLocalId(this.from))
  142. return;
  143. let state = this.player.getPlayerState();
  144. // if its paused and haven't been pause - send paused
  145. if (state === YT.PlayerState.PAUSED && sendPauseEvent) {
  146. this.emitter.emit(UIEvents.UPDATE_SHARED_VIDEO,
  147. this.url, 'pause');
  148. }
  149. // if its playing and it was paused - send update with time
  150. // if its playing and was playing just send update with time
  151. else if (state === YT.PlayerState.PLAYING) {
  152. this.emitter.emit(UIEvents.UPDATE_SHARED_VIDEO,
  153. this.url, 'playing',
  154. this.player.getCurrentTime(),
  155. this.player.isMuted() ? 0 : this.player.getVolume());
  156. }
  157. }
  158. /**
  159. * Updates video, if its not playing and needs starting or
  160. * if its playing and needs to be paysed
  161. * @param url the video url
  162. * @param attributes
  163. */
  164. updateSharedVideo (url, attributes) {
  165. // if we are sending the event ignore
  166. if(APP.conference.isLocalId(this.from)) {
  167. return;
  168. }
  169. if (attributes.state == 'playing') {
  170. if(!this.isSharedVideoShown) {
  171. this.showSharedVideo(url, attributes);
  172. return;
  173. }
  174. // ocasionally we get this.player.getCurrentTime is not a function
  175. // it seems its that player hasn't really loaded
  176. if(!this.player || !this.player.getCurrentTime
  177. || !this.player.pauseVideo
  178. || !this.player.playVideo
  179. || !this.player.getVolume
  180. || !this.player.seekTo
  181. || !this.player.getVolume)
  182. return;
  183. // check received time and current time
  184. let currentPosition = this.player.getCurrentTime();
  185. let diff = Math.abs(attributes.time - currentPosition);
  186. // if we drift more than two times of the interval for checking
  187. // sync, the interval is in milliseconds
  188. if(diff > this.updateInterval*2/1000) {
  189. console.log("Player seekTo:", attributes.time,
  190. " current time is:", currentPosition, " diff:", diff);
  191. this.player.seekTo(attributes.time);
  192. }
  193. // lets check the volume
  194. if (attributes.volume !== undefined &&
  195. this.player.getVolume() != attributes.volume) {
  196. this.player.setVolume(attributes.volume);
  197. console.log("Player change of volume:" + attributes.volume);
  198. }
  199. if(this.playerPaused)
  200. this.player.playVideo();
  201. } else if (attributes.state == 'pause') {
  202. // if its not paused, pause it
  203. if(this.isSharedVideoShown) {
  204. this.player.pauseVideo();
  205. }
  206. else {
  207. // if not shown show it, passing attributes so it can
  208. // be shown paused
  209. this.showSharedVideo(url, attributes);
  210. }
  211. }
  212. }
  213. /**
  214. * Stop shared video if it is currently showed. If the user started the
  215. * shared video is the one in the attributes.from (called when user
  216. * left and we want to remove video if the user sharing it left).
  217. * @param attributes
  218. */
  219. stopSharedVideo (attributes) {
  220. if (!this.isSharedVideoShown)
  221. return;
  222. if(this.from !== attributes.from)
  223. return;
  224. if(this.intervalId) {
  225. clearInterval(this.intervalId);
  226. this.intervalId = null;
  227. }
  228. VideoLayout.removeParticipantContainer(this.url);
  229. VideoLayout.showLargeVideoContainer(SHARED_VIDEO_CONTAINER_TYPE, false)
  230. .then(() => {
  231. VideoLayout.removeLargeVideoContainer(
  232. SHARED_VIDEO_CONTAINER_TYPE);
  233. this.player.destroy();
  234. this.player = null;
  235. });
  236. this.url = null;
  237. this.isSharedVideoShown = false;
  238. }
  239. }
  240. /**
  241. * Container for shared video iframe.
  242. */
  243. class SharedVideoContainer extends LargeContainer {
  244. constructor ({url, iframe, player}) {
  245. super();
  246. this.$iframe = $(iframe);
  247. this.url = url;
  248. this.player = player;
  249. }
  250. get $video () {
  251. return this.$iframe;
  252. }
  253. show () {
  254. let self = this;
  255. return new Promise(resolve => {
  256. this.$iframe.fadeIn(300, () => {
  257. self.bodyBackground = document.body.style.background;
  258. document.body.style.background = 'black';
  259. this.$iframe.css({opacity: 1});
  260. resolve();
  261. });
  262. });
  263. }
  264. hide () {
  265. let self = this;
  266. return new Promise(resolve => {
  267. this.$iframe.fadeOut(300, () => {
  268. document.body.style.background = self.bodyBackground;
  269. this.$iframe.css({opacity: 0});
  270. resolve();
  271. });
  272. });
  273. }
  274. onHoverIn () {
  275. ToolbarToggler.showToolbar();
  276. }
  277. get id () {
  278. return this.url;
  279. }
  280. resize (containerWidth, containerHeight) {
  281. let height = containerHeight - FilmStrip.getFilmStripHeight();
  282. let width = containerWidth;
  283. this.$iframe.width(width).height(height);
  284. }
  285. /**
  286. * @return {boolean} do not switch on dominant speaker event if on stage.
  287. */
  288. stayOnStage () {
  289. return false;
  290. }
  291. }
  292. function SharedVideoThumb (url)
  293. {
  294. this.id = url;
  295. this.url = url;
  296. this.setVideoType(SHARED_VIDEO_CONTAINER_TYPE);
  297. this.videoSpanId = "sharedVideoContainer";
  298. this.container = this.createContainer(this.videoSpanId);
  299. this.container.onclick = this.videoClick.bind(this);
  300. SmallVideo.call(this, VideoLayout);
  301. this.isVideoMuted = true;
  302. }
  303. SharedVideoThumb.prototype = Object.create(SmallVideo.prototype);
  304. SharedVideoThumb.prototype.constructor = SharedVideoThumb;
  305. /**
  306. * hide display name
  307. */
  308. SharedVideoThumb.prototype.setDeviceAvailabilityIcons = function () {};
  309. SharedVideoThumb.prototype.avatarChanged = function () {};
  310. SharedVideoThumb.prototype.createContainer = function (spanId) {
  311. var container = document.createElement('span');
  312. container.id = spanId;
  313. container.className = 'videocontainer';
  314. // add the avatar
  315. var avatar = document.createElement('img');
  316. avatar.id = 'avatar_' + this.id;
  317. avatar.className = 'sharedVideoAvatar';
  318. avatar.src = "https://img.youtube.com/vi/" + this.url + "/0.jpg";
  319. container.appendChild(avatar);
  320. var remotes = document.getElementById('remoteVideos');
  321. return remotes.appendChild(container);
  322. };
  323. /**
  324. * The thumb click handler.
  325. */
  326. SharedVideoThumb.prototype.videoClick = function () {
  327. VideoLayout.handleVideoThumbClicked(this.url);
  328. };
  329. /**
  330. * Removes RemoteVideo from the page.
  331. */
  332. SharedVideoThumb.prototype.remove = function () {
  333. console.log("Remove shared video thumb", this.id);
  334. // Make sure that the large video is updated if are removing its
  335. // corresponding small video.
  336. this.VideoLayout.updateAfterThumbRemoved(this.id);
  337. // Remove whole container
  338. if (this.container.parentNode) {
  339. this.container.parentNode.removeChild(this.container);
  340. }
  341. };
  342. /**
  343. * Sets the display name for the thumb.
  344. */
  345. SharedVideoThumb.prototype.setDisplayName = function(displayName) {
  346. if (!this.container) {
  347. console.warn( "Unable to set displayName - " + this.videoSpanId +
  348. " does not exist");
  349. return;
  350. }
  351. var nameSpan = $('#' + this.videoSpanId + '>span.displayname');
  352. // If we already have a display name for this video.
  353. if (nameSpan.length > 0) {
  354. if (displayName && displayName.length > 0) {
  355. $('#' + this.videoSpanId + '_name').text(displayName);
  356. }
  357. } else {
  358. nameSpan = document.createElement('span');
  359. nameSpan.className = 'displayname';
  360. $('#' + this.videoSpanId)[0].appendChild(nameSpan);
  361. if (displayName && displayName.length > 0)
  362. $(nameSpan).text(displayName);
  363. nameSpan.id = this.videoSpanId + '_name';
  364. }
  365. };
  366. /**
  367. * Checks if given string is youtube url.
  368. * @param {string} url string to check.
  369. * @returns {boolean}
  370. */
  371. function getYoutubeLink(url) {
  372. let p = /^(?:https?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))((\w|-){11})(?:\S+)?$/;//jshint ignore:line
  373. return (url.match(p)) ? RegExp.$1 : false;
  374. }
  375. /**
  376. * Ask user if he want to close shared video.
  377. */
  378. function showStopVideoPropmpt() {
  379. return new Promise(function (resolve, reject) {
  380. messageHandler.openTwoButtonDialog(
  381. "dialog.removeSharedVideoTitle",
  382. null,
  383. "dialog.removeSharedVideoMsg",
  384. null,
  385. false,
  386. "dialog.Remove",
  387. function(e,v,m,f) {
  388. if (v) {
  389. resolve();
  390. } else {
  391. reject();
  392. }
  393. }
  394. );
  395. });
  396. }
  397. /**
  398. * Ask user for shared video url to share with others.
  399. * Dialog validates client input to allow only youtube urls.
  400. */
  401. function requestVideoLink() {
  402. let i18n = APP.translation;
  403. const title = i18n.generateTranslationHTML("dialog.shareVideoTitle");
  404. const cancelButton = i18n.generateTranslationHTML("dialog.Cancel");
  405. const shareButton = i18n.generateTranslationHTML("dialog.Share");
  406. const backButton = i18n.generateTranslationHTML("dialog.Back");
  407. const linkError
  408. = i18n.generateTranslationHTML("dialog.shareVideoLinkError");
  409. const i18nOptions = {url: defaultSharedVideoLink};
  410. const defaultUrl = i18n.translateString("defaultLink", i18nOptions);
  411. return new Promise(function (resolve, reject) {
  412. let dialog = messageHandler.openDialogWithStates({
  413. state0: {
  414. html: `
  415. <h2>${title}</h2>
  416. <input name="sharedVideoUrl" type="text"
  417. data-i18n="[placeholder]defaultLink"
  418. data-i18n-options="${JSON.stringify(i18nOptions)}"
  419. placeholder="${defaultUrl}"
  420. autofocus>`,
  421. persistent: false,
  422. buttons: [
  423. {title: cancelButton, value: false},
  424. {title: shareButton, value: true}
  425. ],
  426. focus: ':input:first',
  427. defaultButton: 1,
  428. submit: function (e, v, m, f) {
  429. e.preventDefault();
  430. if (!v) {
  431. reject('cancelled');
  432. dialog.close();
  433. return;
  434. }
  435. let sharedVideoUrl = f.sharedVideoUrl;
  436. if (!sharedVideoUrl) {
  437. return;
  438. }
  439. let urlValue = encodeURI(UIUtil.escapeHtml(sharedVideoUrl));
  440. let yVideoId = getYoutubeLink(urlValue);
  441. if (!yVideoId) {
  442. dialog.goToState('state1');
  443. return false;
  444. }
  445. resolve(yVideoId);
  446. dialog.close();
  447. }
  448. },
  449. state1: {
  450. html: `<h2>${title}</h2> ${linkError}`,
  451. persistent: false,
  452. buttons: [
  453. {title: cancelButton, value: false},
  454. {title: backButton, value: true}
  455. ],
  456. focus: ':input:first',
  457. defaultButton: 1,
  458. submit: function (e, v, m, f) {
  459. e.preventDefault();
  460. if (v === 0) {
  461. reject();
  462. dialog.close();
  463. } else {
  464. dialog.goToState('state0');
  465. }
  466. }
  467. }
  468. });
  469. });
  470. }