User:Candalua/common.js

From Wikimedia Commons, the free media repository
Jump to navigation Jump to search
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.
$(document).ready(function() {
	function forceDownload(url, fileName){
		// fileName = url.substring(url.lastIndexOf('/')+1, url.length);
	    var xhr = new XMLHttpRequest();
	    xhr.open("GET", url, true);
	    xhr.responseType = "blob";
	    xhr.onload = function() {
	        var urlCreator = window.URL || window.webkitURL;
	        var imageUrl = urlCreator.createObjectURL(this.response);
	        var tag = document.createElement('a');
	        tag.href = imageUrl;
	        tag.download = fileName;
	        document.body.appendChild(tag);
	        tag.click();
	        document.body.removeChild(tag);
	    };
	    xhr.send();
	}
	
	if (mw.config.get('wgPageName') == "Special:Contributions") {
		$('.mw-contributions-title').each(function() { 
			title = $(this).attr('title');
			if (title.indexOf('File:') === 0) {
				$.ajax({
					url: '/w/api.php?action=query&format=json&prop=imageinfo&iiprop=url&titles=' + title,
				}).done(function(response) {
					for (var key in response.query.pages) {
						if (response.query.pages.hasOwnProperty(key)) {
							value = response.query.pages[key];
							imageurl = value.imageinfo[0].url;
							filetitle = value.title;
							imagetitle = filetitle.replace('File:', '').replace(/ /g, '_');
							//console.log(imageurl);
							//console.log(imagetitle);
							$('.mw-contributions-title[title="' + filetitle + '"]').before(
								$('<a href="#">Scarica </a>').data('url', imageurl).data('title', imagetitle).click(function(e) {
									e.preventDefault();
									forceDownload($(this).data('url'), $(this).data('title'));
								})
							);
						}
					}
				});
			}
		});
	}
	
	if (mw.config.get('wgPageName').indexOf("Special:ListFiles") === 0) {
		$('.TablePager_col_img_name a:first-child').each(function() {
			filename = $(this).attr('title').replace('File:', '');
			$(this).parent().append(' <a target="_new" href="/w/index.php?title=Special:Upload&wpForReUpload=1&wpDestFile=' + filename + '">Upload</a>');
		});
	}
	
	if (mw.config.get('wgPageName') == "Special:Upload") {
		searchParams = new URLSearchParams(window.location.search);
		if (searchParams.get('wpForReUpload') == '1')
			$('#wpUploadDescription').val('sbiancato');
	}
});