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

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