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 15:56, 28 April 2011 (update). 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.1; 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(/%21/g, "!").
                    replace(/%2C/g, ",").
                    replace(/%28/g, "(").
                    replace(/%29/g, ")");
                    // .replace(/'/, "%27")
};

$.botLog = function (arg) {
    if (typeof console !== "undefined") {
        console.log(arg);
    } else {
        mw.log(arg); // does nothing unless page is loaded in debug mode
    }
};

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

    if (! $.botReady) {
        setTimeout($.botStartColorizer, 125);
        return;
    }
    $.botLog("Starting colorizer.");
    doHighlighting = function( pagetitle ){
        var urltitle = 'a[href="/wiki/' + $.urlifytitle( pagetitle ) + '"]';
        $.botLog("Looking for " + urltitle);
        $(urltitle).addClass(pagetitle.indexOf("(disambiguation)") === -1 ?
                "dabpagelink" : "intdablink");
    };

    for (pageid in $.botPagelinkdata) {
        // skip red links
        if ($.botPagelinkdata.hasOwnProperty(pageid) && pageid > 0) {
            pageobj = $.botPagelinkdata[pageid];
            // check templates to see if this is a disambig page
            isdisambig = false;
            if (pageobj.templates) {
                for (template=0; template < pageobj.templates.length;
                        template++) {
                    if ($.botDabtemplates.indexOf(
                            pageobj.templates[template].title) !== -1 ){
                        isdisambig = true;
                        break;
                    }
                }
                if (isdisambig){
                    // find the link element(s) that match the title
                    doHighlighting(pageobj.title);
                    // if pageobj is target of a redirect, also highlight linnks to
                    //    the redirect
                    if ($.redirectsToFrom[pageobj.title]) {
                        doHighlighting($.redirectsToFrom[pageobj.title]);
                    }
                }
            }
        }
    }
    $('#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;
            $.botDabtemplates = [];
            for (pageid in data.query.pages) {
                if (data.query.pages.hasOwnProperty(pageid)) {
                    thispage = data.query.pages[pageid];
                    for (link in thispage.links) {
                        if (thispage.links.hasOwnProperty(link)) {
                            $.botDabtemplates.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) {
            $.botLog( "Page link query failed!" );
            return;
        }
        for (page in linkdata.query.pages) {
            if (linkdata.query.pages.hasOwnProperty(page)) {
                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=0; newT < pageTemplates.length; newT++) {
                            knownT = false;
                            ttitle = pageTemplates[newT].title;
                            if (savedTemplates) {
                                for (oldT=0; oldT < savedTemplates.length;
                                        oldT++) {
                                    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=0; r < pqr.length; r++) {
            $.redirectsFromTo[ pqr[r].from ] =  pqr[r].to;
            $.redirectsToFrom[ pqr[r].to ] = pqr[r].from;
        }
        qc = linkdata["query-continue"];
        $.botQueryContinue = qc; /* for debugging */
        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 statustext = document.createTextNode('dabcolorizer: working');
        var newspan = document.createElement('span');
        newspan.appendChild(statustext);
        newspan.id = "colorizerStatus";
        $('h1.firstHeading').children(":last").after(newspan);
        $('#colorizerStatus').addClass("editsection");
        $.botStartColorizer();
    });
}