Azema / ABMoteurs

// ==UserScript==
// @name        ABMoteurs
// @namespace   abmoteurs
// @description Met à jour le programme en cours sur le site Web AUTOMOTO la chaîne
// @match       https://www.automoto-lachaine.fr/*
// @require     https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js
// @version     1.0.2
// @author      Manuel Hervo
// @copyright   2018, Manuel Hervo
// @license     BSD-3-Clause
// @grant       unsafeWindow
// @grant       GM_addStyle
// ==/UserScript==
(function($) {
    'use strict';
    var debug = false, // Permet d'afficher ou non les messages de debug
        logLevels = ['log', 'info', 'debug', 'warn', 'error'],
        interval = 300000, // interval des requetes toutes les 5 minutes
        intervalInitial = 300000, // interval des requetes toutes les 5 minutes
        timeoutId = null, // ID du timeout
        requestInProgress = false, // Flag de requete en cours
        errCount = 0, // Nombre d'erreurs de requetes consecutives
        force = false, // Forcage de la recuperation du programme
        firstLaunch = true, // Premier lancement du script
        jwpPosition, jwpPause = false, jwFound = true;

    /**
     * Formatte la date et l'heure au format français
     */
    function formatDate(date) {
        'use strict';
        var day = date.getDate(),
            month = date.getMonth(),
            hour = date.getHours(),
            minute = date.getMinutes(),
            seconds = date.getSeconds();

        var format = (day<10?'0'+day.toString():day).toString() + '/' + (month<10?'0'+month.toString():month).toString() + '/' + date.getFullYear().toString()
                   + ' ' + (hour<10?'0'+hour.toString():hour).toString() + ':' + (minute<10?'0'+minute.toString():minute).toString() + ':'
                   + (seconds<10?'0'+seconds.toString():seconds).toString();
        return format;
    }

    /**
     * Fonction d'affchage d'un message dans la console préfixé d'une date
     */
    function log(type) {
        'use strict';
        if (logLevels.lastIndexOf(type) < 0) {
            type = 'log';
        } else {
            Array.prototype.shift.call(arguments);
        }
        // Si debug est false, on affiche que les messages d'erreur
        if (!debug && logLevels.lastIndexOf(type) < 3) {
            return;
        }
        var now = new Date();
        Array.prototype.unshift.call(arguments, '[' + formatDate(now) + ']: ');
        console[type].apply(this, arguments);
    }

    /**
     * Fonction de remplacement d'un block HTML avec fonction callback
     */
    $.fn.replaceWithCallback = function(replace, callback){
        var ret = $.fn.replaceWith.call(this, replace); // Call replaceWith
        if (typeof callback === 'function'){
            callback.call(ret, true); // Call your callback
        }
        return ret; // For chaining
    };
    /**
     * Fonction pour l'animation de la barre de progression
     */
    function animProgress(elem, progress) {
        log('animProgress called');
        if (progress > 100) {
            progress = 100;
        }
        $(elem).animate({
            width: progress+'%'
        }, {
            duration: 400,
            // swing or linear
            easing: 'linear',
            complete: function(scope, i, elem) {
                log('animProgress complete');
            }
        });
    }

    /**
     * Recupere la page Web du site ABMoteur
     */
    function getPage(cb) {
        log('getPage called');
        requestInProgress = true;
        $.ajax({
            url: '/Live-Replay',
            timeout: 5000,
            method: 'GET',
            dataType: 'html',
            success: cb,
            error: function(respObj, textStatus, errorThrown) {
                if (++errCount >= 5) {
                    log('error', 'GetPage 5 errors continue');
                    return;
                }
                log('error', 'Error! ', respObj.status, respObj.statusText);
                requestInProgress = false;
                timeoutId = setTimeout(getPrograms, 500, cb);
            },
            complete: function(respObj, textStatus) {
                log('log', 'AJAX Complete. Status: ', textStatus);
            }});
    }

    /**
     * Recupere la partie des programmes en cours dans la page HTML passée en paramètre
     */
    function getOneThird(page) {
        log('getOneThird called');
        var html = $.parseHTML(page);
        var $oneThird = $('.live-replay .container .col-md-4', html);
        if ($oneThird.length == 1) {
            return $oneThird;
        }
        return undefined;
    }

    /**
     * Met à jour la progression du programme en cours
     */
    function updateProgress(forceProgress) {
        log('updateProgress called');
        var now = new Date(),
            $progress = $('#progress_bar'),
            nowMin = (now.getHours() * 60) + now.getMinutes(),
            debut = $('#date_deb_diff').text(),
            debMin,
            fin = $('#date_fin_diff').text(),
            finMin, tmp, duration, percent = 0;
        forceProgress = forceProgress || false;

        //log('log', 'debut: %s, fin: %s', debut, fin);
        tmp = debut.split(':');
        debMin = (parseInt(tmp[0], 10) * 60) + (parseInt(tmp[1], 10));
        //log('log', 'debMin: ', debMin);
        tmp = fin.split(':');
        finMin = (parseInt(tmp[0], 10) * 60) + (parseInt(tmp[1], 10));
        //log('log', 'finMin: ', finMin);
        if (nowMin > debMin) {
            nowMin -= debMin;
            //log('now: ', nowMin);
            duration = finMin - debMin;
            percent = Math.round(parseInt((nowMin * 100) / duration));
        }
        log('log', 'percent: ' + percent);
        log('log', 'forceProgress: ', forceProgress);
        //var progressVal = $progress.progressbar( 'option', 'value' );
        if (parseInt($progress.attr('data-progress')) !== percent || forceProgress) {
            $progress.attr('data-progress', percent);
            animProgress($('#progress_bar .ui-progress'), percent);
        } else {
            log('info', 'pourcentage identique');
        }
        if ((duration * 60 * 1000) < interval) {
            interval = duration * 60 * 1000;
        } else {
            interval = intervalInitial;
        }
        if (!jwpPause && jwpPosition == jwplayer().getPosition()) {
            //location.reload();
        }
        jwpPosition = jwplayer().getPosition();
    }

    /**
     * Calcule la durée restante du programme en cours
     * @return le nombre de minutes restantes
     */
    function getRemainingTimeOfProgram() {
        var fin = $('#date_fin_diff').text(),
            now = new Date(),
            nowMin = (now.getHours() * 60) + now.getMinutes(),
            tmp, finMin;
        tmp = fin.split(':');
        finMin = (parseInt(tmp[0], 10) * 60) + (parseInt(tmp[1], 10));
        return finMin - nowMin;
    }

    /**
     * Ajoute un bouton de rafraichissement dans la partie du programme en cours
     */
    function addRefreshBtn() {
        var background = '';
        if (!jwFound) {
            background = 'background-color:yellow;text-align:center;';
        }
        var title = $('.live-replay .container .col-md-4 h4:first');
        GM_addStyle('.live-replay .container .col-md-4 h4 { display: inline-block; } .live-replay .container .col-md-4 .title {display: block;} #refresh-prog {cursor:pointer;}');
        title.after('<span id="refresh-prog" style="display:inline-block;margin-left:15px;'+background+'"><img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABoAAAAaCAYAAACpSkzOAAAEE0lEQVRIib2WzWtTTRTGf3PT3OTmhkCpobG4URJECk2bhW3UjWAtShcuFDURV9o2i0IXBf0XxOJO1K2UBHUjaKFC4KWQiLQlBFFQiMEosVohLsxH0yR3XOW++arv6u1ZzdyZc57zPDPnzBUjI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De/fukU6neffuHYlEgnA4zMmTJ9F1HVVVURQFKSWGYZgv7OvXr4lGo3z69MkE6TwCswUJIUJ2u/10pVJpy0QIwdGjR7lw4QLBYBCPx0O1WuXHjx8kk0lWVlbIZDJ7dfie/wz/q+3b79a+Af0BDI/MPIPYT18AAAAASUVORK5CYII=" style="width:50%;"/></span>');
        $('#refresh-prog').off().click(function() {
            clearTimeout(timeoutId); // On tue l'appel de fonction en cours
            force = true; // On active le forcage de la mise a jour du programme
            getPrograms(); // On demande la mise à jour
        });
    }

    function getPrograms() {
        if (/Live-Replay/.test(document.location) === false) {
            return;
        }
        log('getPrograms called');
        // On vérifie si la fin du programme est dans moins de 5 minutes
        var remaining = getRemainingTimeOfProgram();
        if ((remaining <= 5 || force) && !requestInProgress) {
            force = false; // On desactive le forcage de la mise a jour
            getPage(function (data, textStatus) {
                requestInProgress = false;
                errCount = 0;
                log('callback getPage');
                if (data) {
                    var $oneThird = getOneThird(data);
                    if ($oneThird !== undefined) {
                        log('one_third update');
                        $('.live-replay .container .col-md-4').replaceWithCallback($oneThird, updateProgress);
                        // On ajoute un bouton de refresh
                        addRefreshBtn();
                    }
                }
                // On relance la fonction dans interval de temps
                timeoutId = setTimeout(getPrograms, interval);
            });
        } else {
            timeoutId = setTimeout(getPrograms, interval);
        }
        // Si premier lancement, on ajoute le bouton de refresh
        if (firstLaunch) {
            firstLaunch = false;
            addRefreshBtn();
        }
    }

    // Chargement du script jwplayer
    function addJwPlayer(d, s, id) {
        var js,
            fjs = d.getElementsByTagName(s)[0],
            p = /^http:/.test(d.location) ? 'http' : 'https';
        if (!d.getElementById(id)) {
            js = d.createElement(s);
            js.id = id;
            js.type = 'text/javascript';
            js.src = p + '://cdn.jwplayer.com/players/nPripu9l-ALJ3XQCI.js';
            fjs.parentNode.insertBefore(js, fjs);
        }
    }
    // Initialisation du player
    function setupPlayer() {
        //jwplayer.key = 'PA80S1NuJPtZSHmnEH5k9umR5MbmZWu3pc8hG4vYk0WGLCjxhRNGfUlS8QCE01ts';
        jwplayer.key = '3tZRiXLaugEqX2QSB5mGtG5QpF2nCZb3vtIlDBC+/Qc=';
        jwplayer('fp-hlsjs').setup({
            'file': 'https://live.automoto-lachaine.fr/abmoteur.isml/manifest.m3u8?hdnts=exp=1549967288~acl=/*~hmac=dc144caf194a6ad4d8995e23467dca3ce8c9d317d08c7b8c56bd5547f5672fe8',
            'aspectratio': '16:9',
            'autostart': true,
            'cast': {},
            'controls': true,
            'primary': 'html5',
            'stagevideo': false,
            'stretching': 'uniform',
            'width': '100%',
            'ph': 1,
            'pid': 'V64tMklE',
            'withCredentials': true,
            plugins: {
                'https://cdn.stickyadstv.com/plugins/jw/StickyJW6Plugin.js': {
                    remainingAdTime: 'This advertisement runs for [sec] seconds',
                    ads: {
                        zones: {
                            preroll: '2074',
                            midroll: '-1',
                            postroll: '2076'
                        },
                        midrollDelay: 10,
                        midrollInterval: 60,
                        'companionZones': '2074;2076'
                    }
                }
            }
        });

        jwplayer().on('error', function (err) {
            var header = document.getElementById('fp-message_h'),
                detail = document.getElementById('fp-message_p'),
                color = 'color:black;';
            header.innerHTML = '<div style="' + color + '">Le flux Live n\'est pas disponible. Veuillez activer les cookies sur votre navigateur internet.</div> <a href="http://www.groupe-ab.fr/How-do-I-allow-third-party-cookies-to-be-set-in-my-browser.html" target="_blank" style="' + color + '">Besoin d\'aide pour activer les cookies</a>';
            detail.innerHTML = ' ';
            $.ajax({
                type: 'GET',
                url: 'http://str.abweb.com/ABVIptv.asmx/LogVideoLoadError?video=https://live.automoto-lachaine.fr/abmoteur.isml/manifest.m3u8?hdnts=exp=1541491726~acl=/*~hmac=397d1e292f707b400dabe54620c21cd9f4b906b4910b03dcf68e3df8dbc35991&errorCode=' + err.message + '&engineName=engine&userAgent=' + navigator.userAgent,
                dataType: 'jsonp'
            });
        });
    }
    // fonction qui attend que jwplayer soit chargé
    function checkPlayer() {
        if (typeof jwplayer == 'undefined') {
            setTimeout(checkPlayer, 500);
        } else {
            setupPlayer();
        }
    }
    // Rustine pour le player manquant
    /*if (typeof jwplayer == 'undefined') {
        jwFound = false;
        addJwPlayer(document, 'script', 'Wjwplayer');
        checkPlayer();
    }*/

    // Au lancement, on appelle la fonction de recuperation du programme en cours
    getPrograms();
    // On met à jour la progression du programme a intervalle réguliere
    setInterval(updateProgress, 60000);
    // On ajoute un attribut a l'iframe du player pour autoriser le plein ecran
    $('.ifram_player').attr('allowfullscreen', '');

    // Ajout du bouton Live-Replay sur la page d'accueil du site automoto-lachaine.fr
    $('.topbar-right.one_half_less.last').prepend('<a href="/Live-Replay"><div class="btn btn-primary">Live-Replay</div></a>');

    /*if (typeof jwplayer != 'undefined') {
        jwplayer().on('pause', function() {jwpPause = true;});
        jwplayer().on('play', function() {jwpPause = false;});
    }*/
    $('.twitter-timeline').remove();
}(jQuery));