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(function(data){ console.log('then', data); unusedFiles.parseFiles(data); if (data.continue && data.continue.aicontinue) {unusedFiles.getFiles(data.continue.aicontinue);} else {document.querySelector('div#content.page-content').insertBefore(document.createTextNode('Done loading'), list);} });		},		parseFiles: function(data) {			console.log('pase files:', data);			if (data.error || !data.query || !data.query.allimages || data.query.allimages.length == 0) {				console.log('early stop:', data);				document.querySelector('div#content.page-content').insertBefore(document.createTextNode('Done loading'), list);				return;			}			var files = [];			data.query.allimages.forEach(function(file){ files.push(file.title); });			// Break in 50s as that's the base limit of api			for (var i = 0; i < files.length; i += 49) {			   var chunk = files.slice(i, i + 49);				api.get({ action: 'query', prop: 'fileusage', fulimit: 1, titles: chunk }).then(function(_files){ if (_files && _files.query && _files.query.pages) { var filtered_files = _files.query.pages.reduce(function(a, o){ if(o.fileusage) {return a.push(o.title);} else {return a;} }, []); console.log(filtered_files); filtered_files.forEach(function(file){							var link = document.createElement('a');							link.href = '/wiki/' + _files.query.pages[a].title;							link.innerHTML = _files.query.pages[a].title;							var bullet = document.createElement('li');							bullet.append(link);							list.append(bullet);						}); }				});			}		}	};	mw.loader.using('mediawiki.api').then(unusedFiles.init); });