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...');	var knownHasUsage = {};	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',				fulimit: 'max'			};			if (!!continueFrom) {Object.assign(params, continueFrom);}			api.get(params)			.then(function(data){ // console.log('then', data); unusedFiles.parseFiles(data); if (data.continue) { // continueName - get value by the key that isn't just "continue" - could be "fucontinue", "aicontinue", "gaicontinue" var continueName = data.continue[Object.keys(data.continue).filter(function(k) {						return k !== 'continue';					})[0]]; label.textContent = 'Loading from: \d+$/, '') + ' ...'; unusedFiles.getFiles(data.continue); } 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){ if (ID === 1) { return; }				var item = data.query.pages[ID]; var bulletId = 'unusedFile-ns-' + item.ns + '-pageid-' + item.pageid; var isUsed = knownHasUsage[bulletId] || (Array.isArray(item.fileusage) && item.fileusage.length > 0); var existingBullet = document.getElementById(bulletId); if (isUsed) { knownHasUsage[bulletId] = true; if (existingBullet) { existingBullet.remove; }				} else { if (existingBullet) { return; }					var link = document.createElement('a'); link.href = '/wiki/' + item.title; link.innerHTML = item.title; var bullet = document.createElement('li'); bullet.id = bulletId; bullet.append(link); list.append(bullet); }			});		}	};	mw.loader.using('mediawiki.api').then(unusedFiles.init); });