User:Majr/fileNuke.js

mw.loader.using( 'mediawiki.api', function {	'use strict';	var api = new mw.Api;	var $galleryList = $( '#gallery-list' );	var deleteFiles = function( files, reason, count ) {		if ( count === undefined ) {			count = 0;		} else if ( $galleryList.length ) {			var $textbox = $galleryList.children( 'textarea' );			$textbox.prop( 'value', function( $, text ) { return text.replace( files[count - 1], '' ).replace( /\n+/g, '\n' ).trim; } );			$textbox[0].scrollTop = $textbox[0].scrollHeight;		}		if ( !files[count] ) {			return;		}		api.get( { action: 'query', list: 'backlinks', blredirect: true, bltitle: files[count] } ).then( function( data ) { var backlinks = data.query.backlinks; if ( backlinks.length > 1 || ( backlinks.length === 1 && backlinks[0].title !== files[count] ) ) { console.info( 'Skipped:', files[count] ); mw.notify( 'Skipped: ' + files[count] ); return; }			return api.postWithToken( 'edit', {				action: 'delete',				title: files[count],				reason: reason			} ).done( function {				console.info( 'Deleted:', files[count] );				mw.notify( 'Deleted: ' + files[count] );			} ); } ).then( function { deleteFiles( files, reason, count + 1 ); }, function( code, data ) { if ( code === 'http' && data.textStatus === 'timeout' ) { // File was probably deleted, try again just in-case deleteFiles( files, reason, count ); } else if ( code === 'missingtitle' ) { // File was probably deleted and timed-out, skip console.info( 'Skip:', files[count] ); mw.notify( 'Skip: ' + files[count] ); deleteFiles( files, reason, count + 1 ); } else { handleError( code, data, files[count] ); }		} );	};	var handleError = function( code, data, file ) {		var title, text;		if ( code === 'http' ) {			if ( data.textStatus === 'error' ) {				text = 'Connection error';			} else {				title = 'HTTP error';				text = data.textStatus;			}		} else {			title = 'API error';			text = data.error.info;		}		console.error( text + ':', file );		mw.notify( [ text + ' ' + file ], { title: title, autoHide: false } );	};

if ( $galleryList.length ) { $galleryList .append( $( ' ' ).addClass( 'mw-ui-button mw-ui-destructive delete' ).text( 'Delete' ) ) .append( $( ' ' ).addClass( 'mw-ui-input reason' ).css( { display: 'block', width: '100%', boxSizing: 'border-box', marginTop: '1px' } ).val( 'Unused file' ) ); $galleryList.find( '.delete' ).click( function {			var reason = $galleryList.find( '.reason' ).val;			deleteFiles( $galleryList.find( 'textarea' ).val.split( '\n' ), reason );		} ); } } );