Jump to content

User:Technical 13/SandBox/getPageViews.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.
// Licensed under the MIT license; theopolismewiki@gmail.com
( function ( $, mw ) {
	function sum ( obj ) {
		var total;
		for (var prop in obj ) {
			if ( obj.hasOwnProperty( prop ) ) {
				total += parseInt( obj[prop], 10 );
			}
		}
		return total;
	}
	function getPageData( pagename, language ) {
		var deferred = $.Deferred(),
		request3 = $.getJSON( 'http://stats.grok.se/json/' + language + '/latest30/' + pagename ),
		request6 = $.getJSON( 'http://stats.grok.se/json/' + language + '/latest60/' + pagename ),
		request9 = $.getJSON( 'http://stats.grok.se/json/' + language + '/latest90/' + pagename );
		$.when( request3, request6, request9 ).done( function ( data3, data6, data9 ) {
			deferred.resolve( {
				title: data3.title,
				rank: data3.rank,
				hits30: sum( data3.daily_views ),
				hits60: sum( data6.daily_views ),
				hits90: sum( data9.daily_views )
			} );
		} );
		return deferred;
	}
	function getPagesTable( pages, language ) {
		var table = $( '<div>' ), requests = [];
		$.each( pages, function ( i, page ) {
			requests.push( getPageData( page, language ) );
		} );
		$.when.apply( $, requests ).done( function () {
			$.each( requests, function ( i, request ) {
				request.done( function ( data ) {
				table.append( $( '<div>' ).text( JSON.stringify( data ) ) );
				} );
			} );
		} );
	}
	var pages = prompt( 'Enter page names, separated by pipes', mw.config.get( 'wgTitle' ) ).split( '|' ),
	language = mw.config.get( 'wgPageContentLanguage' );
	$( '#mw-content-text' ).prepend( getPagesTable( pages, language ) );
} )( jQuery, mediaWiki );