User:Kwwxis/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' });	var knownHasUsage = {};	// 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(lastContinue) {			RUNNING++;			var params = {				action: 'query',				generator: 'allimages',				prop: 'fileusage',				fulimit: 500			};			if (!!lastContinue) {				Object.assign(params, lastContinue);			}			api.get(params).then(function(data){ console.log('getFiles 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.textContent = '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 item = data.query.pages[ID]; var bulletId = 'unusedFile-ns-' + item.ns + '-pageid-' + item.pageid; console.log('Item', item); var isUsed = knownHasUsage[bulletId] || (Array.isArray(item.fileusage) && item.fileusage.length > 0); if (ID === 1) { return; }				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/' + data.query.pages[ID].title; link.innerHTML = data.query.pages[ID].title; var bullet = document.createElement('li'); bullet.id = bulletId; bullet.append(link); list.append(bullet); }			});		}	};	mw.loader.using('mediawiki.api').then(unusedFiles.init); });