Jump to content

User:Jeeputer/addOrRemoveUsersFromJson.js

From Wikipedia, the free encyclopedia
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.
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> Do not remove! prevents wiki-linking

// Originally developed for usage on Persian Wikipedia at [[MediaWiki:Gadget-AddNewUserToJSON.js]]
// Slighlty tweaked for use on English Wikipedia
// Easily adds/removes usernames to/from AWB check page
// useful for admins who are not familiar with JSON syntax

$.when(
	$.ready,
	mw.loader.using(['mediawiki.util', 'mediawiki.api', 'oojs-ui-core', 'oojs-ui-widgets'])
).then(function() {
	"use strict";
	
	var checkPage = 'Wikipedia:AutoWikiBrowser/CheckPageJSON';
	
	// Only administrators on the checkpage
    if (mw.config.get('wgPageName') !== checkPage ||  mw.config.get('wgUserGoups').indexOf('sysop') === -1) {
        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: 'Remove this user',
            flags: 'destructive',
            id: 'remove-user'
        });
        removeButton.setData(this.textContent.replace(/\"/g, ''));  
        $(this).after($('<td>').append(removeButton.$element)); 
    });

    var fieldset = new OO.ui.FieldsetLayout({
        label: 'Add a new allowed user to this list',
        id: 'add-new-user-fieldset'
    });

    var userInput = new OO.ui.TextInputWidget({
        placeholder: 'Without "User:" prefix'
    });

    fieldset.addItems([
        new OO.ui.MessageWidget({
            inline: true,
        	label: new OO.ui.HtmlSnippet(
        		'<strong>Type the user\'s name without "User:" prefix in the box below and then click on the blue "Add" button.</strong><br/>' +
        		'To remove a user from the list, click on ' +
        		'<img src="/media/wikipedia/commons/d/d1/OOjs_UI_icon_block-destructive.svg"></span>' +
        		' icon next to their name.'
    		)
        }),
        new OO.ui.ActionFieldLayout(userInput, new OO.ui.ButtonWidget({
            label: 'Add',
            flags: [
                'primary',
                'progressive'
            ],
            id: 'add-new-user-button'
        }), {
            align: 'top'
        })
    ]);
    
    $('span#remove-user').on('click', function () {
        var user = this.textContent;
        OO.ui.confirm('Remove "' + user + '" from the list?').done(function (confirmed) {
        	if (confirmed) {
        		removeUser(user);
			} else {
				return;
			}
        });
    });
    
    $("#siteSub").append(fieldset.$element);
    $("#add-new-user-fieldset").css("margin-bottom", "0.5em");				// margin, so it doesn't stick to other possibly activated gadgets or scripts
    $('#add-new-user-button').on('click', function() {						// gadgets which appear at the bottom of page title
        addNewUser(userInput.getValue());
    });

    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 (userName) {
        $.getJSON('/w/index.php', {
            action: 'raw',
            ctype: 'application/json',
            title: mw.config.get('wgPageName')
        }).then(function(data) {
            var index = data.enabledusers.indexOf(userName);
            if (index > -1) {
              data.enabledusers.splice(index, 1);
            }
            var sort = function (x) { return x.sort(); };
            return savePage(
                mw.config.get('wgPageName'),
                JSON.stringify({
                    enabledusers: sort(data.enabledusers),
                    enabledbots: data.enabledbots
                }, null, 4),
                'Remove [[Special:Contributions/' + userName + '|' + userName + ']] from the list'
            ).then(function () {
	            mw.notify('Removed "' + userName + '" from the list!', {
                	type: 'success'
        		});
                setTimeout(function() {
                    location.reload();												
                }, 2000);
            });
        });
    }

    function addNewUser(userName) {
        $.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 sort = function (x) { return x.sort(); };
            return savePage(
                mw.config.get('wgPageName'),
                JSON.stringify({
                    enabledusers: sort(data.enabledusers.concat(userName)),
                    enabledbots: data.enabledbots
                }, null, 4),
                'Add [[Special:Contributions/' + userName + '|' + userName + ']] per [[WP:RFP/AWB#User:' + userName + '|request]]'
            );
        }).then(function() {
            mw.notify('Added ' + userName + ' to the list!', {
                type: 'success'
            });
            setTimeout(function() {
                location.reload();
            }, 2000);
        });
    }
});
//</nowiki>