Jump to content

User:Enterprisey/mark-join-date.js

From Wikipedia, the free encyclopedia
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.
$( function() {
    if( mw.config.get( "wgPageName" ).indexOf( "Wikipedia:Sockpuppet_investigations/" ) >= 0 ) {

        mw.loader.using( [ 'mediawiki.api' ] ).then( function () {

        var allLinks = Array.from( document.querySelectorAll( "a[href^='https://en.wikipedia.org/wiki/User:'].external" ) );
        var CHUNK_SIZE = 10;
        for( var i = 0; i < allLinks.length; i += CHUNK_SIZE ) {
            fetchAndDisplayDates( allLinks.slice( i, i + CHUNK_SIZE ) );
        }

        // Make an API call to fetch all registration dates for users in this chunk
        function fetchAndDisplayDates( links ) {

            // Make the "ususers" parameter for the query;
            // must be pipe-separated URL-encoded usernames
            var users = links.map( function ( link ) {
                    return usernameFromUrl( link.href ); } );
            var usersParam = users.map( encodeURIComponent ).join( "|" );

            // Perform query
            ( new mw.Api() ).get( {
                "list": "users",
                "ususers": usersParam,
                "usprop": "registration"
            } ).done( function ( res ) {
                if( res && res.query && res.query.users ) {

                    // `identicalLinks` is necessary because `users` might have duplicates
                    var dateSpan, dateText, identicalLinks;
                    for( var j = 0; j < res.query.users.length; j++ ) {
                        currUser = res.query.users[j].name;
                        try { dateText = res.query.users[j].registration.replace( /T.*/, "" ); } catch (e) { continue; }

                        identicalLinks = links.filter( function ( link ) { return usernameFromUrl( link.href ) === currUser; } );
                        
                        for( var k = 0; k < identicalLinks.length; k++ ) {
                            dateSpan = document.createElement( "span" );
                            dateSpan.style.fontSize = "80%";
                            dateSpan.style.paddingLeft = "0.2em";
                            dateSpan.textContent = dateText;
                            identicalLinks[k].parentNode.insertBefore( dateSpan, identicalLinks[k].nextSibling );
                        }
                    }
                } else {
                    console.log( "bad data", res );
                }
            } );
        }

        } ); // end mw.loader.using callback

        // Turns "//en.wikipedia.org/wiki/User:Example" into "Example"
        function usernameFromUrl( url ) { return url.substr( 35 ); }
    }
} );