User:Ricordisamoa/FPwallpaper.js

Note: After saving, you have to bypass your browser's cache to see the changes. Internet Explorer: press Ctrl-F5, Mozilla: hold down Shift while clicking Reload (or press Ctrl-Shift-R), Opera/Konqueror: press F5, Safari: hold down Shift + Alt while clicking Reload, Chrome: hold down Shift while clicking Reload.
if(/bot/i.test(wgUserName)===false) return;
wp_queue=[];
$.ajax({
	url:mw.util.wikiScript("api"),
	data:{
		action:"query",
		format:"json",
		//generator:"categorymembers",
		//gcmtitle:"Category:Featured pictures by Jkadavoor (Jee)",
		generator:"embeddedin",
		geinamespace:6,// only files
		geilimit:300,
		geititle:"Template:Assessments",// with {{Assessments}}
		geifilterredir:"nonredirects",
		prop:"imageinfo|categories",
		clcategories:"Category:Commons featured desktop backgrounds|Category:Commons featured widescreen desktop backgrounds",
		iiprop:"dimensions"
	},
	cache:false,
	dataType:"json"
})
.done(function(data){
	console.log(data);
	$.each(data.query.pages,function(k,v){
		var categories=v.categories?$.map(v.categories,function(e){return e.title;}):[];
		var width=v.imageinfo[0].width;
		var height=v.imageinfo[0].height;
		var code=(width/height===8/5||width/height===16/10||width/height===16/9)?"2":((width/height===4/3||width/height===5/4)?"1":"");
		if(categories.length===0&&code!=""&&width>=1024&&height>=768){
			wp_queue.push({title:v.title,code:code});
		}
		else console.log(v.title+"  can't be set.");
		if(Object.keys(data.query.pages).indexOf(k)===Object.keys(data.query.pages).length-1) queue_process();
	});
});
function queue_process(){
	console.log("--> "+wp_queue.length+" images to process.");
	var i=0;
	var interval=setInterval(function(){
		if(i<wp_queue.length){
			$.get(
				mw.util.wikiScript(),
				{title:wp_queue[i].title,action:"raw"}
			)
			.done(function(text){
				console.groupCollapsed(wp_queue[i].title+"   "+wp_queue[i].code);
				text=text.replace(/(\n\r?)+$/,"");
				var newText=text.replace(/(\{\{[Aa]ssessments\|[A-Za-z]+=[0-9]+)(\}\}|\|)/,"$1"+"|wallpaper="+wp_queue[i].code+"$2");
				console.log(text);
				console.log(newText);
				console.groupEnd();
				if(newText!=text&&text.indexOf("|wallpaper=")===-1){
					$.post(
						mw.util.wikiScript("api"),
						{
							action:"edit",
							text:newText,
							title:wp_queue[i].title,
							summary:'Adding parameter "wallpaper='+wp_queue[i].code+'" to {{[[Template:Assessments|Assessments]]}}',
							minor:true,
							bot:true,
							token:mw.user.tokens.get("editToken")
						}
					)
					.done(function(data){
						if(data&&data.error&&data.error.info){
							console.warn("Error! on  "+wp_queue[i].title+": "+data.error.info);
						}
						else console.log("Good!");
					})
					.fail(function(){
						console.log("FAILED!");
					});
				}
				else console.log("text==newText!");
				i+=1;
			});
		}
		else{
			alert("Task completed.");
			clearInterval(interval);
			return;
		}
	},80000);
}