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

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