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

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