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 = 0;		}		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; }			var deleteReq = api.postWithToken( 'edit', {				action: 'delete',				title: files[count],				reason: reason			} ); return deleteReq.then( null, function( code, data ) {				// File was probably deleted, check if it's now missing				if ( code === 'http' && data.textStatus === 'timeout' ) {					return api.get( { action: 'query', titles: files[count], formatversion: 2 } ).then( function( data ) { if ( !data.query.pages[0].missing ) { // Still there... return original error return deleteReq; }					} );				}				return this;			} ).done( function {				console.info( 'Deleted:', files[count] );				mw.notify( 'Deleted: ' + files[count] );			} ); } ).then( function { deleteFiles( files, reason, count + 1 ); }, function( code, data ) { 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 );		} ); } } );