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 {			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',				list: 'allimages',				ailimit: 'max'			};			if (continueFrom !== undefined && continueFrom !== null) {params.aicontinue = continueFrom;}			api.get(params)			.then(function(data){ // console.log('then', data); unusedFiles.parseFiles(data); throw (data.continue ? data.continue.aicontinue : null); })			.catch(function (e){ console.log(e); if (e !== null) {label.textContent = 'Loading from: '+e+' ...'; unusedFiles.getFiles(e);} else {label.textContent = 'Done loading!';} });		},		parseFiles: function(data) {			if (data.error || !data.query || !data.query.allimages || data.query.allimages.length == 0) {				console.log('early stop, something went wrong:', data);				label = 'Early stop, either there\'s no unused files or something went wrong.';				return;			}			var files = [];			data.query.allimages.forEach(function(file){ files.push(file.title); });			// console.log('file list:', files);			// Break in 50s as that's the base limit of api			for (var i = 0; i < files.length; i += 49) {				api.get({ action: 'query', prop: 'fileusage', titles: files.slice(i, i + 49), funamespace: '*', fulimit: 1, fuprop: 'title' }).then(function(_files){ if (_files && _files.query && _files.query.pages) { Object.keys(_files.query.pages).forEach(function(ID){							var file = _files.query.pages[ID];							if (ID !== -1 && file.fileusage == null) {								var link = document.createElement('a');								link.href = '/wiki/' + file.title;								link.innerHTML = file.title;								var bullet = document.createElement('li');								bullet.append(link);								list.append(bullet);							} 						}); }				});			}		}	};	mw.loader.using('mediawiki.api').then(unusedFiles.init); });