您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

SharedVideo.js 17KB

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