Jump to content

User:R'n'B/dabcolorizer.js

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by R'n'B (talk | contribs) at 18:05, 19 April 2011 (add status information on title line). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.
Note: After saving, you have to bypass your browser's cache to see the changes. Google Chrome, Firefox, Microsoft Edge and Safari: Hold down the ⇧ Shift key and click the Reload toolbar button. For details and instructions about other browsers, see Wikipedia:Bypass your cache.
// Version 0.2; alpha release

importScript("User:Luasóg bot/framework.js");

$.urlifytitle = function ( title ){
    var urlified = mw.util.wikiUrlencode(title);
    urlified = urlified.slice(0,1).toUpperCase() + urlified.slice(1);
    return urlified.replace(/'/, "%27").replace(/%21/, "!").
                    replace(/%2C/, ",").
                    replace(/%28/, "(").replace(/%29/, ")");
};

$.botStartColorizer = function (){
    var pageid,
        pageobj,
        isdisambig,
        template,
        linktitle,
        urltitle;

    if( ! $.botReady ) {
        setTimeout($.botStartColorizer, 125);
        return;
    }
    mw.log("Starting colorizer.");
    for( pageid in $.botPagelinkdata ){
        pageobj = $.botPagelinkdata[pageid];
        // check templates to see if this is a disambig page
        isdisambig = false;
        if( pageobj.templates ){
            for( template in pageobj.templates ){
                if( $.disambigtemplates.indexOf(
                        pageobj.templates[template].title) !== -1 ){
                    isdisambig = true;
                    break;
                }
            }
        }
        if( isdisambig ){
            // find the link element(s) that match the title
            // if pageobj is target of a redirect, use the redirect
            //    as the link to highlight
            linktitle = $.redirectsToFrom[pageobj.title] ?
                        $.redirectsToFrom[pageobj.title] :
                        pageobj.title;
            urltitle = 'a[href="/wiki/' + $.urlifytitle( linktitle ) + '"]';
            mw.log("Looking for " + urltitle);
            $(urltitle).addClass(linktitle.indexOf("(disambiguation)") === -1 ?
                    "dabpagelink" : "intdablink");
        }
    }
    $('#colorizerStatus')[0].innerHTML = "dabcolorizer: done!";
    $('#colorizerStatus').fadeOut('slow');
};

$.botInitialize = function (){
    // make sure framework has been loaded
    if (! window.Luasog) {
        setTimeout($.botInitialize, 125);
        return;
    }
    // wrapper for Luasog bot request method
    Luasog.prototype.raw_request = Luasog.prototype.request;
    // wraps request with handling of maxlag
    Luasog.prototype.request = function (__luas_args, __luas_callback){
        __luas_args.maxlag = "5";
        var lagpattern = /Waiting for [\d.]+: (\d+) seconds? lagged/;
        var __luas_this = this;
        this.raw_request(__luas_args, function (response_data){
            // callback here once data is received
            var lagmatch, lagtime;
            if( response_data.error ){
                if( response_data.error.code === "maxlag" ){
                    lagmatch = lagpattern.exec(response_data.error.info);
                    lagtime = parseInt(lagmatch[1], 10);
                    // set throttle into the future for lag delay
                    __luas_this.timeoflastrequest = ((new Date()).getTime()
                       + Math.min(Math.max(5000, 500*lagtime), 120000));
                    // repeat request
                    __luas_this.request(__luas_args, __luas_callback);
                } else {
                    Luasog.exception({ name: response_data.error.code,
                                       message: response_data.error.info });
                }
            } else {
                // no error code, go to original callback
                __luas_callback(response_data);
            }
        });
    };

    // initialize the bot
    $.bot = new Luasog(mw.config.get("wgServer")
                       + mw.config.get("wgScriptPath") + "/api.php");
    $.bot.speed = 10;

    // get the list of disambig templates
    $.bot.request(
        {'action':'query', 'prop':'links',
         'titles':'MediaWiki:Disambiguationspage', 'plnamespace':'10',
         'pllimit':'max'},
        function (data){
            var link, pageid, thispage;
            $.disambigtemplates = [];
            for (pageid in data.query.pages) {
                thispage = data.query.pages[pageid];
                for (link in thispage.links) {
                    $.disambigtemplates.push( thispage.links[link].title );
                }
            }
        }
    );

    // get the text of all pages linked from the current page;
    // throttle should ensure that previous request will be completed
    // before this one starts
    $.botParams = {'action':'query', 'generator':'links',
                   'prop':'info|revisions|templates', 'gplnamespace':'0',
                   'gpllimit':'max', 'titles':mw.config.get("wgPageName"),
                   'tllimit':'max', 'redirects':''};
    $.botPagelinkdata = {};
    $.botReady = false;
    $.redirectsFromTo = {};
    $.redirectsToFrom = {};
    $.botCallback = function (linkdata){
        var page,
            pageTemplates,
            savedTemplates,
            ttitle,
            newT,
            oldT,
            knownT,
            pqr,
            qc,
            r;
        if ( ! linkdata.query) {
            mw.log( "Page link query failed!" );
            return;
        }
        for( page in linkdata.query.pages ){
            if( $.botPagelinkdata[page] ){
                // this page already loaded, so see if there are
                // any new templates
                pageTemplates = linkdata.query.pages[page].templates;
                savedTemplates = $.botPagelinkdata[page].templates;
                if (pageTemplates) {
                    for( newT in pageTemplates ){
                        knownT = false;
                        ttitle = pageTemplates[newT].title;
                        if( savedTemplates ){
                            for( oldT in savedTemplates ){
                                if( savedTemplates[oldT].title === ttitle) {
                                    knownT = true;
                                    break;
                                }
                            }
                        }
                        if( ! knownT ){
                            if (savedTemplates) {
                                 savedTemplates.push(pageTemplates[newT]);
                            } else {
                                $.botPagelinkdata[page].templates =
                                         [pageTemplates[newT]];
                                savedTemplates =
                                         $.botPagelinkdata[page].templates;
                            }
                        }
                    }
                }
            } else {
                $.botPagelinkdata[page] = linkdata.query.pages[page];
            }
        }
        pqr = linkdata.query.redirects;
        for( r in pqr ){
            $.redirectsFromTo[ pqr[r].from ] =  pqr[r].to;
            $.redirectsToFrom[ pqr[r].to ] = pqr[r].from;
        }
        qc = linkdata["query-continue"];
        if( qc ){
            if( qc.templates ) {
                $.botParams.tlcontinue = qc.templates.tlcontinue;
                delete $.botParams.gplcontinue;
                $.bot.request( $.botParams, $.botCallback );
            } else if( qc.links ) {
                delete $.botParams.tlcontinue;
                $.botParams.gplcontinue = qc.links.tlcontinue;
                $.bot.request( $.botParams, $.botCallback );
            }
        } else {
            delete $.botParams.tlcontinue;
            delete $.botParams.gplcontinue;
            $.botReady = true;
        }
    };

    $.bot.request( $.botParams, $.botCallback );

}

if ( mw.config.get("wgIsArticle") ){
    $.botInitialize();
    // wait until DOM is ready
    $(function() {
        var newspan = document.createElement('span');
        newspan.id = "colorizerStatus";
        newspan.innerHTML = "dabcolorizer: working";
        $('h1.firstHeading').children().after(newspan);
        $('#colorizerStatus').addClass("editsection");
        $.botStartColorizer();
    });
}