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

SharedVideo.js 16KB

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