User:Mikevoir/UnusedFiles.js

(function{	// Double load protection	if (document.querySelector('a#tu-uf')) {return;}	// Dependencies	var api;	var RUNNING = 0;	var used = document.createElement('ul');	var unused = 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.getFiles))    			); });			var list = document.createElement('ul');			document.querySelector('div#content.page-content').insertBefore(list, document.querySelector('div#mw-content-text.mw-body-content'));			var list1 = list.append(document.createElement('li'));			list1.innerHTML = 'Unused files';			list1.append(unused);			var list2 = list.append(document.createElement('li'));			list2.innerHTML = 'Used files';			list2.append(used);		},		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]; if (!page_data.query.pages[id].fileusage) { unused.append($('').append($('').attr({ href: '/wiki/'+page_data.query.pages[id].title }).text(page_data.query.pages[id].title))); } else { used.append($('').append($('').attr({ href: '/wiki/'+page_data.query.pages[id].title }).text(page_data.query.pages[id].title))); }					}				});			});			if (data.continue && data.continue.aicontinue) { unusedFiles.getFiles(data.continue.aicontinue); } else { console.log('used:', used); console.log('unused:', unused); }		}	};	mw.loader.using('mediawiki.api').then(unusedFiles.init); });