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

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