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');	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 {			document.querySelector('div#content.page-content').insertBefore(list, document.querySelector('div#mw-content-text.mw-body-content'));			unusedFiles.getFiles;		},		getFiles: function(continueFrom){			if ((!continueFrom||'string' !== typeof continueFrom) && RUNNING>0) {return;}			RUNNING++;			console.log('start running loop #'+RUNNING);			var params = {				action: 'query',				list: 'allimages',				ailimit: 'max'			};			if (continueFrom && 'string' == typeof continueFrom) {params.aicontinue = continueFrom;}			api.get(params).then(unusedFiles.parseFiles);		},		parseFiles: function(data) {			console.log('pase files:', data);			if (data.error || !data.query || !data.query.allimages || data.query.allimages.length == 0) { 				console.log('used:', used);				console.log('unused:', unused);				return;			}			var params = {				action: 'query',				prop: 'fileusage', fulimit: 1 };			data.query.allimages.forEach(function(page){				params.titles = page.title;				api.get(params).then(function(page_data){ if (page_data && page_data.query && page_data.query.pages && !page_data.query.pages['-1']) { var id = Object.keys(page_data.query.pages)[0]; var link = document.createElement('a'); link.href = '/wiki/'+page_data.query.pages[id].title; link.innerHTML = page_data.query.pages[id].title; var bullet = document.createElement('li'); bullet.append(link); if (!page_data.query.pages[id].fileusage) { list.append(bullet); } }				});			});			if (data.continue && data.continue.aicontinue) { unusedFiles.getFiles(data.continue.aicontinue); } else { document.querySelector('div#content.page-content').insertBefore(document.createTextNode('Done loading'), list); }		}	};	mw.loader.using('mediawiki.api').then(unusedFiles.init); });