AtoZ Utilities

Utilities that are frequently used in other scripts.

目前為 2020-06-03 提交的版本,檢視 最新版本

此腳本不應該直接安裝,它是一個供其他腳本使用的函式庫。欲使用本函式庫,請在腳本 metadata 寫上: // @require https://update.gf.qytechs.cn/scripts/404603/812057/AtoZ%20Utilities.js

您需要先安裝使用者腳本管理器擴展,如 TampermonkeyGreasemonkeyViolentmonkey 之後才能安裝該腳本。

You will need to install an extension such as Tampermonkey to install this script.

您需要先安裝使用者腳本管理器擴充功能,如 TampermonkeyViolentmonkey 後才能安裝該腳本。

您需要先安裝使用者腳本管理器擴充功能,如 TampermonkeyUserscripts 後才能安裝該腳本。

你需要先安裝一款使用者腳本管理器擴展,比如 Tampermonkey,才能安裝此腳本

您需要先安裝使用者腳本管理器擴充功能後才能安裝該腳本。

(我已經安裝了使用者腳本管理器,讓我安裝!)

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

(我已經安裝了使用者樣式管理器,讓我安裝!)

// ==UserScript==
// @name        AtoZ Utilities
// @description Utilities that are frequently used in other scripts.
// @version     1.0.0.1
// @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 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) {
    debug(`Torn API request for Part: ${part} Player Id: ${tornPlayerId} Selections: ${selections}`);
    if (validateEmpty(key)) {
         key = tornAPIKey;
    }

    return new Promise((resolve, reject) => {
        let funcName = "tornAPIRequest";

        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) {
                            setAPI(null);
                        }
                    }
                }
            },
            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