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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546
  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. return new Promise(resolve => {
  255. this.$iframe.fadeIn(300, () => {
  256. this.$iframe.css({opacity: 1});
  257. resolve();
  258. });
  259. });
  260. }
  261. hide () {
  262. return new Promise(resolve => {
  263. this.$iframe.fadeOut(300, () => {
  264. this.$iframe.css({opacity: 0});
  265. resolve();
  266. });
  267. });
  268. }
  269. onHoverIn () {
  270. ToolbarToggler.showToolbar();
  271. }
  272. get id () {
  273. return this.url;
  274. }
  275. resize (containerWidth, containerHeight) {
  276. let height = containerHeight - FilmStrip.getFilmStripHeight();
  277. let width = containerWidth;
  278. this.$iframe.width(width).height(height);
  279. }
  280. /**
  281. * @return {boolean} do not switch on dominant speaker event if on stage.
  282. */
  283. stayOnStage () {
  284. return false;
  285. }
  286. }
  287. function SharedVideoThumb (url)
  288. {
  289. this.id = url;
  290. this.url = url;
  291. this.setVideoType(SHARED_VIDEO_CONTAINER_TYPE);
  292. this.videoSpanId = "sharedVideoContainer";
  293. this.container = this.createContainer(this.videoSpanId);
  294. this.container.onclick = this.videoClick.bind(this);
  295. SmallVideo.call(this, VideoLayout);
  296. this.isVideoMuted = true;
  297. }
  298. SharedVideoThumb.prototype = Object.create(SmallVideo.prototype);
  299. SharedVideoThumb.prototype.constructor = SharedVideoThumb;
  300. /**
  301. * hide display name
  302. */
  303. SharedVideoThumb.prototype.setDeviceAvailabilityIcons = function () {};
  304. SharedVideoThumb.prototype.avatarChanged = function () {};
  305. SharedVideoThumb.prototype.createContainer = function (spanId) {
  306. var container = document.createElement('span');
  307. container.id = spanId;
  308. container.className = 'videocontainer';
  309. // add the avatar
  310. var avatar = document.createElement('img');
  311. avatar.id = 'avatar_' + this.id;
  312. avatar.className = 'sharedVideoAvatar';
  313. avatar.src = "https://img.youtube.com/vi/" + this.url + "/0.jpg";
  314. container.appendChild(avatar);
  315. var remotes = document.getElementById('remoteVideos');
  316. return remotes.appendChild(container);
  317. };
  318. /**
  319. * The thumb click handler.
  320. */
  321. SharedVideoThumb.prototype.videoClick = function () {
  322. VideoLayout.handleVideoThumbClicked(this.url);
  323. };
  324. /**
  325. * Removes RemoteVideo from the page.
  326. */
  327. SharedVideoThumb.prototype.remove = function () {
  328. console.log("Remove shared video thumb", this.id);
  329. // Make sure that the large video is updated if are removing its
  330. // corresponding small video.
  331. this.VideoLayout.updateAfterThumbRemoved(this.id);
  332. // Remove whole container
  333. if (this.container.parentNode) {
  334. this.container.parentNode.removeChild(this.container);
  335. }
  336. };
  337. /**
  338. * Sets the display name for the thumb.
  339. */
  340. SharedVideoThumb.prototype.setDisplayName = function(displayName) {
  341. if (!this.container) {
  342. console.warn( "Unable to set displayName - " + this.videoSpanId +
  343. " does not exist");
  344. return;
  345. }
  346. var nameSpan = $('#' + this.videoSpanId + '>span.displayname');
  347. // If we already have a display name for this video.
  348. if (nameSpan.length > 0) {
  349. if (displayName && displayName.length > 0) {
  350. $('#' + this.videoSpanId + '_name').text(displayName);
  351. }
  352. } else {
  353. nameSpan = document.createElement('span');
  354. nameSpan.className = 'displayname';
  355. $('#' + this.videoSpanId)[0].appendChild(nameSpan);
  356. if (displayName && displayName.length > 0)
  357. $(nameSpan).text(displayName);
  358. nameSpan.id = this.videoSpanId + '_name';
  359. }
  360. };
  361. /**
  362. * Checks if given string is youtube url.
  363. * @param {string} url string to check.
  364. * @returns {boolean}
  365. */
  366. function getYoutubeLink(url) {
  367. let p = /^(?:https?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))((\w|-){11})(?:\S+)?$/;//jshint ignore:line
  368. return (url.match(p)) ? RegExp.$1 : false;
  369. }
  370. /**
  371. * Ask user if he want to close shared video.
  372. */
  373. function showStopVideoPropmpt() {
  374. return new Promise(function (resolve, reject) {
  375. messageHandler.openTwoButtonDialog(
  376. "dialog.removeSharedVideoTitle",
  377. null,
  378. "dialog.removeSharedVideoMsg",
  379. null,
  380. false,
  381. "dialog.Remove",
  382. function(e,v,m,f) {
  383. if (v) {
  384. resolve();
  385. } else {
  386. reject();
  387. }
  388. }
  389. );
  390. });
  391. }
  392. /**
  393. * Ask user for shared video url to share with others.
  394. * Dialog validates client input to allow only youtube urls.
  395. */
  396. function requestVideoLink() {
  397. let i18n = APP.translation;
  398. const title = i18n.generateTranslationHTML("dialog.shareVideoTitle");
  399. const cancelButton = i18n.generateTranslationHTML("dialog.Cancel");
  400. const shareButton = i18n.generateTranslationHTML("dialog.Share");
  401. const backButton = i18n.generateTranslationHTML("dialog.Back");
  402. const linkError
  403. = i18n.generateTranslationHTML("dialog.shareVideoLinkError");
  404. const i18nOptions = {url: defaultSharedVideoLink};
  405. const defaultUrl = i18n.translateString("defaultLink", i18nOptions);
  406. return new Promise(function (resolve, reject) {
  407. let dialog = messageHandler.openDialogWithStates({
  408. state0: {
  409. html: `
  410. <h2>${title}</h2>
  411. <input name="sharedVideoUrl" type="text"
  412. data-i18n="[placeholder]defaultLink"
  413. data-i18n-options="${JSON.stringify(i18nOptions)}"
  414. placeholder="${defaultUrl}"
  415. autofocus>`,
  416. persistent: false,
  417. buttons: [
  418. {title: cancelButton, value: false},
  419. {title: shareButton, value: true}
  420. ],
  421. focus: ':input:first',
  422. defaultButton: 1,
  423. submit: function (e, v, m, f) {
  424. e.preventDefault();
  425. if (!v) {
  426. reject('cancelled');
  427. dialog.close();
  428. return;
  429. }
  430. let sharedVideoUrl = f.sharedVideoUrl;
  431. if (!sharedVideoUrl) {
  432. return;
  433. }
  434. let urlValue = encodeURI(UIUtil.escapeHtml(sharedVideoUrl));
  435. let yVideoId = getYoutubeLink(urlValue);
  436. if (!yVideoId) {
  437. dialog.goToState('state1');
  438. return false;
  439. }
  440. resolve(yVideoId);
  441. dialog.close();
  442. }
  443. },
  444. state1: {
  445. html: `<h2>${title}</h2> ${linkError}`,
  446. persistent: false,
  447. buttons: [
  448. {title: cancelButton, value: false},
  449. {title: backButton, value: true}
  450. ],
  451. focus: ':input:first',
  452. defaultButton: 1,
  453. submit: function (e, v, m, f) {
  454. e.preventDefault();
  455. if (v === 0) {
  456. reject();
  457. dialog.close();
  458. } else {
  459. dialog.goToState('state0');
  460. }
  461. }
  462. }
  463. });
  464. });
  465. }