MediaWiki:UploadHelper-fa.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.
// <nowiki> // DO NOT REMOVE THIS LINE EVER
// A tool to help uploading images from Persian Wikipedia
// Author: User:Ebrahim
$(function () {
	'use strict';
	
	var localName = mw.util.getParamValue('wpDestFile');
	$('#mw-htmlform-source').replaceWith($('<div>', {
		text: 'Persian Wikipedia',
		id: 'uploadhelper-image',
		style: 'font-size: large'
	}).prepend($('<img>', { src: '//fa.wikipedia.org/w/thumb.php?f=' + localName + '&w=200' }), ' '));
	$('#uploadtext').hide();
	
	var mediaLocation;
	setTimeout(function () {
		$('#hotcatLabelTranslated').parent().hide();
		$('#wpUploadPreview, .mw-htmlform-field-Licenses').hide(); // until we figure how to deal with them
	}, 2000);
	$('#wpUploadDescription').css({ height: 400, width: 700 });
	$('#wpDestFile').val(localName);
	
	$('[name=wpUpload]').click(function (e) {
		e.preventDefault();
		$(this).prop('disabled', 'disabled');
		mw.notify('Please wait...', { autoHide: false });
		getBlob(mediaLocation).then(function (blob) {
			var formData = new FormData();
			formData.append('action', 'upload');
			formData.append('filename', $('#wpDestFile').val());
			formData.append('token', mw.user.tokens.get('csrfToken'));
			formData.append('format', 'json');
			formData.append('text', $('#wpUploadDescription').val());
			formData.append('comment', 'Uploaded ' + localName + ' from Persian Wikipedia');
			formData.append('watchlist', $('#wpWatchthis').prop('checked') ? 'watch' : 'nochange');
			formData.append('ignorewarnings', $('#wpIgnoreWarning').prop('checked') ? '1' : '0');
			formData.append('file', blob);
			return $.ajax({
				url: mw.util.wikiScript('api'),
				contentType: false,
				processData: false,
				type: 'POST',
				data: formData
			});
		}).then(function () {
			if (isLocalAdmin) {
				return deleteLocalFile(localName, 'Now available on Wikimedia Commons: [[File:' + $('#wpDestFile').val() + ']]');
			}
		}).then(function () {
			location.href = mw.util.getUrl('File:' + $('#wpDestFile').val());
		}, function (data) {
			mw.notify(data.error);
		});
	}).prop('disabled', 'disabled'); // disabled till we get mediaLocation
	
	$.when(loadPageFa(localName), getMediaInfo(localName)).then(function (text, info) {
		mediaLocation = info[0].url;
		$('#mw-htmlform-description').parent().after($('<textarea>', {
			disabled: 'disabled',
			dir: 'RTL',
			style: 'width: 600px; height: 400px;'
		}).val(text));
		
		var licenses = {
			'PD-user-w': 'مالکیت عمومی-خود',
			'Cc-by-sa-3.0': 'کک-یاد-سه',
			'Cc-by-sa-2.0': 'کک-یاد-۲',
			'Cc-by-3.0': 'Cc-by-3.0',
			'Cc-by-2.0': 'Cc-by-2.0',
			'GFDL-user-w': '(مجوز گنو|گنو-خود)',
			'PD-Iran': 'نگاره قدیمی',
			'PD-old': 'نگاره قدیمی',
			'PD-Afghanistan': 'مالکیت_عمومی-افغانستان',
			'PD-AR-Photo': 'مالکیت_عمومی-آرژانتین',
			'PD-author': 'عدم_حفظ_حق_تکثیر',
			//'PD-because': 'PD',
			'PD-Egypt': 'مالکیت_عمومی-مصر',
			'PD-Iraq': 'مالکیت_عمومی-عراق',
			'PD-Italy': 'مالکیت_عمومی-ایتالیا',
			'PD-Pakistan': 'مالکیت_عمومی-پاکستان',
			'PD-UK': 'مالکیت_عمومی-بریتانیا',
			'PD': 'مالکیت عمومی'
		};
		var license = [];
		var oldestUploadInfo = info[info.length - 1];
		var user = ((oldestUploadInfo.user || '').match(/\[\[.+?:([^\]\|]+)/) || {})[1] || oldestUploadInfo.user;
		text = text.replace(/PD-Self/i, 'PD-user-w');
		text = text.replace('مالکیت عمومی-خود', 'PD-user-w');
		Object.keys(licenses).forEach(function (x) {
			if (x === 'PD' && license.length !== 0) {
				// the license is already detected
				return;
			}
			if (text.match(new RegExp(licenses[x].replace(' ', '[ _]'), 'i')) || text.match(new RegExp(x.replace(' ', '[ _]'), 'i'))) {
				if (['PD-user-w', 'Cc-by-sa-3.0', 'Cc-by-sa-2.0', 'Cc-by-3.0', 'Cc-by-2.0', 'GFDL-user-w'].indexOf(x) !== -1) {
					license.push('{{' + x + '|fa|Persian Wikipedia|' + user + '}}');
				} else {
					license.push('{{' + x + '}}');
				}
			}
		});
		if (license.length === 0) {
			license.push(text.replace('{{انتقال به انبار}}', '').replace('{{انتقال به ویکی\u200cانبار}}', '').replace('الگو:', '').match(/\{\{.*\}\}/)[0] || '');
		}
		var parsedPage = {};
		(text.match(/\| *([^\s]+) *= *([^\n\}]*)/g) || []).forEach(function (x) {
			var parts = x.match(/\| *([^\s]+) *= *([^\n\}]*)/);
			parsedPage[parts[1]] = parts[2];
		});
		if ((parsedPage['پدیدآور'] || '').indexOf('کاربر:' + user) !== -1) {
			parsedPage['پدیدآور'] = '';
		}
		
		$('#wpUploadDescription').val([
			'== {{int:filedesc}} ==',
			'{{Information',
			'|Description={{fa|1=' + (parsedPage['توضیحات'] || text.split('\n')[0]) + '}}',
			'|Source={{transferred from|fa.wikipedia|}}' +
				((parsedPage['منبع'] || '').replace(/خودم|بارگذار|اثر شخصی/, '') ? '{{fa|1=' + parsedPage['منبع'].replace(/خودم|بارگذار/, 'Self') + '}}' : ''),
			'|Date={{Original upload date|' + new Date(oldestUploadInfo.timestamp).toDateString() + '}}' +
				((parsedPage['تاریخ'] || '') ? '{{fa|1=' + parsedPage['تاریخ'] + '}}' : ''),
			'|Author={{User at project|' + user + '|wikipedia|fa}}' +
				((parsedPage['پدیدآور'] || '').replace(/خودم|بارگذار/, '') ? '{{fa|1=' + parsedPage['پدیدآور'] + '}}' : ''),
			'|Permission=',
			'|other_versions=',
			'}}',
			'',
			'== {{int:license-header}} ==',
			license.join('\n'),
			'',
			'== {{Original upload log}} ==',
			'{{original description|fa.wikipedia|' + localName.replace('File:', '').replace(/ /g, '_') + '}}',
			'{| class="wikitable"',
			'! {{int:filehist-datetime}} !! {{int:filehist-dimensions}} !! {{int:filehist-user}} !! {{int:filehist-comment}}',
			'|-\n| ' + info.map(function (x) {
				return new Date(x.timestamp).toDateString() + ' || ' + x.height + '×' + x.width +
					'× (' + x.size + ' bytes) || [[:fa:User:' + x.user + '|' + x.user +
					"]] || ''<nowiki>" + x.comment.replace(/\s+/g, ' ') + "</nowiki>''";
			}).join('|-\n| '),
			'|}'
		].join('\n'));

		$('[name=wpUpload]').prop('disabled', '');
	});
	
	function getMediaInfo(name) {
		return new mw.Api({ ajax: { url: '//fa.wikipedia.org/w/api.php' } }).get({
			action: 'query',
			titles: 'File:' + name,
			prop: 'imageinfo',
			iiprop: 'timestamp|user|comment|size|url',
			iilimit: 'max',
			format: 'json',
			origin: location.protocol + '//' + location.hostname
		}).then(function (x) {
			return x.query.pages[Object.keys(x.query.pages)[0]].imageinfo;
		});
	}
	
	function loadPageFa(title) {
		return new mw.Api({ ajax: { url: '//fa.wikipedia.org/w/api.php' } }).get({
			action: 'query',
			prop: 'revisions',
			titles: 'File:' + title,
			rvprop: 'content',
			format: 'json',
			origin: location.protocol + '//' + location.hostname
		}).then(function (data) {
			return data.query.pages[Object.keys(data.query.pages)[0]].revisions[0]['*'];
		});
	}
	
	var localToken;
	var isLocalAdmin;
	function fillLocalTokenAndAdmin() {
		return $.ajax({
			url: '//fa.wikipedia.org/w/api.php',
			data: {
				action: 'query',
				meta: 'tokens|userinfo',
				format: 'json',
				uiprop: 'rights',
				origin: location.protocol + '//' + location.hostname
			},
			xhrFields: { withCredentials: true }
		}).then(function (data) {
			localToken = data.query.tokens.csrftoken;
			isLocalAdmin = data.query.userinfo.rights.indexOf('delete') !== -1;
		});
	}
	fillLocalTokenAndAdmin();
	
	function deleteLocalFile(name, reason) {
		return $.ajax({
			url: '//fa.wikipedia.org/w/api.php',
			data: {
				action: 'delete',
				title: 'File:' + name,
				reason: reason,
				format: 'json',
				token: localToken,
				origin: location.protocol + '//' + location.hostname
			},
			type: 'POST',
			xhrFields: { withCredentials: true }
		});
	}
	
	function getBlob(url) {
		var defer = $.Deferred();
		// http://stackoverflow.com/a/17682424
		var xhr = new XMLHttpRequest();
		xhr.onreadystatechange = function () {
		    if (this.readyState == 4 && this.status == 200) {
		        defer.resolve(this.response);
		    }
		};
		xhr.open('GET', url);
		xhr.responseType = 'blob';
		xhr.send();
		return defer;
	}
});