Jump to content

User:Ingenuity/AddToBadImageList.js

From Wikipedia, the free encyclopedia
Note: After saving, you have to bypass your browser's cache to see the changes. Google Chrome, Firefox, Microsoft Edge and Safari: Hold down the ⇧ Shift key and click the Reload toolbar button. For details and instructions about other browsers, see Wikipedia:Bypass your cache.
// <nowiki>

(function() {
	async function addToBadImageList() {
		const api = new mw.Api();
		const bilContent = await api.get({
			action: "query",
			prop: "revisions",
			rvprop: "content",
			titles: "MediaWiki:Bad image list",
			formatversion: "2",
			format: "json"
		});
		const bilPage = bilContent.query.pages[0].revisions[0].content;
		const bilLines = bilPage.split("\n");
		const bilImages = bilLines
			.filter(line => line.startsWith("*"))
			.map(line => [ line, line.match(/\[\[:File:([^\]]+?)\]\]/) ])
			.filter(line => line[1] !== null);
		
		const image = prompt("Enter image name (without File: prefix):");
		
		bilImages.push([ `* [[:File:${image}]]`, [ null, image ] ]);
		bilImages.sort((a, b) => a[1][1].replace(/\./g, "\t").localeCompare(b[1][1].replace(/\./g, "\t")));
		const newImages = bilImages
			.map(line => line[0])
			.join("\n");
		
		const newPage = bilLines
			.filter(line => !line.startsWith("*"))
			.join("\n")
			.concat("\n" + newImages);

		await api.post({
			action: "edit",
			title: "MediaWiki:Bad image list",
			text: newPage,
			summary: "Adding image (via script)",
			token: mw.user.tokens.get("csrfToken")
		});

		location.reload();
	}
	
	mw.util.addPortletLink("p-tb", "#", "Add to BIL", "ca-bil", null, null, "#ca-bil"); 
	document.querySelector("#ca-bil").addEventListener("click", addToBadImageList);
})();

// </nowiki>