User:NKohli (WMF)/megawatch.js

Source: 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.
/* Watch/unwatch all pages (up to 500) in a category */

// @param n Number of pages to watch/unwatch
// @param act Action: watch or unwatch
function watchPages( n, act ) {
	// Make the ajax request to fetch subpages
	$.ajax( {
			url: mw.util.wikiScript( 'api' ),
			data: {
				action: 'query',
				list: 	'categorymembers',
				format: 'json',
				cmtitle: mw.config.get( 'wgPageName' ),
				formatversion:	2,
				cmprop: 'title',
				cmtype: 'page',
				cmlimit: n
			},
			success: function( data ) {
				subpgs = data.query.categorymembers;
				// Check if we got anything
				if ( !subpgs ) {
					console.log('none found');
				} else {
					result = [];
			 		for( var i = 0; i < subpgs.length; i++) {
			 			result.push( subpgs[i].title );
			 		}

			 		// Post the watch request
			 		if ( act == 'watch' ) {
				 		new mw.Api().postWithToken( 'watch', {
							action: 'watch',
							titles: $.isArray( result ) ? result.join( '|' ) : String( result ),
							formatversion: 2,
							format: 'json'
						} )
						.fail( function ( code, errResponse ) { console.log( errResponse ); } )
						.done( function () { 
							$( '#megawatch' ).addClass( 'watched' );
						} );
					// Or the unwatch request
			 		} else {
			 			new mw.Api().postWithToken( 'watch', {
							action: 'watch',
							titles: $.isArray( result ) ? result.join( '|' ) : String( result ),
							formatversion: 2,
							format: 'json',
							unwatch: 'true'
						} )
						.fail( function ( code, errResponse ) { console.log( errResponse ); } )
						.done( function () { 
							$( '#megawatch' ).removeClass( 'watched' );
						} );
			 		}
				}
			}
		} );
}

$( document ).ready( function() {
	if ( mw.config.get( 'wgCanonicalNamespace' ) == 'Category' ) {
		$( '#p-cactions' ).find( 'ul' ).append(
			"<li><a title=\"Watch all pages in this category\" href=\"#\" id=\"megawatch\">Megawatch</a></li>\n"
		);
		$( '#megawatch' ).click( function() {
			var n = 500;
			if ( $( '#megawatch' ).hasClass( 'watched' ) ) {
				var r = confirm( 'Are you sure you want to unwatch all pages in this category? (Restricted to top 50 pages only)' );
                if ( r == true ) {
				    watchPages( n, 'unwatch' );
				}
			} else {
				var r = confirm( 'Are you sure you want to watch all pages in this category? (Restricted to top 50 pages only)' );
				if ( r == true ) {
				    watchPages( n, 'watch' );
                }
			}
		} );
	}
} );