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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803
  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. this.mutedWithUserInteraction = false;
  26. }
  27. /**
  28. * Indicates if the player volume is currently on. This will return true if
  29. * we have an available player, which is currently in a PLAYING state,
  30. * which isn't muted and has it's volume greater than 0.
  31. *
  32. * @returns {boolean} indicating if the volume of the shared video is
  33. * currently on.
  34. */
  35. isSharedVideoVolumeOn() {
  36. return (this.player
  37. && this.player.getPlayerState() === YT.PlayerState.PLAYING
  38. && !this.player.isMuted()
  39. && this.player.getVolume() > 0);
  40. }
  41. /**
  42. * Indicates if the local user is the owner of the shared video.
  43. * @returns {*|boolean}
  44. */
  45. isSharedVideoOwner() {
  46. return this.from && APP.conference.isLocalId(this.from);
  47. }
  48. /**
  49. * Starts shared video by asking user for url, or if its already working
  50. * asks whether the user wants to stop sharing the video.
  51. */
  52. toggleSharedVideo () {
  53. if(!this.isSharedVideoShown) {
  54. requestVideoLink().then(
  55. url => this.emitter.emit(
  56. UIEvents.UPDATE_SHARED_VIDEO, url, 'start'),
  57. err => console.error('SHARED VIDEO CANCELED', err)
  58. );
  59. return;
  60. }
  61. if(APP.conference.isLocalId(this.from)) {
  62. showStopVideoPropmpt().then(() =>
  63. this.emitter.emit(
  64. UIEvents.UPDATE_SHARED_VIDEO, this.url, 'stop'));
  65. } else {
  66. messageHandler.openMessageDialog(
  67. "dialog.shareVideoTitle",
  68. "dialog.alreadySharedVideoMsg"
  69. );
  70. }
  71. }
  72. /**
  73. * Shows the player component and starts the process that will be sending
  74. * updates, if we are the one shared the video.
  75. *
  76. * @param id the id of the sender of the command
  77. * @param url the video url
  78. * @param attributes
  79. */
  80. onSharedVideoStart (id, url, attributes) {
  81. if (this.isSharedVideoShown)
  82. return;
  83. this.isSharedVideoShown = true;
  84. // the video url
  85. this.url = url;
  86. // the owner of the video
  87. this.from = id;
  88. this.mutedWithUserInteraction = APP.conference.isLocalAudioMuted();
  89. //listen for local audio mute events
  90. this.localAudioMutedListener = this.onLocalAudioMuted.bind(this);
  91. this.emitter.on(UIEvents.AUDIO_MUTED, this.localAudioMutedListener);
  92. // This code loads the IFrame Player API code asynchronously.
  93. var tag = document.createElement('script');
  94. tag.src = "https://www.youtube.com/iframe_api";
  95. var firstScriptTag = document.getElementsByTagName('script')[0];
  96. firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
  97. // sometimes we receive errors like player not defined
  98. // or player.pauseVideo is not a function
  99. // we need to operate with player after start playing
  100. // self.player will be defined once it start playing
  101. // and will process any initial attributes if any
  102. this.initialAttributes = attributes;
  103. var self = this;
  104. if(self.isPlayerAPILoaded)
  105. window.onYouTubeIframeAPIReady();
  106. else
  107. window.onYouTubeIframeAPIReady = function() {
  108. self.isPlayerAPILoaded = true;
  109. let showControls = APP.conference.isLocalId(self.from) ? 1 : 0;
  110. let p = new YT.Player('sharedVideoIFrame', {
  111. height: '100%',
  112. width: '100%',
  113. videoId: self.url,
  114. playerVars: {
  115. 'origin': location.origin,
  116. 'fs': '0',
  117. 'autoplay': 0,
  118. 'controls': showControls,
  119. 'rel' : 0
  120. },
  121. events: {
  122. 'onReady': onPlayerReady,
  123. 'onStateChange': onPlayerStateChange,
  124. 'onError': onPlayerError
  125. }
  126. });
  127. // add listener for volume changes
  128. p.addEventListener(
  129. "onVolumeChange", "onVolumeChange");
  130. if (APP.conference.isLocalId(self.from)){
  131. // adds progress listener that will be firing events
  132. // while we are paused and we change the progress of the
  133. // video (seeking forward or backward on the video)
  134. p.addEventListener(
  135. "onVideoProgress", "onVideoProgress");
  136. }
  137. };
  138. /**
  139. * Indicates that a change in state has occurred for the shared video.
  140. * @param event the event notifying us of the change
  141. */
  142. window.onPlayerStateChange = function(event) {
  143. if (event.data == YT.PlayerState.PLAYING) {
  144. self.player = event.target;
  145. if(self.initialAttributes)
  146. {
  147. // If a network update has occurred already now is the
  148. // time to process it.
  149. self.processVideoUpdate(
  150. self.player,
  151. self.initialAttributes);
  152. self.initialAttributes = null;
  153. }
  154. self.smartAudioMute();
  155. } else if (event.data == YT.PlayerState.PAUSED) {
  156. self.smartAudioUnmute();
  157. }
  158. self.fireSharedVideoEvent(event.data == YT.PlayerState.PAUSED);
  159. };
  160. /**
  161. * Track player progress while paused.
  162. * @param event
  163. */
  164. window.onVideoProgress = function (event) {
  165. let state = event.target.getPlayerState();
  166. if (state == YT.PlayerState.PAUSED) {
  167. self.fireSharedVideoEvent(true);
  168. }
  169. };
  170. /**
  171. * Gets notified for volume state changed.
  172. * @param event
  173. */
  174. window.onVolumeChange = function (event) {
  175. self.fireSharedVideoEvent();
  176. // let's check, if player is not muted lets mute locally
  177. if(event.data.volume > 0 && !event.data.muted) {
  178. self.smartAudioMute();
  179. }
  180. else if (event.data.volume <=0 || event.data.muted) {
  181. self.smartAudioUnmute();
  182. }
  183. };
  184. window.onPlayerReady = function(event) {
  185. let player = event.target;
  186. // do not relay on autoplay as it is not sending all of the events
  187. // in onPlayerStateChange
  188. player.playVideo();
  189. let thumb = new SharedVideoThumb(self.url);
  190. thumb.setDisplayName(player.getVideoData().title);
  191. VideoLayout.addParticipantContainer(self.url, thumb);
  192. let iframe = player.getIframe();
  193. self.sharedVideo = new SharedVideoContainer(
  194. {url, iframe, player});
  195. //prevents pausing participants not sharing the video
  196. // to pause the video
  197. if (!APP.conference.isLocalId(self.from)) {
  198. $("#sharedVideo").css("pointer-events","none");
  199. }
  200. VideoLayout.addLargeVideoContainer(
  201. SHARED_VIDEO_CONTAINER_TYPE, self.sharedVideo);
  202. VideoLayout.handleVideoThumbClicked(self.url);
  203. // If we are sending the command and we are starting the player
  204. // we need to continuously send the player current time position
  205. if(APP.conference.isLocalId(self.from)) {
  206. self.intervalId = setInterval(
  207. self.fireSharedVideoEvent.bind(self),
  208. updateInterval);
  209. }
  210. };
  211. window.onPlayerError = function(event) {
  212. console.error("Error in the player:", event.data);
  213. // store the error player, so we can remove it
  214. self.errorInPlayer = event.target;
  215. };
  216. }
  217. /**
  218. * Process attributes, whether player needs to be paused or seek.
  219. * @param player the player to operate over
  220. * @param attributes the attributes with the player state we want
  221. */
  222. processVideoUpdate (player, attributes)
  223. {
  224. if(!attributes)
  225. return;
  226. if (attributes.state == 'playing') {
  227. let isPlayerPaused
  228. = (this.player.getPlayerState() === YT.PlayerState.PAUSED);
  229. // If our player is currently paused force the seek.
  230. this.processTime(player, attributes, isPlayerPaused);
  231. // Process mute.
  232. let isAttrMuted = (attributes.muted === "true");
  233. if (player.isMuted() !== isAttrMuted) {
  234. this.smartPlayerMute(isAttrMuted, true);
  235. }
  236. // Process volume
  237. if (!isAttrMuted
  238. && attributes.volume !== undefined
  239. && player.getVolume() != attributes.volume) {
  240. player.setVolume(attributes.volume);
  241. console.info("Player change of volume:" + attributes.volume);
  242. this.showSharedVideoMutedPopup(false);
  243. }
  244. if (isPlayerPaused)
  245. player.playVideo();
  246. } else if (attributes.state == 'pause') {
  247. // if its not paused, pause it
  248. player.pauseVideo();
  249. this.processTime(player, attributes, true);
  250. }
  251. }
  252. /**
  253. * Check for time in attributes and if needed seek in current player
  254. * @param player the player to operate over
  255. * @param attributes the attributes with the player state we want
  256. * @param forceSeek whether seek should be forced
  257. */
  258. processTime (player, attributes, forceSeek)
  259. {
  260. if(forceSeek) {
  261. console.info("Player seekTo:", attributes.time);
  262. player.seekTo(attributes.time);
  263. return;
  264. }
  265. // check received time and current time
  266. let currentPosition = player.getCurrentTime();
  267. let diff = Math.abs(attributes.time - currentPosition);
  268. // if we drift more than the interval for checking
  269. // sync, the interval is in milliseconds
  270. if(diff > updateInterval/1000) {
  271. console.info("Player seekTo:", attributes.time,
  272. " current time is:", currentPosition, " diff:", diff);
  273. player.seekTo(attributes.time);
  274. }
  275. }
  276. /**
  277. * Checks current state of the player and fire an event with the values.
  278. */
  279. fireSharedVideoEvent(sendPauseEvent)
  280. {
  281. // ignore update checks if we are not the owner of the video
  282. // or there is still no player defined or we are stopped
  283. // (in a process of stopping)
  284. if(!APP.conference.isLocalId(this.from) || !this.player
  285. || !this.isSharedVideoShown)
  286. return;
  287. let state = this.player.getPlayerState();
  288. // if its paused and haven't been pause - send paused
  289. if (state === YT.PlayerState.PAUSED && sendPauseEvent) {
  290. this.emitter.emit(UIEvents.UPDATE_SHARED_VIDEO,
  291. this.url, 'pause', this.player.getCurrentTime());
  292. }
  293. // if its playing and it was paused - send update with time
  294. // if its playing and was playing just send update with time
  295. else if (state === YT.PlayerState.PLAYING) {
  296. this.emitter.emit(UIEvents.UPDATE_SHARED_VIDEO,
  297. this.url, 'playing',
  298. this.player.getCurrentTime(),
  299. this.player.isMuted(),
  300. this.player.getVolume());
  301. }
  302. }
  303. /**
  304. * Updates video, if its not playing and needs starting or
  305. * if its playing and needs to be paysed
  306. * @param id the id of the sender of the command
  307. * @param url the video url
  308. * @param attributes
  309. */
  310. onSharedVideoUpdate (id, url, attributes) {
  311. // if we are sending the event ignore
  312. if(APP.conference.isLocalId(this.from)) {
  313. return;
  314. }
  315. if(!this.isSharedVideoShown) {
  316. this.onSharedVideoStart(id, url, attributes);
  317. return;
  318. }
  319. if(!this.player)
  320. this.initialAttributes = attributes;
  321. else {
  322. this.processVideoUpdate(this.player, attributes);
  323. }
  324. }
  325. /**
  326. * Stop shared video if it is currently showed. If the user started the
  327. * shared video is the one in the id (called when user
  328. * left and we want to remove video if the user sharing it left).
  329. * @param id the id of the sender of the command
  330. */
  331. onSharedVideoStop (id, attributes) {
  332. if (!this.isSharedVideoShown)
  333. return;
  334. if(this.from !== id)
  335. return;
  336. if(!this.player) {
  337. // if there is no error in the player till now,
  338. // store the initial attributes
  339. if (!this.errorInPlayer) {
  340. this.initialAttributes = attributes;
  341. return;
  342. }
  343. }
  344. if(this.intervalId) {
  345. clearInterval(this.intervalId);
  346. this.intervalId = null;
  347. }
  348. this.emitter.removeListener(UIEvents.AUDIO_MUTED,
  349. this.localAudioMutedListener);
  350. this.localAudioMutedListener = null;
  351. VideoLayout.removeParticipantContainer(this.url);
  352. VideoLayout.showLargeVideoContainer(SHARED_VIDEO_CONTAINER_TYPE, false)
  353. .then(() => {
  354. VideoLayout.removeLargeVideoContainer(
  355. SHARED_VIDEO_CONTAINER_TYPE);
  356. if(this.player) {
  357. this.player.destroy();
  358. this.player = null;
  359. } // if there is an error in player, remove that instance
  360. else if (this.errorInPlayer) {
  361. this.errorInPlayer.destroy();
  362. this.errorInPlayer = null;
  363. }
  364. this.smartAudioUnmute();
  365. // revert to original behavior (prevents pausing
  366. // for participants not sharing the video to pause it)
  367. $("#sharedVideo").css("pointer-events","auto");
  368. });
  369. this.url = null;
  370. this.isSharedVideoShown = false;
  371. this.initialAttributes = null;
  372. }
  373. /**
  374. * Receives events for local audio mute/unmute by local user.
  375. * @param muted boolena whether it is muted or not.
  376. * @param {boolean} indicates if this mute was a result of user interaction,
  377. * i.e. pressing the mute button or it was programatically triggerred
  378. */
  379. onLocalAudioMuted (muted, userInteraction) {
  380. if(!this.player)
  381. return;
  382. if (muted) {
  383. this.mutedWithUserInteraction = userInteraction;
  384. }
  385. else if (this.player.getPlayerState() !== YT.PlayerState.PAUSED) {
  386. this.smartPlayerMute(true, false);
  387. // Check if we need to update other participants
  388. this.fireSharedVideoEvent();
  389. }
  390. }
  391. /**
  392. * Mutes / unmutes the player.
  393. * @param mute true to mute the shared video, false - otherwise.
  394. * @param {boolean} Indicates if this mute is a consequence of a network
  395. * video update or is called locally.
  396. */
  397. smartPlayerMute(mute, isVideoUpdate) {
  398. if (!this.player.isMuted() && mute) {
  399. this.player.mute();
  400. if (isVideoUpdate)
  401. this.smartAudioUnmute();
  402. }
  403. else if (this.player.isMuted() && !mute) {
  404. this.player.unMute();
  405. if (isVideoUpdate)
  406. this.smartAudioMute();
  407. }
  408. this.showSharedVideoMutedPopup(mute);
  409. }
  410. /**
  411. * Smart mike unmute. If the mike is currently muted and it wasn't muted
  412. * by the user via the mike button and the volume of the shared video is on
  413. * we're unmuting the mike automatically.
  414. */
  415. smartAudioUnmute() {
  416. if (APP.conference.isLocalAudioMuted()
  417. && !this.mutedWithUserInteraction
  418. && !this.isSharedVideoVolumeOn()) {
  419. this.emitter.emit(UIEvents.AUDIO_MUTED, false, false);
  420. this.showMicMutedPopup(false);
  421. }
  422. }
  423. /**
  424. * Smart mike mute. If the mike isn't currently muted and the shared video
  425. * volume is on we mute the mike.
  426. */
  427. smartAudioMute() {
  428. if (!APP.conference.isLocalAudioMuted()
  429. && this.isSharedVideoVolumeOn()) {
  430. this.emitter.emit(UIEvents.AUDIO_MUTED, true, false);
  431. this.showMicMutedPopup(true);
  432. }
  433. }
  434. /**
  435. * Shows a popup under the microphone toolbar icon that notifies the user
  436. * of automatic mute after a shared video has started.
  437. * @param show boolean, show or hide the notification
  438. */
  439. showMicMutedPopup (show) {
  440. if(show)
  441. this.showSharedVideoMutedPopup(false);
  442. UIUtil.animateShowElement($("#micMutedPopup"), show, 5000);
  443. }
  444. /**
  445. * Shows a popup under the shared video toolbar icon that notifies the user
  446. * of automatic mute of the shared video after the user has unmuted their
  447. * mic.
  448. * @param show boolean, show or hide the notification
  449. */
  450. showSharedVideoMutedPopup (show) {
  451. if(show)
  452. this.showMicMutedPopup(false);
  453. UIUtil.animateShowElement($("#sharedVideoMutedPopup"), show, 5000);
  454. }
  455. }
  456. /**
  457. * Container for shared video iframe.
  458. */
  459. class SharedVideoContainer extends LargeContainer {
  460. constructor ({url, iframe, player}) {
  461. super();
  462. this.$iframe = $(iframe);
  463. this.url = url;
  464. this.player = player;
  465. }
  466. get $video () {
  467. return this.$iframe;
  468. }
  469. show () {
  470. let self = this;
  471. return new Promise(resolve => {
  472. this.$iframe.fadeIn(300, () => {
  473. self.bodyBackground = document.body.style.background;
  474. document.body.style.background = 'black';
  475. this.$iframe.css({opacity: 1});
  476. ToolbarToggler.dockToolbar(true);
  477. resolve();
  478. });
  479. });
  480. }
  481. hide () {
  482. let self = this;
  483. ToolbarToggler.dockToolbar(false);
  484. return new Promise(resolve => {
  485. this.$iframe.fadeOut(300, () => {
  486. document.body.style.background = self.bodyBackground;
  487. this.$iframe.css({opacity: 0});
  488. resolve();
  489. });
  490. });
  491. }
  492. onHoverIn () {
  493. ToolbarToggler.showToolbar();
  494. }
  495. get id () {
  496. return this.url;
  497. }
  498. resize (containerWidth, containerHeight) {
  499. let height = containerHeight - FilmStrip.getFilmStripHeight();
  500. let width = containerWidth;
  501. this.$iframe.width(width).height(height);
  502. }
  503. /**
  504. * @return {boolean} do not switch on dominant speaker event if on stage.
  505. */
  506. stayOnStage () {
  507. return false;
  508. }
  509. }
  510. function SharedVideoThumb (url)
  511. {
  512. this.id = url;
  513. this.url = url;
  514. this.setVideoType(SHARED_VIDEO_CONTAINER_TYPE);
  515. this.videoSpanId = "sharedVideoContainer";
  516. this.container = this.createContainer(this.videoSpanId);
  517. this.container.onclick = this.videoClick.bind(this);
  518. SmallVideo.call(this, VideoLayout);
  519. this.isVideoMuted = true;
  520. }
  521. SharedVideoThumb.prototype = Object.create(SmallVideo.prototype);
  522. SharedVideoThumb.prototype.constructor = SharedVideoThumb;
  523. /**
  524. * hide display name
  525. */
  526. SharedVideoThumb.prototype.setDeviceAvailabilityIcons = function () {};
  527. SharedVideoThumb.prototype.avatarChanged = function () {};
  528. SharedVideoThumb.prototype.createContainer = function (spanId) {
  529. var container = document.createElement('span');
  530. container.id = spanId;
  531. container.className = 'videocontainer';
  532. // add the avatar
  533. var avatar = document.createElement('img');
  534. avatar.id = 'avatar_' + this.id;
  535. avatar.className = 'sharedVideoAvatar';
  536. avatar.src = "https://img.youtube.com/vi/" + this.url + "/0.jpg";
  537. container.appendChild(avatar);
  538. var remotes = document.getElementById('remoteVideos');
  539. return remotes.appendChild(container);
  540. };
  541. /**
  542. * The thumb click handler.
  543. */
  544. SharedVideoThumb.prototype.videoClick = function () {
  545. VideoLayout.handleVideoThumbClicked(this.url);
  546. };
  547. /**
  548. * Removes RemoteVideo from the page.
  549. */
  550. SharedVideoThumb.prototype.remove = function () {
  551. console.log("Remove shared video thumb", this.id);
  552. // Make sure that the large video is updated if are removing its
  553. // corresponding small video.
  554. this.VideoLayout.updateAfterThumbRemoved(this.id);
  555. // Remove whole container
  556. if (this.container.parentNode) {
  557. this.container.parentNode.removeChild(this.container);
  558. }
  559. };
  560. /**
  561. * Sets the display name for the thumb.
  562. */
  563. SharedVideoThumb.prototype.setDisplayName = function(displayName) {
  564. if (!this.container) {
  565. console.warn( "Unable to set displayName - " + this.videoSpanId +
  566. " does not exist");
  567. return;
  568. }
  569. var nameSpan = $('#' + this.videoSpanId + '>span.displayname');
  570. // If we already have a display name for this video.
  571. if (nameSpan.length > 0) {
  572. if (displayName && displayName.length > 0) {
  573. $('#' + this.videoSpanId + '_name').text(displayName);
  574. }
  575. } else {
  576. nameSpan = document.createElement('span');
  577. nameSpan.className = 'displayname';
  578. $('#' + this.videoSpanId)[0].appendChild(nameSpan);
  579. if (displayName && displayName.length > 0)
  580. $(nameSpan).text(displayName);
  581. nameSpan.id = this.videoSpanId + '_name';
  582. }
  583. };
  584. /**
  585. * Checks if given string is youtube url.
  586. * @param {string} url string to check.
  587. * @returns {boolean}
  588. */
  589. function getYoutubeLink(url) {
  590. let p = /^(?:https?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))((\w|-){11})(?:\S+)?$/;//jshint ignore:line
  591. return (url.match(p)) ? RegExp.$1 : false;
  592. }
  593. /**
  594. * Ask user if he want to close shared video.
  595. */
  596. function showStopVideoPropmpt() {
  597. return new Promise(function (resolve, reject) {
  598. messageHandler.openTwoButtonDialog(
  599. "dialog.removeSharedVideoTitle",
  600. null,
  601. "dialog.removeSharedVideoMsg",
  602. null,
  603. false,
  604. "dialog.Remove",
  605. function(e,v,m,f) {
  606. if (v) {
  607. resolve();
  608. } else {
  609. reject();
  610. }
  611. }
  612. );
  613. });
  614. }
  615. /**
  616. * Ask user for shared video url to share with others.
  617. * Dialog validates client input to allow only youtube urls.
  618. */
  619. function requestVideoLink() {
  620. let i18n = APP.translation;
  621. const title = i18n.generateTranslationHTML("dialog.shareVideoTitle");
  622. const cancelButton = i18n.generateTranslationHTML("dialog.Cancel");
  623. const shareButton = i18n.generateTranslationHTML("dialog.Share");
  624. const backButton = i18n.generateTranslationHTML("dialog.Back");
  625. const linkError
  626. = i18n.generateTranslationHTML("dialog.shareVideoLinkError");
  627. const i18nOptions = {url: defaultSharedVideoLink};
  628. const defaultUrl = i18n.translateString("defaultLink", i18nOptions);
  629. return new Promise(function (resolve, reject) {
  630. let dialog = messageHandler.openDialogWithStates({
  631. state0: {
  632. html: `
  633. <h2>${title}</h2>
  634. <input name="sharedVideoUrl" type="text"
  635. data-i18n="[placeholder]defaultLink"
  636. data-i18n-options="${JSON.stringify(i18nOptions)}"
  637. placeholder="${defaultUrl}"
  638. autofocus>`,
  639. persistent: false,
  640. buttons: [
  641. {title: cancelButton, value: false},
  642. {title: shareButton, value: true}
  643. ],
  644. focus: ':input:first',
  645. defaultButton: 1,
  646. submit: function (e, v, m, f) {
  647. e.preventDefault();
  648. if (!v) {
  649. reject('cancelled');
  650. dialog.close();
  651. return;
  652. }
  653. let sharedVideoUrl = f.sharedVideoUrl;
  654. if (!sharedVideoUrl) {
  655. return;
  656. }
  657. let urlValue = encodeURI(UIUtil.escapeHtml(sharedVideoUrl));
  658. let yVideoId = getYoutubeLink(urlValue);
  659. if (!yVideoId) {
  660. dialog.goToState('state1');
  661. return false;
  662. }
  663. resolve(yVideoId);
  664. dialog.close();
  665. }
  666. },
  667. state1: {
  668. html: `<h2>${title}</h2> ${linkError}`,
  669. persistent: false,
  670. buttons: [
  671. {title: cancelButton, value: false},
  672. {title: backButton, value: true}
  673. ],
  674. focus: ':input:first',
  675. defaultButton: 1,
  676. submit: function (e, v, m, f) {
  677. e.preventDefault();
  678. if (v === 0) {
  679. reject();
  680. dialog.close();
  681. } else {
  682. dialog.goToState('state0');
  683. }
  684. }
  685. }
  686. });
  687. });
  688. }