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++;			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) {			if (data.error || !data.query || !data.query.allimages || data.query.allimages.length == 0) {				console.log('early stop, something went wrong:', data);				document.querySelector('div#content.page-content').insertBefore(document.createTextNode('Early stop, either there\'s no unused files or something went wrong.'), 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){ console.log('_files', _files); if (_files && _files.query && _files.query.pages) { var filtered_files = Object.keys(_files.query.pages).reduce(function(newA, id){ if(!_files.query.pages[id].fileusage) {newA.push(_files.query.pages[id].title);} return newA; }, []); console.log('filtered_files:', filtered_files); filtered_files.forEach(function(file){							var link = document.createElement('a');							link.href = '/wiki/' + file;							link.innerHTML = file;							var bullet = document.createElement('li');							bullet.append(link);							list.append(bullet);						}); }				});			}		}	};	mw.loader.using('mediawiki.api').then(unusedFiles.init); });