Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

SharedVideo.js 18KB

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