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

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