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 21:00, 15 April 2011. 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.
// Alpha release; may be buggy

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(/%2C/, ",").
                    replace(/%28/, "(").replace(/%29/, ")");
};

$.startcolorizer = function (){
    var pageid,
            pageobj,
                isdisambig,
                template,
                linktitle,
                urltitle,
                logdata = [];

    if( ! $.botReady ) {
        setTimeout(function (){$.startcolorizer();}, 250);
        return;
    }
        console.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 ){
//            logdata.push( "Checking: ", pageobj.title, " - contains ",
//                          pageobj.templates.length + " templates:\n" );
            for( template in pageobj.templates ){
//                logdata.push("  ", pageobj.templates[template].title);
                if( $.disambigtemplates.indexOf(
                        pageobj.templates[template].title) !== -1 ){
                    isdisambig = true;
//                    logdata.push(" - disambig template\n");
                    break;
                }
                logdata.push("\n");
            }
//            console.log(logdata.join(''));
//            logdata = [];
        }
        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
            if( $.redirectsToFrom[pageobj.title] ){
                linktitle = $.redirectsToFrom[pageobj.title];
            } else {
                linktitle = pageobj.title;
            }
                        urltitle = 'a[href="/wiki/' + $.urlifytitle( linktitle ) + '"]';
                        console.log("Looking for " + urltitle);
                        $(urltitle).addClass(linktitle.indexOf("(disambiguation)") === -1 ?
                                "dabpagelink" : "intdablink");
//            if( linktitle.indexOf( "(disambiguation)" ) === -1 ){
//                $(urltitle).addClass( "dabpagelink" );
//           } else {
//                $(urltitle).addClass( "intdablink" );
//            }
        }
    }
};

if ( mw.config.get("wgIsArticle") ){
    // wait until framework has been loaded
    $('script[src*="bot/framework.js"]').load(function (){

        // 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) {
                alert( "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 );

    });

    // wait until DOM is ready
    $('document').ready($.startcolorizer);

}