| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750 | /* global $, APP, YT, onPlayerReady, onPlayerStateChange, onPlayerError */
import messageHandler from '../util/MessageHandler';
import UIUtil from '../util/UIUtil';
import UIEvents from '../../../service/UI/UIEvents';
import VideoLayout from "../videolayout/VideoLayout";
import LargeContainer from '../videolayout/LargeContainer';
import SmallVideo from '../videolayout/SmallVideo';
import FilmStrip from '../videolayout/FilmStrip';
import ToolbarToggler from "../toolbars/ToolbarToggler";
export const SHARED_VIDEO_CONTAINER_TYPE = "sharedvideo";
/**
 * Example shared video link.
 * @type {string}
 */
const defaultSharedVideoLink = "https://www.youtube.com/watch?v=xNXN7CZk8X0";
const updateInterval = 5000; // milliseconds
/**
 * Manager of shared video.
 */
export default class SharedVideoManager {
    constructor (emitter) {
        this.emitter = emitter;
        this.isSharedVideoShown = false;
        this.isPlayerAPILoaded = false;
    }
    /**
     * Starts shared video by asking user for url, or if its already working
     * asks whether the user wants to stop sharing the video.
     */
    toggleSharedVideo () {
        if(!this.isSharedVideoShown) {
            requestVideoLink().then(
                    url => this.emitter.emit(
                                UIEvents.UPDATE_SHARED_VIDEO, url, 'start'),
                    err => console.error('SHARED VIDEO CANCELED', err)
            );
            return;
        }
        if(APP.conference.isLocalId(this.from)) {
            showStopVideoPropmpt().then(() =>
                this.emitter.emit(
                    UIEvents.UPDATE_SHARED_VIDEO, this.url, 'stop'));
        } else {
            messageHandler.openMessageDialog(
                "dialog.shareVideoTitle",
                "dialog.alreadySharedVideoMsg"
            );
        }
    }
    /**
     * Shows the player component and starts the checking function
     * that will be sending updates, if we are the one shared the video
     * @param id the id of the sender of the command
     * @param url the video url
     * @param attributes
     */
    showSharedVideo (id, url, attributes) {
        if (this.isSharedVideoShown)
            return;
        this.isSharedVideoShown = true;
        // the video url
        this.url = url;
        // the owner of the video
        this.from = id;
        //listen for local audio mute events
        this.localAudioMutedListener = this.localAudioMuted.bind(this);
        this.emitter.on(UIEvents.AUDIO_MUTED, this.localAudioMutedListener);
        // This code loads the IFrame Player API code asynchronously.
        var tag = document.createElement('script');
        tag.src = "https://www.youtube.com/iframe_api";
        var firstScriptTag = document.getElementsByTagName('script')[0];
        firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
        // sometimes we receive errors like player not defined
        // or player.pauseVideo is not a function
        // we need to operate with player after start playing
        // self.player will be defined once it start playing
        // and will process any initial attributes if any
        this.initialAttributes = attributes;
        var self = this;
        if(self.isPlayerAPILoaded)
            window.onYouTubeIframeAPIReady();
        else
            window.onYouTubeIframeAPIReady = function() {
                self.isPlayerAPILoaded = true;
                let showControls = APP.conference.isLocalId(self.from) ? 1 : 0;
                let p = new YT.Player('sharedVideoIFrame', {
                    height: '100%',
                    width: '100%',
                    videoId: self.url,
                    playerVars: {
                        'origin': location.origin,
                        'fs': '0',
                        'autoplay': 0,
                        'controls': showControls,
                        'rel' : 0
                    },
                    events: {
                        'onReady': onPlayerReady,
                        'onStateChange': onPlayerStateChange,
                        'onError': onPlayerError
                    }
                });
                // add listener for volume changes
                p.addEventListener(
                    "onVolumeChange", "onVolumeChange");
                if (APP.conference.isLocalId(self.from)){
                    // adds progress listener that will be firing events
                    // while we are paused and we change the progress of the
                    // video (seeking forward or backward on the video)
                    p.addEventListener(
                        "onVideoProgress", "onVideoProgress");
                }
            };
        window.onPlayerStateChange = function(event) {
            if (event.data == YT.PlayerState.PLAYING) {
                self.playerPaused = false;
                self.player = event.target;
                if(self.initialAttributes)
                {
                    self.processAttributes(
                        self.player, self.initialAttributes, self.playerPaused);
                    self.initialAttributes = null;
                }
                self.updateCheck();
            } else if (event.data == YT.PlayerState.PAUSED) {
                self.playerPaused = true;
                self.updateCheck(true);
            }
        };
        /**
         * Track player progress while paused.
         * @param event
         */
        window.onVideoProgress = function (event) {
            let state = event.target.getPlayerState();
            if (state == YT.PlayerState.PAUSED) {
                self.updateCheck(true);
            }
        };
        /**
         * Gets notified for volume state changed.
         * @param event
         */
        window.onVolumeChange = function (event) {
            self.updateCheck();
            // let's check, if player is not muted lets mute locally
            if(event.data.volume > 0 && !event.data.muted
                && !APP.conference.isLocalAudioMuted()){
                self.emitter.emit(UIEvents.AUDIO_MUTED, true);
                self.showMicMutedPopup(true);
            }
        };
        window.onPlayerReady = function(event) {
            let player = event.target;
            // do not relay on autoplay as it is not sending all of the events
            // in onPlayerStateChange
            player.playVideo();
            let thumb = new SharedVideoThumb(self.url);
            thumb.setDisplayName(player.getVideoData().title);
            VideoLayout.addParticipantContainer(self.url, thumb);
            let iframe = player.getIframe();
            self.sharedVideo = new SharedVideoContainer(
                {url, iframe, player});
            //prevents pausing participants not sharing the video
            // to pause the video
            if (!APP.conference.isLocalId(self.from)) {
                $("#sharedVideo").css("pointer-events","none");
            }
            VideoLayout.addLargeVideoContainer(
                SHARED_VIDEO_CONTAINER_TYPE, self.sharedVideo);
            VideoLayout.handleVideoThumbClicked(self.url);
            // If we are sending the command and we are starting the player
            // we need to continuously send the player current time position
            if(APP.conference.isLocalId(self.from)) {
                self.intervalId = setInterval(
                    self.updateCheck.bind(self),
                    updateInterval);
            }
        };
        window.onPlayerError = function(event) {
            console.error("Error in the player:", event.data);
            // store the error player, so we can remove it
            self.errorInPlayer = event.target;
        };
    }
    /**
     * Process attributes, whether player needs to be paused or seek.
     * @param player the player to operate over
     * @param attributes the attributes with the player state we want
     * @param playerPaused current saved state for the player
     */
    processAttributes (player, attributes, playerPaused)
    {
        if(!attributes)
            return;
        if (attributes.state == 'playing') {
            this.processTime(player, attributes, playerPaused);
            // lets check the volume
            if (attributes.volume !== undefined &&
                player.getVolume() != attributes.volume
                && APP.conference.isLocalAudioMuted()) {
                player.setVolume(attributes.volume);
                console.info("Player change of volume:" + attributes.volume);
                this.showSharedVideoMutedPopup(false);
            }
            if(playerPaused)
                player.playVideo();
        } else if (attributes.state == 'pause') {
            // if its not paused, pause it
            player.pauseVideo();
            this.processTime(player, attributes, true);
        } else if (attributes.state == 'stop') {
            this.stopSharedVideo(this.from);
        }
    }
    /**
     * Check for time in attributes and if needed seek in current player
     * @param player the player to operate over
     * @param attributes the attributes with the player state we want
     * @param forceSeek whether seek should be forced
     */
    processTime (player, attributes, forceSeek)
    {
        if(forceSeek) {
            console.info("Player seekTo:", attributes.time);
            player.seekTo(attributes.time);
            return;
        }
        // check received time and current time
        let currentPosition = player.getCurrentTime();
        let diff = Math.abs(attributes.time - currentPosition);
        // if we drift more than the interval for checking
        // sync, the interval is in milliseconds
        if(diff > updateInterval/1000) {
            console.info("Player seekTo:", attributes.time,
                " current time is:", currentPosition, " diff:", diff);
            player.seekTo(attributes.time);
        }
    }
    /**
     * Checks current state of the player and fire an event with the values.
     */
    updateCheck(sendPauseEvent)
    {
        // ignore update checks if we are not the owner of the video
        // or there is still no player defined or we are stopped
        // (in a process of stopping)
        if(!APP.conference.isLocalId(this.from) || !this.player
            || !this.isSharedVideoShown)
            return;
        let state = this.player.getPlayerState();
        // if its paused and haven't been pause - send paused
        if (state === YT.PlayerState.PAUSED && sendPauseEvent) {
            this.emitter.emit(UIEvents.UPDATE_SHARED_VIDEO,
                this.url, 'pause', this.player.getCurrentTime());
        }
        // if its playing and it was paused - send update with time
        // if its playing and was playing just send update with time
        else if (state === YT.PlayerState.PLAYING) {
            this.emitter.emit(UIEvents.UPDATE_SHARED_VIDEO,
                this.url, 'playing',
                this.player.getCurrentTime(),
                this.player.isMuted() ? 0 : this.player.getVolume());
        }
    }
    /**
     * Updates video, if its not playing and needs starting or
     * if its playing and needs to be paysed
     * @param id the id of the sender of the command
     * @param url the video url
     * @param attributes
     */
    updateSharedVideo (id, url, attributes) {
        // if we are sending the event ignore
        if(APP.conference.isLocalId(this.from)) {
            return;
        }
        if(!this.isSharedVideoShown) {
            this.showSharedVideo(id, url, attributes);
            return;
        }
        if(!this.player)
            this.initialAttributes = attributes;
        else {
            this.processAttributes(this.player, attributes, this.playerPaused);
        }
    }
    /**
     * Stop shared video if it is currently showed. If the user started the
     * shared video is the one in the id (called when user
     * left and we want to remove video if the user sharing it left).
     * @param id the id of the sender of the command
     */
    stopSharedVideo (id, attributes) {
        if (!this.isSharedVideoShown)
            return;
        if(this.from !== id)
            return;
        if(!this.player){
            // if there is no error in the player till now,
            // store the initial attributes
            if (!this.errorInPlayer) {
                this.initialAttributes = attributes;
                return;
            }
        }
        if(this.intervalId) {
            clearInterval(this.intervalId);
            this.intervalId = null;
        }
        this.emitter.removeListener(UIEvents.AUDIO_MUTED,
            this.localAudioMutedListener);
        this.localAudioMutedListener = null;
        this.showSharedVideoMutedPopup(false);
        VideoLayout.removeParticipantContainer(this.url);
        VideoLayout.showLargeVideoContainer(SHARED_VIDEO_CONTAINER_TYPE, false)
            .then(() => {
                VideoLayout.removeLargeVideoContainer(
                    SHARED_VIDEO_CONTAINER_TYPE);
                if(this.player) {
                    this.player.destroy();
                    this.player = null;
                } // if there is an error in player, remove that instance
                else if (this.errorInPlayer) {
                    this.errorInPlayer.destroy();
                    this.errorInPlayer = null;
                }
                // revert to original behavior (prevents pausing
                // for participants not sharing the video to pause it)
                $("#sharedVideo").css("pointer-events","auto");
        });
        this.url = null;
        this.isSharedVideoShown = false;
        this.initialAttributes = null;
    }
    /**
     * Receives events for local audio mute/unmute by local user.
     * @param muted boolena whether it is muted or not.
     */
    localAudioMuted (muted) {
        if(!this.player)
            return;
        if(muted)
            return;
        // if we are un-muting and player is not muted, lets muted
        // to not pollute the conference
        if(this.player.getVolume() > 0 || !this.player.isMuted()){
            this.player.setVolume(0);
            this.showSharedVideoMutedPopup(true);
        }
    }
    /**
     * Shows a popup under the microphone toolbar icon that notifies the user
     * of automatic mute after a shared video has started.
     * @param show boolean, show or hide the notification
     */
    showMicMutedPopup (show) {
        var micMutedPopupSelector = $("#micMutedPopup");
        if(show) {
            this.showSharedVideoMutedPopup(false);
            if (!micMutedPopupSelector.is(":visible"))
                micMutedPopupSelector.css("display", "inline-block");
            // FIXME: we need an utility method for that.
            micMutedPopupSelector.fadeIn(300,
                () => {micMutedPopupSelector.css({opacity: 1});}
            );
            setTimeout(
                function () {
                    micMutedPopupSelector.fadeOut(300,
                        () => {micMutedPopupSelector.css({opacity: 0});}
                    );
                }, 5000);
        }
        else {
            micMutedPopupSelector.fadeOut(300,
                () => {micMutedPopupSelector.css({opacity: 0});}
            );
        }
    }
    /**
     * Shows a popup under the shared video toolbar icon that notifies the user
     * of automatic mute of the shared video after the user has unmuted their
     * mic.
     * @param show boolean, show or hide the notification
     */
    showSharedVideoMutedPopup (show) {
        var sharedVideoMutedPopupSelector = $("#sharedVideoMutedPopup");
        if(show) {
            this.showMicMutedPopup(false);
            if (!sharedVideoMutedPopupSelector.is(":visible"))
                sharedVideoMutedPopupSelector.css("display", "inline-block");
            // FIXME: we need an utility method for that.
            sharedVideoMutedPopupSelector.fadeIn(300,
                () => {sharedVideoMutedPopupSelector.css({opacity: 1});}
            );
            setTimeout(
                function () {
                    sharedVideoMutedPopupSelector.fadeOut(300,
                        () => {sharedVideoMutedPopupSelector.css({opacity: 0});}
                    );
                }, 5000);
        }
        else {
            sharedVideoMutedPopupSelector.fadeOut(300,
                () => {sharedVideoMutedPopupSelector.css({opacity: 0});}
            );
        }
    }
}
/**
 * Container for shared video iframe.
 */
class SharedVideoContainer extends LargeContainer {
    constructor ({url, iframe, player}) {
        super();
        this.$iframe = $(iframe);
        this.url = url;
        this.player = player;
    }
    get $video () {
        return this.$iframe;
    }
    show () {
        let self = this;
        return new Promise(resolve => {
            this.$iframe.fadeIn(300, () => {
                self.bodyBackground = document.body.style.background;
                document.body.style.background = 'black';
                this.$iframe.css({opacity: 1});
                ToolbarToggler.dockToolbar(true);
                resolve();
            });
        });
    }
    hide () {
        let self = this;
        ToolbarToggler.dockToolbar(false);
        return new Promise(resolve => {
            this.$iframe.fadeOut(300, () => {
                document.body.style.background = self.bodyBackground;
                this.$iframe.css({opacity: 0});
                resolve();
            });
        });
    }
    onHoverIn () {
        ToolbarToggler.showToolbar();
    }
    get id () {
        return this.url;
    }
    resize (containerWidth, containerHeight) {
        let height = containerHeight - FilmStrip.getFilmStripHeight();
        let width = containerWidth;
        this.$iframe.width(width).height(height);
    }
    /**
     * @return {boolean} do not switch on dominant speaker event if on stage.
     */
    stayOnStage () {
        return false;
    }
}
function SharedVideoThumb (url)
{
    this.id = url;
    this.url = url;
    this.setVideoType(SHARED_VIDEO_CONTAINER_TYPE);
    this.videoSpanId = "sharedVideoContainer";
    this.container = this.createContainer(this.videoSpanId);
    this.container.onclick = this.videoClick.bind(this);
    SmallVideo.call(this, VideoLayout);
    this.isVideoMuted = true;
}
SharedVideoThumb.prototype = Object.create(SmallVideo.prototype);
SharedVideoThumb.prototype.constructor = SharedVideoThumb;
/**
 * hide display name
 */
SharedVideoThumb.prototype.setDeviceAvailabilityIcons = function () {};
SharedVideoThumb.prototype.avatarChanged = function () {};
SharedVideoThumb.prototype.createContainer = function (spanId) {
    var container = document.createElement('span');
    container.id = spanId;
    container.className = 'videocontainer';
    // add the avatar
    var avatar = document.createElement('img');
    avatar.id = 'avatar_' + this.id;
    avatar.className = 'sharedVideoAvatar';
    avatar.src = "https://img.youtube.com/vi/" + this.url + "/0.jpg";
    container.appendChild(avatar);
    var remotes = document.getElementById('remoteVideos');
    return remotes.appendChild(container);
};
/**
 * The thumb click handler.
 */
SharedVideoThumb.prototype.videoClick = function () {
    VideoLayout.handleVideoThumbClicked(this.url);
};
/**
 * Removes RemoteVideo from the page.
 */
SharedVideoThumb.prototype.remove = function () {
    console.log("Remove shared video thumb", this.id);
    // Make sure that the large video is updated if are removing its
    // corresponding small video.
    this.VideoLayout.updateAfterThumbRemoved(this.id);
    // Remove whole container
    if (this.container.parentNode) {
        this.container.parentNode.removeChild(this.container);
    }
};
/**
 * Sets the display name for the thumb.
 */
SharedVideoThumb.prototype.setDisplayName = function(displayName) {
    if (!this.container) {
        console.warn( "Unable to set displayName - " + this.videoSpanId +
            " does not exist");
        return;
    }
    var nameSpan = $('#' + this.videoSpanId + '>span.displayname');
    // If we already have a display name for this video.
    if (nameSpan.length > 0) {
        if (displayName && displayName.length > 0) {
            $('#' + this.videoSpanId + '_name').text(displayName);
        }
    } else {
        nameSpan = document.createElement('span');
        nameSpan.className = 'displayname';
        $('#' + this.videoSpanId)[0].appendChild(nameSpan);
        if (displayName && displayName.length > 0)
            $(nameSpan).text(displayName);
        nameSpan.id = this.videoSpanId + '_name';
    }
};
/**
 * Checks if given string is youtube url.
 * @param {string} url string to check.
 * @returns {boolean}
 */
function getYoutubeLink(url) {
    let p = /^(?:https?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))((\w|-){11})(?:\S+)?$/;//jshint ignore:line
    return (url.match(p)) ? RegExp.$1 : false;
}
/**
 * Ask user if he want to close shared video.
 */
function showStopVideoPropmpt() {
    return new Promise(function (resolve, reject) {
        messageHandler.openTwoButtonDialog(
            "dialog.removeSharedVideoTitle",
            null,
            "dialog.removeSharedVideoMsg",
            null,
            false,
            "dialog.Remove",
            function(e,v,m,f) {
                if (v) {
                    resolve();
                } else {
                    reject();
                }
            }
        );
    });
}
/**
 * Ask user for shared video url to share with others.
 * Dialog validates client input to allow only youtube urls.
 */
function requestVideoLink() {
    let i18n = APP.translation;
    const title = i18n.generateTranslationHTML("dialog.shareVideoTitle");
    const cancelButton = i18n.generateTranslationHTML("dialog.Cancel");
    const shareButton = i18n.generateTranslationHTML("dialog.Share");
    const backButton = i18n.generateTranslationHTML("dialog.Back");
    const linkError
        = i18n.generateTranslationHTML("dialog.shareVideoLinkError");
    const i18nOptions = {url: defaultSharedVideoLink};
    const defaultUrl = i18n.translateString("defaultLink", i18nOptions);
    return new Promise(function (resolve, reject) {
        let dialog = messageHandler.openDialogWithStates({
            state0: {
                html:  `
                    <h2>${title}</h2>
                    <input name="sharedVideoUrl" type="text"
                           data-i18n="[placeholder]defaultLink"
                           data-i18n-options="${JSON.stringify(i18nOptions)}"
                           placeholder="${defaultUrl}"
                           autofocus>`,
                persistent: false,
                buttons: [
                    {title: cancelButton, value: false},
                    {title: shareButton, value: true}
                ],
                focus: ':input:first',
                defaultButton: 1,
                submit: function (e, v, m, f) {
                    e.preventDefault();
                    if (!v) {
                        reject('cancelled');
                        dialog.close();
                        return;
                    }
                    let sharedVideoUrl = f.sharedVideoUrl;
                    if (!sharedVideoUrl) {
                        return;
                    }
                    let urlValue = encodeURI(UIUtil.escapeHtml(sharedVideoUrl));
                    let yVideoId = getYoutubeLink(urlValue);
                    if (!yVideoId) {
                        dialog.goToState('state1');
                        return false;
                    }
                    resolve(yVideoId);
                    dialog.close();
                }
            },
            state1: {
                html: `<h2>${title}</h2> ${linkError}`,
                persistent: false,
                buttons: [
                    {title: cancelButton, value: false},
                    {title: backButton, value: true}
                ],
                focus: ':input:first',
                defaultButton: 1,
                submit: function (e, v, m, f) {
                    e.preventDefault();
                    if (v === 0) {
                        reject();
                        dialog.close();
                    } else {
                        dialog.goToState('state0');
                    }
                }
            }
        });
    });
}
 |