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

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