User:Xytl/chat.js

// ToDo: // Modular approach // RPS // Refine key system // Do some tidying // Do some commenting /* var apiConfig = { version: "exp3", autostart: true, modules: [ {title: "Help", onClick: "apiHelp", subgroup: ""} ] };

$(function {   var style = $(" [class*='sub-'] { display: none; } ");    $('html > head').append(style);    if (apiConfig.autostart) {        enable;    }    $('[name="message"]').keydown(function(e) { if (e.which == 13) { switch($(this).val) { case "/enable": $(this).val(''); enable; break; case "/disable": $(this).val(''); disable; break; default: return; }       }    }); }); function enable { $('#Rail').append('API '); // Check if the user has their API Key set if (localStorage.getItem("apikey") === null) { api_button("Set ID Key", "apiKey"); } else { api_button("Whoami", "apiIdentifyMe", ""); api_button("Mail &#8628;", "showMail", ""); api_button("Get Mail ", "apiMail", "sub-mail"); api_button("Send Mail", "apiSend", "sub-mail"); api_button("Undelivered", "apiUndelivered", "sub-mail"); api_button("Warnings &#8628;", "showWarnings", ""); api_button("Warn", "apiAddWarn", "sub-warn"); api_button("Cancel Warn", "apiRemoveWarn", "sub-warn"); api_button("Warn History", "apiGetWarnings", "sub-warn"); api_button("User Management", "apiUserManagement", ""); api_button("Utilities &#8628;", "showUtilities", ""); api_button("Ban User", "apiBan", "sub-util"); api_button("Block User", "apiBlock", "sub-util"); api_button("Misc &#8628;", "showMisc", ""); api_button("RPS", "apiRPS", "sub-misc"); api_button("Dice", "apiDice", "sub-misc"); api_button("Links", "apiLinks", "sub-misc"); apiCountMsg; }   api_button("Help", "apiHelp"); } function disable { $('.api').remove; clearInterval; } function api_button(name, onclick, subclass) { $('#APIList').append('' + name + ''); } //////////////////////// // Hide/show handlers // //////////////////////// function showMail { $('.sub-mail').toggle; } function showWarnings { $('.sub-warn').toggle; }

function showUtilities { if (mainRoom.userMain.toJSON.canPromoteModerator) { $('.sub-util').toggle; } }

function showMisc { $('.sub-misc').toggle; } ////////////////////////////// // All the onclick handlers // ////////////////////////////// function apiCancel(id) { var args = {controller: "msg", action: "cancel_msg", id: id}; apiRequest(args, true); $('#' + id).remove; } function apiRead(id) { var args = {controller: "msg", action: "read_msg", id: id}; apiRequest(args, true); $('#' + id).remove; } function apiMail { var args = {controller: "msg", action: "get_msg"}; apiRequest(args, true); } function apiSend { createInputModal('Send Message', ' To   Message     ', {controller: "msg", action: "send_msg", target: null, message: null}, 2); } function apiHelp { createModal('Help', 'This is the help documentation for the chatbot API. What is this? This is a partial replacement and improvement to the functions of the original chatbots. It allows much of the same functionality with greatly increased privacy and reduced impact on chat. It is also intended to make commands easier to use. How do I use it? Step one is to request an ID key. In order to ensure that users cannot masquerade as others, an additional step of authentification is required.'); } function apiIdentifyMe { var args = {controller: "info", action: "whoami"}; apiRequest(args, true); } function apiUndelivered { var args = {controller: "msg", action: "undelivered"}; apiRequest(args, true); } function apiKey { var id = window.prompt("Please enter your ID Key (this is NOT your Wikia password)", "ID Key"); if(id.length !== 0) { localStorage.setItem("apikey", id); createModal("ID Key", "Your ID key has been saved"); disable; enable; } else { createModal("ID Key", "ID key cannot be blank"); } } function apiCountMsg { var args = {controller: "msg", action: "msg_count"}; apiRequest(args, false); } function apiAddWarn { createInputModal('Add Warning', ' Username   Wiki   Reason    ', {controller: "warn", action: "add_warn", target: null, wiki: null, reason: null}, 3); } function apiRemoveWarn { createInputModal('Remove Warning', ' Username   Wiki   Warn ID  <input id="id" class="formField" placeholder="" type="text" style="width:400px"/>  ', {controller: "warn", action: "remove_warn", target: null, wiki: null, id: null}, 3); } function apiGetWarnings { createInputModal('Warning History', '<form class="WikiaForm" id="inputForm"> Username  <input id="target" class="formField" placeholder="Username" type="text" style="width:400px"/> Wiki  <input id="wiki" class="formField" placeholder="Wiki subdomain" type="text" style="width:400px"/>  ', {controller: "warn", action: "get_warnings", target: null, wiki: null}, 2); }

function apiUserManagement { createInputModal('Get User Level/Status', '<form class="WikiaForm" id="inputForm"> Username  <input id="target" class="formField" placeholder="Username" type="text" style="width:400px"/>  ', {controller: "management", action: "return_levels", target: null, hr: true}, 1); }

function apiBan { var user = prompt("Enter the username of the user to ban:"); mainRoom.ban({name: user}); }

function apiBlock { createInputModal('Block User', '<form class="WikiaForm" id="inputForm"> Username  <input id="user" class="formField" placeholder="Username" type="text" style="width:400px"/> Expiry Time  <input id="expiry" class="formField" placeholder="1 week" type="text" style="width:400px"/> Reason  <input id="reason" class="formField" placeholder="Troll" type="text" style="width:400px"/> Block IP and subsequent IP\'s  <input id="autoblock" class="formField" type="checkbox"/> Permit access to Message Wall  <input id="allowusertalk" class="formField" type="checkbox"/> Prevent Account Creation  <input id="nocreate" class="formField" type="checkbox"/>  ', {action: "block", user: null, expiry: null, reason: null, autoblock: null, allowusertalk: null, nocreate: null, token: mw.user.tokens.values.editToken}, 6, "postRequest"); }

function apiChangeLevels(username) { cancelModal; createInputModal('Change levels' + username, '<form class="WikiaForm" id="inputForm"> Status  <select id="statuslevel" class="formField"> Select  Disabled  Restricted  Normal  Unchanged  Authlevel  <select id="authlevel" class="formField"> Select  Operator  Overseerer  User  Unchanged    ', {controller: "management", action: "change_levels", target: username, statuslevel: null, authlevel: null}, 2); }

function apiRPS { }

function apiDice { createModal('Roll some Dice', 'Roll Select  1  2  3  4  5  6  <input id="dicesides" type="text" placeholder="N" style="width:20px"/> sided dice <span class="button" onclick="diceRoll">Roll '); }

function diceRoll { var number = $('#dicenumber').val; var sides = $('#dicesides').val; cancelModal; var diceRolls = []; for (i=0; i < number; i++) { diceRolls.push(Math.floor(Math.random*(sides)+1)); }   createModal('Roll some Dice', 'You got the following numbers: ' + diceRolls.join(', ')); }

function apiLinks { createModal('Useful Links', '<a target="_blank" href="' + wgServer + '/wiki/User:' + wgUserName + '">My Profile</a> <a target="_blank" href="' + wgServer + '/wiki/Special:EditCount">EditCount</a> <a target="_blank" href="' + wgServer + '/wiki/Mediawiki:Emoticons">Emoticons</a> <a target="_blank" href="' + wgServer + '/wiki/Special:BlockList">Block List</a> <a target="_blank" href="' + wgServer + '/wiki/Special:ChatBanList">Chat Ban List</a> <a target="_blank" href="http://www.ajwiki.xyz/logs">Logs</a>'); }

///////////////////// // Modal functions // ///////////////////// function cancelModal { $($('.modalWrapper')[$('.modalWrapper').length - 1]).closeModal; } function createModal(title, content) { $.showCustomModal(title, content, {       id: "apiWindow",        width: 650,        buttons: [{            id: "cancel",            message: "Close",            handler: function  {                cancelModal;            }        }]    }); } // Args is an object // tbd (to be done) is an integer representing the number of variables needed function createInputModal(title, content, args, tbd, handler) { if (handler === undefined) { handler = "apiRequest"; }   $.showCustomModal(title, content, {        id: "apiWindow",        width: 650,        buttons: [{            id: "cancel",            message: "Close",            handler: function  {                cancelModal;            }        }, {            id: "submit",            defaultButton: true,            message: "Submit",            handler: function  {                submitModal(args, tbd, handler);            }        }]    }); } function submitModal(args, tbd, handler) { //Turns form fields into variables var $form = $('#inputForm'); j = $form.find('.formField'); for (var i=0; i < tbd; i++) { // If check box isn't checked, remove argument from list if ($(j[i]).attr('type') === "checkbox" && !$(j[i]).is(':checked')) { delete args[$(j[i]).attr('id')]; continue; // If select is left unchanged, set it to a default value } else if ($(j[i]).is("select") && !$(j[i]).val) { args[$(j[i]).attr('id')] = "default"; continue; // If we can't get a value out of it, leave it as null } else if (!$(j[i]).val) { continue; }       args[$(j[i]).attr('id')] = $(j[i]).val; }	switch(handler) { case "apiRequest": apiRequest(args, true); break; case "postRequest": postRequest(args); break; default: console.log("API client: Unable to parse handler"); }   cancelModal; } //////////////////////////// // Ajax request functions // /////////////////////////// function apiRequest(args, p2m) { args.user = wgUserName; if (localStorage.getItem("apikey") === null) { //If it doesn't work, just shut it down disable; console.log("WARNING: apikey not found"); } else { $.ajax({           url: 'http://api.ajwiki.xyz/'+apiConfig.version+'/api.php',            beforeSend: function(xhr) {                xhr.setRequestHeader('X-API-USER', wgUserName);                xhr.setRequestHeader('X-API-Key', localStorage.getItem("apikey"));            },            data: args,            type: 'POST',            success: function(raw_data) {                var data = $.parseJSON(raw_data);                if(p2m) {                    parseToModal(data, args);                } else {                    parseGeneral(data, args);                }            }        }); } } function parseToModal(data, args) { var no, responsearray = [], responsedata, i=0; if(data.query.status === "error") { createModal("Error", data.query.data); } else { if($.type(data.query.data) === "string") { if (args.action === "read_msg") { return; } else { createModal(args.action, data.query.data); }       } else if($.type(data.query.data) === "array") { if (args.action === "get_msg") { no = data.query.data.length; for (i=0; i < no; i++) { responsedata = data.query.data[i]; responsearray.push('<span id="' + responsedata[0] + '" onclick="apiRead(' + responsedata[0] + ')">[Delete] ['+responsedata[1]+'] ' + responsedata[2] + ' to you: ' + responsedata[3] + ' '); }               createModal("Message", responsearray.join(" ")); } else if(args.action === "undelivered") { no = data.query.data.length; for (i=0; i < no; i++) { responsedata = data.query.data[i]; responsearray.push('<span id="' + responsedata[0] + '">&#60;<b color="red" onclick="apiCancel(' + responsedata[0] + ')">Cancel</b>&#62; [' + responsedata[1] + '] ' + responsedata[2] + ' '); }               createModal("Undelivered messages", responsearray.join(" ")); } else if(args.action === "get_warnings") { no = data.query.data.length; responsearray.push(' Moderator  Reason  Timestamp  Expired '); for (i=0; i < no; i++) { responsedata = data.query.data[i]; responsearray.push('<tr id="' + responsedata[0] + '"> ' + responsedata[1] + ' ' + responsedata[2] + '  ' + responsedata[3] + '  ' + responsedata[4] + '  '); }               responsedata.push('</table'); createModal("Warning History", responsearray.join.replace(/,/g, '')); } else { console.log("Error: unable to handle response"); }       } else if($.type(data.query.data) == "object") { var output = []; $.each(data.query.data, function(key, value) {               output.push(key + ": " + value);            }); if (args.action === "return_levels") { output.push('<span onclick="apiChangeLevels(`' + data.query.data.username + '`)" style="font-weight: bold">Change '); }           createModal("Response", output.join(" ")); } else { console.log("Error: unable to handle response type"); }   } } function parseGeneral(data, args) { if(args.action == "msg_count") { $('#msgCount').text("[" + data.query.data + "]"); } }

function postRequest(args) { //Mediawiki seems to be tetchy about capitalising things like "infinite" console.log(args); if (args.hasOwnProperty("expiry")) { args.expiry = args.expiry.toLowerCase; }   var values = $.map(args, function(k, v) { return v + '=' + encodeURIComponent(k); }); values.push("format=json"); var url = wgServer+"/api.php?" + values.join("&"); console.log(url); $.post(url, function(data) {       console.log(data);    }); } window.setInterval(function{   apiCountMsg; }, 60000); console.log("Loaded API client v0.96");