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

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