AtoZ Utilities

Utilities that are frequently used in other scripts.

Устаревшая версия за 03.06.2020. Перейдите к последней версии.

Этот скрипт недоступен для установки пользователем. Он является библиотекой, которая подключается к другим скриптам мета-ключом // @require https://updategf.qytechs.cn/scripts/404603/812070/AtoZ%20Utilities.js

Чтобы установить этот скрипт, вы сначала должны установить расширение браузера, например Tampermonkey, Greasemonkey или Violentmonkey.

Для установки этого скрипта вам необходимо установить расширение, такое как Tampermonkey.

Чтобы установить этот скрипт, вы сначала должны установить расширение браузера, например Tampermonkey или Violentmonkey.

Чтобы установить этот скрипт, вы сначала должны установить расширение браузера, например Tampermonkey или Userscripts.

Чтобы установить этот скрипт, сначала вы должны установить расширение браузера, например Tampermonkey.

Чтобы установить этот скрипт, вы должны установить расширение — менеджер скриптов.

(у меня уже есть менеджер скриптов, дайте мне установить скрипт!)

Чтобы установить этот стиль, сначала вы должны установить расширение браузера, например Stylus.

Чтобы установить этот стиль, сначала вы должны установить расширение браузера, например Stylus.

Чтобы установить этот стиль, сначала вы должны установить расширение браузера, например Stylus.

Чтобы установить этот стиль, сначала вы должны установить расширение — менеджер стилей.

Чтобы установить этот стиль, сначала вы должны установить расширение — менеджер стилей.

Чтобы установить этот стиль, сначала вы должны установить расширение — менеджер стилей.

(у меня уже есть менеджер стилей, дайте мне установить скрипт!)

// ==UserScript==
// @name        AtoZ Utilities
// @description Utilities that are frequently used in other scripts.
// @version     1.0.0.4
// @exclude     *
// @namespace   AtoZ
// @source      https://greasyfork.org/en/scripts/404603-atoz-utilities
// ==/UserScript==


initialize();

function initialize() {
    Number.prototype.format = function(n, x) {
        var re = '\\d(?=(\\d{' + (x || 3) + '})+' + (n > 0 ? '\\.' : '$') + ')';
        return this.toFixed(Math.max(0, ~~n)).replace(new RegExp(re, 'g'), '$&,');
    };
}

const localStorageAPIKey = "AtoZ_apikey";
const localStorageDKKAPIKey = "dkkutils_apikey";
const tornPlayerIdCookieName = "uid";

var Logging = {
    Identifier: "*** AtoZ ***",
    Debugging: {
        Active: false,
        Identifier: "*** AtoZ DEBUG ***"
    }
}

var thisScriptName = "Utilities";
var tornAPIKey = null;
var tornPlayerId = getCookie(tornPlayerIdCookieName);

//#region General Purpose

function Startup(needAPI) {
    if (needAPI) {
        if (validateEmpty(tornAPIKey)) {
            requestAPIKey();
        }
    }
}

function validateEmpty(value) {
    if (!value || value === undefined || value == "undefined" || value === null || value == "null" || value === ""){
        return true;
    }
    else {
        return false;
    }
}

function verifyJSONString(JSONString) {
    let response = {
        isError: null,
        errorName: null,
        errorMessage: null,
        content: null
    };

    let json = null;

    if (validateEmpty(JSONString)) {
        response.isError = true;
        response.errorName = "EmptyString";
        response.errorMessage = "The JSON string is empty.";
        return response;
    }
    try {
        json = JSON.parse(JSONString);
    } catch (e) {
        response.isError = true;
        response.errorName = e.errorName;
        response.errorMessage = e.errorMessage;
        return response;
    }

    response.isError = false;
    response.content = json;
    return response;
}

//#endregion General Purpose

//#region API Key

function validateAPIKey(apiKey) {
    let funcName = "validateAPIKey";

    if (validateEmpty(apiKey)) {
        if (validateEmpty(tornAPIKey)) {
            createDebugLog(thisScriptName, funcName, "[failure]: " + apiVar);
            return null;
        }
        else {
            apiKey = tornAPIKey;
        }
    }

    if (apiKey.length != 16) {
        createDebugLog(thisScriptName, funcName, "[failure]: " + apiVar);
        return null;
    }

    createDebugLog(thisScriptName, funcName, "[success]: " + apiVar);
    return apiKey;
}

function storeAPIKey(apiKey) {
    let funcName = "storeAPIKey";
    let apiVar = validateAPIKey(apiKey);

    if (validateEmpty(apiVar)) {
        createDebugLog(thisScriptName, funcName, "[failure]: " + apiVar);
        localStorage.removeItem(localStorageAPIKey);
    }
    else{
        localStorage.setItem(localStorageAPIKey, apiVar);
        createDebugLog(thisScriptName, funcName, "[success]: " + apiVar);
    }

    tornAPIKey = apiVar;
}

function clearAPIKey() {
    localStorage.removeItem(localStorageAPIKey);
    tornAPIKey = null;
    createDebugLog(thisScriptName, "clearAPIKey", "User API Key removed.")
}

function retrieveAPIKey() {
    let funcName = "retrieveAPIKey";
    let apiVar = validateAPIKey(localStorage.getItem(localStorageAPIKey));
    if (!validateEmpty(apiVar)) {
        createDebugLog(thisScriptName, funcName, "[success]: " + apiVar);
        return apiVar;
    }
    
    //Maybe the user has DKK scripts, so use that key instead:
    apiVar = validateAPIKey(localStorage.getItem(localStorageDKKAPIKey));
    if (!validateEmpty(apiVar)) {
        createDebugLog(thisScriptName, funcName, "[Try DKK key] - [success]: " + apiVar);
        return apiVar;
    }

    createDebugLog(thisScriptName, funcName, "[failure]:" + apiVar);
    return null
}

function requestAPIKey() {
    let funcName = "requestAPIKey";

    tornAPIKey = retrieveAPIKey();
    if (validateEmpty(tornAPIKey)) {
        createDebugLog(thisScriptName, funcName, "No api key")
        let response = prompt("Enter your API key for the AtoZ script(s) to work: ");
        tornAPIKey = validateAPIKey(response);
        if (!validateEmpty(tornAPIKey)) {
            createDebugLog(thisScriptName, funcName, "[VALID] key obtained from user: " + tornAPIKey)
            storeAPIKey(tornAPIKey);
        } else {
            createDebugLog(thisScriptName, funcName, "[INVALID] key obtained from user: " + tornAPIKey)
            alert("The key you entered is invalid.\nWithout it, this script cannot work.\nRefresh to try again.")
        }
    }
}

//#endregion API Key

//#region Logging

function activateDebugging(activate) {
    Logging.Debugging.Active = activate;
}

function logObject(object) {
    console.log(JSON.parse(JSON.stringify(object)));
}

function createDebugLog(scriptName, functionName, debugMessage) {
    if (!Logging.Debugging.Active) {
        return;
    }

    console.log(Logging.Debugging.Identifier + " [" + scriptName + "] - [" + functionName + "] - " + debugMessage);
}

function createLog(scriptName, functionName, message) {
    console.log(Logging.Identifier + " [" + scriptName + "] - [" + functionName + "] - " + message);
}


//#endregion Logging

//#region Torn API

var tornAPIParts = {
    User: {
        Key: "user",
        Selections: {
            Ammo: "ammo",
            Attacks: "attacks",
            AttacksFull: "attacksfull",
            Bars: "bars",
            Basic: "basic",
            BattleStats: "battlestats",
            Bazaar: "bazaar",
            Cooldowns: "cooldowns",
            Crimes: "crimes",
            Discord: "discord",
            Display: "display",
            Education: "education",
            Events: "events",
            Gym: "gym",
            Hof: "hof",
            Honors: "honors",
            Icons: "icons",
            Inventory: "inventory",
            JobPoints: "jobpoints",
            Medals: "medals",
            Merits: "merits",
            Messages: "messages", 
            Money: "money", 
            Networth: "networth",
            Notifications: "notifications",
            Perks: "perks",
            PersonalStats: "personalstats",
            Profile: "profile",
            Properties: "properties",
            ReceivedEvents: "receivedevents",
            Refills: "refills",
            Revives: "revives",
            RevivesFull: "revivesfull",
            Stocks: "stocks",
            Timestamp: "timestamp",
            Travel: "travel",
            WeaponExp: "weaponexp",
            WorkStats: "workstats"
        }
    },
    Properties: {
        Key: "property",
        Selections: null
    },
    Faction: {
        Key: "faction",
        Selections: null
    },
    Company: {
        Key: "company",
        Selections: null
    },
    ItemMarket: {
        Key: "market",
        Selections: null
    },
    Torn: {
        Key: "torn",
        Selections: null
    }
}

function tornAPIRequest(part, selections, key) {
    let funcName = "tornAPIRequest";

    createDebugLog(thisScriptName, funcName, `Torn API request for Part: ${part} Player Id: ${tornPlayerId} Selections: ${selections}`);
    if (validateEmpty(key)) {
         key = tornAPIKey;
    }

    return new Promise((resolve, reject) => {

        GM_xmlhttpRequest({
            method: "GET",
            url: `https://api.torn.com/${part}/${tornPlayerId}?selections=${selections}&key=${key}`,
            onreadystatechange: function(response) {
                if (response.readyState > 3 && response.status === 200) {
                    //TODO: Remove debugger. It's only to see what comes back here in response... Also, fix the debug log after investigating the response...
                    debugger;
                    createDebugLog(thisScriptName, funcName, "Torn API response received: ")
                    logObject(response);
                    let verifyJSON = verifyJSONString(response.responseText);
                    createDebugLog(thisScriptName, funcName, "Torn API Json verify response:");
                    logObject(verifyJSON);
                    if (verifyJSON.isError) {
                        createDebugLog(thisScriptName, funcName, "JSON Error: " + verifyJSON.errorName + " - " + verifyJSON.errorMessage + " ResponseText: " + response.responseText);
                        reject("JSON Error", response.responseText);
                        return;
                    }

                    resolve(verifyJSON.content);

                    if (verifyJSON.content.error) {
                        //TODO: Remove debugger. It's only to see what comes back here in verifyJSON.content... Also, fix the debug log after investigating the verifyJSON.content...
                        debugger;
                        createDebugLog(thisScriptName, funcName, "Torn API Error: " + verifyJSON.content.error.code)
                        if (verifyJSON.content.error.code == 2) {
                            clearAPIKey();
                        }
                    }
                }
            },
            onerror: function(errorResponse) {
                createDebugLog(thisScriptName, funcName, "httpRequest Error: " + errorResponse);
                reject('httpRequest error.');
            }
        })
    }).catch(err => {
        createDebugLog(thisScriptName, funcName, "Promise Error: " + err);
    });
}

//#endregion Torn API

//#region Cookies

function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for(var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}

//#endregion