User:Mikevoir/UnusedFiles.js

(function{	// Double load protection	if (document.querySelector('a#tu-uf')) {return;}	// Dependencies	var api;	var RUNNING = 0;	var list = document.createElement('ul');	var label = document.createTextNode('Loading...');	importArticle({ type: 'script', article: 'u:dev:MediaWiki:Placement.js' });	// Main object	var unusedFiles = {		init: function {			api = new mw.Api;			mw.hook('dev.placement').add(function(placement) { placement.script('UnusedFiles'); $(placement.element('tools'))[placement.type('prepend')](   			    $('').append($('').attr({ href: '#', id: 't-uf' }).text('Unused Files').click(unusedFiles.loadUI))    			); });		},		loadUI: function(event) {			event.preventDefault;			list.append(label);			document.querySelector('div#content.page-content').insertBefore(list, document.querySelector('div#mw-content-text.mw-body-content'));			unusedFiles.getFiles;		},		getFiles: function(continueFrom){			// console.log('continueFrom:', continueFrom);			RUNNING++;			var params = {				action: 'query',				generator: 'allimages',				prop: 'fileusage'			};			if (continueFrom !== undefined && continueFrom !== null) {params.fucontinue = continueFrom;}			api.get(params)			.then(function(data){ // console.log('then', data); unusedFiles.parseFiles(data); throw (data.continue && data.continue.fucontinue); })			.catch(function (e){ console.log(e); if (e !== undefined && e !== null) {label.textContent = 'Loading from: \d+$/, '') + ' ...'; unusedFiles.getFiles(e);} else {label.textContent = 'Done loading!';} });		},		parseFiles: function(data) {			if (data.error || !data.query || !data.query.pages) {				console.log('early stop, something went wrong:', data);				label = 'Early stop, either there\'s no unused files or something went wrong.';				return;			}			// console.log('data', data);			var files = [];			Object.keys(data.query.pages).forEach(function(ID){ var used = data.query.pages[ID].fileusage; // console.log(data.query.pages[ID].title+':', used); if (ID !== -1 && used == undefined) { var link = document.createElement('a'); link.href = '/wiki/' + data.query.pages[ID].title; link.innerHTML = data.query.pages[ID].title; var bullet = document.createElement('li'); bullet.append(link); list.append(bullet); } 			});		}	};	mw.loader.using('mediawiki.api').then(unusedFiles.init); });