مدیاویکی:Gadget-AddNewUserToJSON.js

از ویکی‌پدیا، دانشنامهٔ آزاد

نکته: برای دیدن تغییرات، ممکن است نیاز باشد که حافظهٔ نهانی مرورگر خود را پس از انتشار پاک‌سازی کنید. گوگل کروم، فایرفاکس، مایکروسافت اج و سافاری: کلید Shift را نگه دارید و روی دکمهٔ Reload در نوار ابزار مرورگر کلیک کنید. برای آگاهی از جزئیات و نحوهٔ پاک‌سازی حافظهٔ نهانی سایر مرورگرها، صفحهٔ ویکی‌پدیا:میانگیر مرورگرتان را خالی کنید را ببینید.

// <nowiki> to prevent wiki-linking

// Easily adds/removes usernames to/from AWB and tofawiki-alot check pages
// useful for admins who are not familiar with JSON syntax

// TODO: notify users when removing their name; needs a notice template

$.when(
	$.ready,
	mw.loader.using(['mediawiki.util', 'mediawiki.api', 'oojs-ui-core', 'oojs-ui-widgets'])
).then(function() {
	"use strict";
	
	var checkPages = {
		'ویکی‌پدیا:AutoWikiBrowser/CheckPageJSON': 'وپ:وخد',
		'ویکی‌پدیا:درخواست_برای_دسترسی/به‌ویکی‌فا_انبوه/فهرست_سفید': 'وپ:دبد/بوا'
	};

    var thisCheckPage = checkPages[mw.config.get('wgPageName')];
	
    if (typeof(thisCheckPage) === 'undefined')
        return;
	
    var tableData = $('td.mw-json-value'); // Each table cell containing usernames
    
    // append remove buttons after each table row
    $(tableData).each(function () {
        var removeButton = new OO.ui.ButtonWidget({
        	framed: false,
        	icon: 'block',
        	label: this.textContent.replace(/\"/g, ''),
        	invisibleLabel: true,
        	title: 'حذف از فهرست',
            flags: 'destructive',
            id: 'remove-user'
        });
        removeButton.setData(this.textContent.replace(/\"/g, ''));  
        $(this).after($('<td>').append(removeButton.$element)); 
    });

    var fieldset = new OO.ui.FieldsetLayout({
        label: 'افزودن کاربر جدید به فهرست',
        id: 'add-new-user-fieldset'
    });

    var userInput = new OO.ui.TextInputWidget({
        placeholder: 'بدون پیشوند «کاربر:»'
    });
    
    var botToggle = new OO.ui.ToggleButtonWidget({
		label: 'ربات؟',
		id: 'add-new-user-bot-toggle'
	});
    
    var actionField = new OO.ui.ActionFieldLayout(
        userInput,
        new OO.ui.ButtonWidget({
            label: 'افزودن',
            flags: [
                'primary',
                'progressive'
            ],
            id: 'add-new-user-button'
        }), {
            align: 'top'
    });
        
    var fieldsetLabel = new OO.ui.MessageWidget({
        inline: true,
    });
    
    // Set the text input value if "userName" param is present in page url
    // this param is set when user clicks on the link provided by
    // {{درخواست دسترسی به‌ویکی‌فا انبوه}} to get to the whitelist.
    // also set the fieldset label depending on that param
    var hasURIParam = window.location.href.indexOf('?userName=') != -1 || window.location.href.indexOf('&userName=') != -1;
    var fieldsetLabelValue;
    if (hasURIParam) {
        fieldsetLabelValue = 'ابتدا نام کاربری که به‌طور خودکار در جعبهٔ زیر وارد شده را بررسی کنید';
        var userName = new URLSearchParams(window.location.search).get('userName');
        userInput.setValue(userName);
    } else {
        fieldsetLabelValue = 'نام کاربر را بدون پیشوند «کاربر:» در جعبهٔ زیر وارد کنید';
    }
    fieldsetLabel.setLabel(
        new OO.ui.HtmlSnippet(
            '<strong>' + fieldsetLabelValue + ' و روی دکمهٔ  «افزودن» کلیک کنید.</strong><br/>' +
            'برای حذف نام کاربر از فهرست، روی دکمهٔ ' +
            '<img src="//upload.wikimedia.org/wikipedia/commons/d/d1/OOjs_UI_icon_block-destructive.svg"/>' +
            ' در کنار نام او کلیک کنید.'
        )
    );

    fieldset.addItems([
        fieldsetLabel,
        actionField,
        new OO.ui.FieldLayout(
            botToggle, {
                align: 'inline'
            }
        )
    ]);
    
    $('span#remove-user').on('click', function () {
        var user = this.textContent;
        OO.ui.prompt('برای افزودن به خلاصه ویرایش پیش‌فرض', {
            textInput: { placeholder: 'خلاصه ویرایش سفارشی' },
            title: 'خلاصه ویرایش'
        }).done(function (result) {
            OO.ui.confirm('از حذف نام «' + user + '» از فهرست مطمئن هستید؟').done(function (confirmed) {
            if (confirmed) {
                var customSummary;
                if (result !== null) {
                    customSummary = '؛ (' +  result + ')';
                } else {
                    customSummary = '';
                }
                removeUser(user, customSummary);
            } else {
                mw.notify('عمل لغو شد!', {
                	type: 'warn'
        		});
                return;
            }
        });
        });
    });
    
    $("#bodyContent").prepend(fieldset.$element);
    $("#add-new-user-fieldset").css("margin-bottom", "0.5em");
    // margin, so it doesn't stick to other possibly activated
    // gadgets or scripts which appear at the bottom of page title
    $('#add-new-user-button').on('click', function() {
        addNewUser(userInput.getValue(), thisCheckPage);
    });

    function savePage(title, text, summary) {
        return new mw.Api().post({
            action: 'edit',
            title: title,
            text: text,
            summary: summary,
            nocreate: '',
            minor: true,
            token: mw.user.tokens.get('csrfToken')
        });
    }

    function removeUser (user, customSummary) {
        $.getJSON('/w/index.php', {
            action: 'raw',
            ctype: 'application/json',
            title: mw.config.get('wgPageName')
        }).then(function(data) {
            var index = data.enabledusers.indexOf(user);
            var botIndex = data.enabledbots.indexOf(user);
            if (index > -1) {
				data.enabledusers.splice(index, 1);	
            } else if (botIndex > -1) {
				data.enabledbots.splice(botIndex, 1);
            }
            var persianSort = (window.persianTools || {}).persianSort || function (x) { return x.sort(); };
            return savePage(
                mw.config.get('wgPageName'),
                JSON.stringify({
                    enabledusers: persianSort(data.enabledusers),
                    enabledbots: persianSort(data.enabledbots)
                }, null, 4),
                'حذف نام [[ویژه:مشارکت‌ها/' + user + '|' + user + ']] از فهرست' + customSummary
            ).then(function () {
	            mw.notify('نام کاربر «' + user + '» از فهرست حذف شد.', {
                	type: 'success'
        		});
                setTimeout(function() {
                    location.reload();												
                }, 2000);
            });
        });
    }

    function addNewUser(userName, reqPage) {
		var isBot = botToggle.getValue(),
    		userType = isBot ? 'ربات' : 'کاربر';
        $.getJSON('/w/index.php', {
            action: 'raw',
            ctype: 'application/json',
            title: mw.config.get('wgPageName')
        }).then(function(data) {
        	// Sort alphabetically with Persian names at the bottom (Persian ک problem is fixed)
			var persianSort = (window.persianTools || {}).persianSort || function (x) { return x.sort(); };
			if (isBot) {
	            return savePage(
	                mw.config.get('wgPageName'),
	                JSON.stringify({
	                    enabledusers: data.enabledusers,
	                    enabledbots: persianSort(data.enabledbots.concat(userName))
	                }, null, 4),
	                'افزودن نام [[کاربر:' + userName + '|' + userName + ']] ([[ویژه:مشارکت‌ها/' + userName + '|مشارکت‌ها]]) به فهرست ربات‌ها پیرو [[' + reqPage + '#' + userName + '|درخواست]]'
	            );
			} else {
	            return savePage(
	                mw.config.get('wgPageName'),
	                JSON.stringify({
	                    enabledusers: persianSort(data.enabledusers.concat(userName)),
	                    enabledbots: data.enabledbots
	                }, null, 4),
	                'افزودن نام [[کاربر:' + userName + '|' + userName + ']] ([[ویژه:مشارکت‌ها/' + userName + '|مشارکت‌ها]]) به فهرست کاربران پیرو [[' + reqPage + '#' + userName + '|درخواست]]'
	            );
			}
        }).then(function() {
            mw.notify('نام ' + userType + ' «' + userName + '» به فهرست افزوده شد.', {
                type: 'success'
            });
            setTimeout(function() {
            	// Delay, so user can read the notification
                location.reload();
            }, 2000);
        });
    }
});
//</nowiki>