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

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