User:MonkeysHK/common.js

/** Staff Tagger * * Code to automate some part of administrator's actions for staff promotion/demotion * * Staff "tag" option appears on Template:User_rights_request * It is commonly used on HSW:STFREQS */

/* jshint esversion: 5, forin: true, immed: true, indent: 4, latedef: true, newcap: true, noarg: true, undef: true, undef: true, unused: true, browser: true, jquery: true, onevar: true, eqeqeq: true, multistr: true, maxerr: 999999, -W082, -W084

/* global mw */ "use strict"; console.log("[User:MonkeysHK/common.js] Test script loading."); $.when(   mw.loader.using(["mediawiki.util", "mediawiki.api"]),    $.Deferred(function(def) { mw.hook("dev.modal").add(function {           def.resolve;        }); }),   $.Deferred(function (def) { if (mw.libs.StaffUtil) { def.resolve(mw.libs.StaffUtil); } else { $.ajax({               cache: true,                dataType: "script",                url: "https://hypixel-skyblock.fandom.com/wiki/MediaWiki:Gadget-StaffColorsUpdater.js"            }).done(function  {                def.resolve(mw.libs.StaffUtil);            }); }   }) ).then(function  {    if (!/codeeditor|sysop|bureaucrat|soap|staff|helper|wiki-manager|content-team-member|util/.test(mw.config.get('wgUserGroups').join('\n')) || (window.StaffTagger && window.StaffTagger.Loaded))        return;

window.StaffTagger = window.StaffTagger || {};

var StaffTagger, that; StaffTagger = that = window.StaffTagger = Object.assign(this, {   	Loaded: true,        api: new mw.Api,        ranksAvailable: [            "bureaucrat",            "administrator",            "codeeditor",            "content-moderator",            "threadmoderator",            "rollback",        ],        rankShorts: {            bureaucrat: "BU",            administrator: "AD",            codeeditor: "CE",            "content-moderator": "CM",            threadmoderator: "DM",            rollback: "RB",        },

luaTableDataModuleToJson: function (moduleName) { return that.api.post({               action: "scribunto-console",                title: mw.config.get("wgPageName"),                question: "=mw.text.jsonEncode(require('" + moduleName + "'))"            }) .then(function(response) { return response.return }) .then(function(data) {               return JSON.parse(data);            }); },

saveToWiki: function (json, summary, page) { var lua = "-- \nreturn " + jsonToLuaTable(json); console.log(lua); api.postWithEditToken({               action: "edit",                text: lua,                title: page,                summary: summary,                minor: true,            }) .then(function {               mw.notify("Refreshing page..", { title: "Save Successful!", type: "info" });                window.location.reload;            }) // Fandom doesn't like catch as a method name ["catch"](errorHandler); },

processInformation: function { var ranklist = $("#StaffTagger-ranks-wrapper *:checked").map(function {               return $(this).attr("data-rank")            }), ranks = ranklist.join("|"), shortranks = ranklist.map(function(r) {                   return rankShorts[r]                }).join("|"); user = $("#StaffTagger-user-input").val;

// #1: Granting rights (Bureaucrat only) that.api.get({               action: 'query',                list: 'users',                ususers: user,                ustoken: 'userrights',            }).always(function (data) {                var usToken = data.query.users[0].userrightstoken;                if (data.query) {                    that.api.post({ "action": "userrights", "format": "json", "user": user, "add": ranks, "expiry": "infinite", "reason": "Per request to be staff: Hypixel_SkyBlock_Wiki_talk:Requests_to_be_staff", "token": usToken, }).always(function (data) { if (data.userrights) console.log('[StaffTagger #1]: Successfully added ranks!'); else console.warn('[StaffTagger #1]: Failed to give ranks: ' + data); });               }                else                    console.warn("[StaffTagger #1]: API error in getting user rights token: " + data, '(API Error code \"' + data + '\")');            });

// #2: Add staff message box to userpage that.api.post({               action: 'edit',                minor: true,                bot: true,                watchlist: 'nochange',                title: 'User:' + user,                summary: 'Adding  message box to userpage',                prependtext: '',                token: mw.user.tokens.values.editToken,            }).always(function (data) {                if (data.edit)                    console.log("[StaffTagger #2]: Successfully tagged", user, 'With rank "' + rank + '"');                else                    console.warn('[StaffTagger #2]: API Error in Tagging', user + ':', data, '(API Error code "' + data + '")');            });

// #3: Protect staff userpage that.api.post({               action: 'protect',                bot: true,                watchlist: 'nochange',                title: 'User:' + user,                protections: (/content-moderator|codeeditor|sysop|bureaucrat/.test(ranks)) ?                    'edit=sysop|move=sysop' :                    'edit=autoconfirmed|move=autoconfirmed',                expiry: 'infinite',                reason: 'Protecting wiki staff userpage',                token: mw.user.tokens.values.editToken,            }).always(function (data) {                if (data.protect)                    console.log("[StaffTagger #3]: Successfully protected ", user + '\'s userpage');                else                    console.warn("[StaffTagger #3]: API error in protecting ", user + '\'s userpage:', data, '(API Error code \"' + data + '\")');            });

// #4: Change Staff Data on Staff Page // Now should update Module:Staff/Members instead that.api.post({               action: "edit",                section: that.getSection(rank),                appendtext: '\n*',                token: mw.user.tokens.values.editToken,                title: 'Hypixel_SkyBlock_Wiki:Staff',                summary: 'Adding ' + user + ' to the staff list per request to be staff: Hypixel_SkyBlock_Wiki_talk:Requests_to_be_staff",                minor: 1,                bot: 1,                watchlist: 'nochange',            }).always(function (data) {                if (data.edit) {                    console.log('[StaffTagger #4]: Successfully added ' + user + ' to staff member list');                } else {                    console.warn('[StaffTagger #4]: Failed to Add user to staff member list: ' + data);                }            });

// #5: Update staff-colors.less mw.libs.StaffUtil.updateStaffColors(function {               console.log("[StaffTagger #5]: Successfully updated staff-colors.less");            }) },

editorCloseHandler: function { that.modal.hide; },

createIntroSection: function { return "Select the ranks to grant this user. Then, the Staff Tagger will perform the following:\ \ Grant selected rights to the user on wiki (if applicable)\ Add StaffMsgBox to the user page\ Protect the user page\ Change staff data on Module:Staff/Members\ Update staff-colors.less\ \ "; },

createRanksSelection: function { return that.ranksAvailable.map(function(rank) {               var idname = "StaffTagger-rank-" + rank;                return {                    type: "div",                    attr: { id: "StaffTagger-ranks-wrapper" },                    children: [{                        type: "input",                        attr: { type: "checkbox", id: idname, "data-rank": rank },                    }, {                        type: "label",                        attr: { for: idname },                        text: rank,                    }],                };            }); },

showModal: function { that.modal.create; that.modal.setContent({ children: [{				type: "form",				attr: {					id: "StaffTagger-form",				},				children: [{					type: "span",                   attr: { class: "page-content" },					html: that.createIntroSection,				}, {					type: "div",					id: "StaffTagger-input",					children: [{						type: "div",						attr: { id: "StaffTagger-user-wrapper" },						children: [{							type: "div",							attr: { id: "StaffTagger-user" },							children: [{                                type: "label",                                id: "StaffTagger-user-label",                                text: "User: ",                            }, {                                type: "input",                                attr: { id: "StaffTagger-user-input", type: "text", value: that.user || "" },                            }]						}],					}, {						type: "div",						attr: { id: "StaffTagger-ranks-wrapper" }, children: [{ type: "div", id: "StaffTagger-ranks-label", text: "Select the ranks to grant this user:", }].concat(that.createRanksSelection), }],				}],			}] });           that.modal.show;        },        onclick: function(e) {            e.preventDefault;            that.user = (mw.config.get("wgNamespaceNumber") !== 2) ? $(this).parent.attr('data-user') :                 mw.config.get("wgPageName").match(mw.config.get("wgFormattedNamespaces")[2] + ":([^/]*)")[1];            that.showModal;        },        init: function  {            $('span#tag-user > a[href*="prepend="].text').click(that.onclick);            if (mw.config.get("wgNamespaceNumber") === 2) {                $('.page-header__contribution-buttons .wds-list, .page-header__actions .wds-list').first.append( $('').append(                       $('', { text: "Staff Tagger", href: "#", click: that.onclick, })                   )                );            }        },

modal: new window.dev.modal.Modal({           id: "StaffTagger-modal",            title: "Staff Tagger",            content: "",            buttons: [{                event: "onSubmit",                id: "StaffTagger-submit",                primary: true,                text: "Submit",            }],            events: {                onSubmit: this.processInformation,            },            size: "large",        }), });   that.init; });