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

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