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

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