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

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