Greasy Fork

New Something c00L

Too lazy to do something on Halloween

// ==UserScript==
// @name         New Something c00L
// @namespace    erepFarm
// @version      2.6.666
// @description  Too lazy to do something on Halloween
// @author       You
// @match        https://www.erepublik.com/pt
// @grant        none
// @run-at		document-end
// ==/UserScript==
(function() {

    // Main function to perform the main task
    async function mainFunction() {
        let energymin = 650;
        let aircraft = false;
        let groundWeaponUse = true;
        let abWeaponUse = false;
        let weapQu = -1;
        let groundWeaponQ = 7;
        let abWeaponQ = 10;
        let energy = erepublik.citizen.energy;
        let ablow = 30000;
        let abhigh = 42000;
        let gblow =  200000000;
        let gbhigh = 360000000;
        let booster = false;
        const day = erepublik.settings.eDay;


        if (abWeaponUse == false) {
            energymin = energymin * 2;
        }

        // Extract the "day" value
        const rfcValue = SERVER_DATA.serverTime.rfc;
        const rfcParts = rfcValue.split(", ");
        const dayAbbreviation = rfcParts[0];
        console.log(dayAbbreviation);

        if (dayAbbreviation == "Tue") {
            ablow = ablow - (ablow * 0.05);
            abhigh = abhigh - (abhigh * 0.15);
        } else if (dayAbbreviation == "Thu" || dayAbbreviation == "Fri") {
            ablow = ablow + (ablow * 0.05);
            abhigh = abhigh + (abhigh * 0.05);
        } else if (dayAbbreviation == "Sat" || dayAbbreviation == "Sun") {
            ablow = ablow + (ablow * 0.1);
            abhigh = abhigh + (abhigh * 0.1);
        }

        const abmid = (ablow + abhigh) / 2;
        const gbmid = (gblow + gbhigh) / 2;
        let low;
        let mid;
        let high;
        let Dbooster;
        let timestampWithRemaining;


        if (aircraft == true) {
            low = ablow;
            mid = abmid;
            high = abhigh;
            createDivElement('aircraft', 'sidebar', 'Aicraft: ');
            createDivElement('slow', 'sidebar', 'Low Damage: ');
            displayValueInHtml('slow', low);
            createDivElement('smid', 'sidebar', 'Mid Damage: ');
            displayValueInHtml('smid', mid);
            createDivElement('shigh', 'sidebar', 'High Damage: ');
            displayValueInHtml('shigh', high);
            createDivElement('useweapon', 'sidebar', 'Activate Weapon: ');
            displayValueInHtml('useweapon', abWeaponUse);
            if (abWeaponUse == true) {
                weapQu = abWeaponQ;
            }
            console.log("weapon Quality:", weapQu);
        } else {
            low = gblow;
            mid = gbmid;
            high = gbhigh;
            createDivElement('ground', 'sidebar', 'Ground: ');
            createDivElement('slow', 'sidebar', 'Low Damage: ');
            displayValueInHtml('slow', low);
            createDivElement('smid', 'sidebar', 'Mid Damage: ');
            displayValueInHtml('smid', mid);
            createDivElement('shigh', 'sidebar', 'High Damage: ');
            displayValueInHtml('shigh', high);
            createDivElement('useweapon', 'sidebar', 'Activate Weapon: ');
            displayValueInHtml('useweapon', groundWeaponUse);
            if (groundWeaponUse == true) {
                weapQu = groundWeaponQ;
            }
            console.log("weapon Quality:", weapQu);

            const targetIndustryId = 100;
            const inventoryItem = await fetchData("https://www.erepublik.com/en/economy/inventory-items");
            if (inventoryItem &&
                inventoryItem.inventoryItems &&
                inventoryItem.inventoryItems.activeEnhancements &&
                inventoryItem.inventoryItems.activeEnhancements.items) {
                const items = inventoryItem.inventoryItems.activeEnhancements.items;
                const itemsArray = Object.values(items);
                const itemWithTargetIndustry = itemsArray.find((item) => item.industryId === targetIndustryId);
                if (itemWithTargetIndustry) {
                    // Extract type, quality, and remaining values
                    const {
                        type,
                        quality,
                        remaining
                    } = itemWithTargetIndustry;

                    if (type === 'damage') {
                        // Get the current Unix timestamp
                        const currentTimestamp = Math.floor(Date.now() / 1000);

                        // Add remaining to the current timestamp
                        timestampWithRemaining = currentTimestamp + remaining;
                        Dbooster = quality / 10;
                        booster = true;
                        console.log(Dbooster);
                    }
                }

            }

        }



        const fetchTime = getCurrentUnixTimestamp();
        const zone = await fetchData(`https://www.erepublik.com/en/military/campaignsJson/citizen?${fetchTime}`);
        await delay(2000);
        const list = await fetchData(`https://www.erepublik.com/en/military/campaignsJson/list?${fetchTime}`);



        if (zone && list && energy > energymin) {
            try {
                createDivElement('emptyBattle', 'sidebar', 'Battle List: ');
                createDivElement('list', 'sidebar', '');
                console.log("Aircraft? ", aircraft);
                let _token = csrfToken;
                let countryLocationId = erepublik.citizen.countryLocationId;
                let division;

                if (aircraft == true) {
                    division = 11;
                } else {
                    division = erepublik.citizen.division;
                }


                //separate battle target to array
                for (const battleId in list.battles) {
                    if (list.battles.hasOwnProperty(battleId)) {
                        const battle = list.battles[battleId];
                        const zoneId = zone.battles[battleId];
                        const battleType = battle.war_type;
                        const round = battle.zone_id;
                        const rnow = round;
                        let battleZoneId;
                        let end;

                        if (zoneId && aircraft == true) {
                            battleZoneId = zoneId.aircraftZoneId;
                        } else {
                            battleZoneId = battleZoneId = zoneId.groundZoneId;
                        }

                        if (battleType == "direct") {
                            const inv = battle.inv.id;
                            const def = battle.def.id;
                            let cidDom = 0;
                            let oppoidDom = 0;


                            if (inv == countryLocationId || def == countryLocationId) {
                                const invpo = battle.inv.points;
                                const devpo = battle.def.points;
                                const point = invpo - devpo;
                                const campaign = Math.abs(point);
                                let oppositeCID;

                                const region = battle.region.name;

                                const batstaturl = `https://www.erepublik.com/en/military/battle-stats/${battleId}/${division}/${battleZoneId}`;
                                const getbatstat = await fetchData(batstaturl);
                                end = getbatstat.zone_finished;
                                let deffend = false;
                                if (countryLocationId == def) {
                                    deffend = true;
                                    oppositeCID = inv;
                                }
                                if (countryLocationId == inv) {
                                    deffend = false;
                                    oppositeCID = def;
                                }

                                if (getbatstat.division.hasOwnProperty(countryLocationId) && getbatstat.division.hasOwnProperty(oppositeCID)) {
                                    cidDom = getbatstat.division[countryLocationId][battleZoneId].domination;
                                    oppoidDom = getbatstat.division[oppositeCID][battleZoneId].domination;

                                } else {
                                    console.log("Division not found");
                                }
                                console.log(region, " deffend?", deffend);
                                await delay(1000);

                                if (end == false) {
                                    const payloadBStat = payloadStat(battleId, round, rnow, division, battleZoneId, _token);
                                    const stat = await battleStat(payloadBStat);
                                    const empty = checkFighterDataEmpty(stat, countryLocationId);


                                    if (empty == true) {
                                        if (day < 5840) {
                                            const shadowPayload = payloadShadow(battleId, battleZoneId, countryLocationId, _token);
                                            await shadowbooster(shadowPayload);
                                        }
                                        await delay(1000);
                                        //check damage per hit
                                        const inventoryLoad = inventoryPayload(battleId, countryLocationId, battleZoneId, _token);
                                        const inventory = await inventoryCheck(inventoryLoad);
                                        let pool = inventory.poolEnergy;
                                        const listweapon = inventory.weapons;
                                        const vehicles = inventory.vehicles;
                                        let totDamage = 0;

                                        // Find the object with quality 10 in the weapons response array
                                        const objectWithQuality = listweapon.find(item => item.quality === weapQu);

                                        // Get the value of the 'amount' property if the object is found
                                        let weaponAmount;
                                        let dph;
                                        if (objectWithQuality) {
                                            weaponAmount = objectWithQuality.amount;
                                            dph = objectWithQuality.damageperHit;
                                        }

                                        //skin
                                        const skinRecommended = vehicles.find(skin => skin.isRecommended === true);
                                        let skinId;
                                        let skinBonus;

                                        if (skinRecommended) {
                                            skinId = skinRecommended.id;
                                            skinBonus = skinRecommended.countryData.damageBonus;
                                        }

                                        let percentage = 0;
                                        if (skinBonus !== null) {
                                            percentage = skinBonus / 100;
                                        }

                                        let damageBonus = dph + (dph * percentage);
                                        console.log("Damage bonus: ", damageBonus);

                                        const currentTimestamp2 = Math.floor(Date.now() / 1000);
                                        const minuteLeft = currentTimestamp2 + 240;

                                        if (booster == true && timestampWithRemaining >= minuteLeft) {
                                            damageBonus = damageBonus + (damageBonus * Dbooster);
                                            console.log("Damage bonus new: ", damageBonus);
                                        }


                                        //check opposite total damage
                                        const opposite = checkFighterDataEmpty(stat, oppositeCID);
                                        if (opposite == false) {
                                            totDamage = calculateTotalValue(stat, oppositeCID)
                                        }

                                        const linkText = `${region} - ${totDamage}`;
                                        const linkUrl = `https://www.erepublik.com/en/military/battlefield/${battleId}/${battleZoneId}`;
                                        displayLinkInHtml('list', linkText, linkUrl);
                                        console.log("Total Damage opposite: ", totDamage);

                                        //check damage
                                        const damageHit = await checkDamage(low, mid, high, deffend, totDamage, damageBonus, campaign, cidDom, oppoidDom);
                                        if (damageHit > 10) {
                                            console.log("Expected Energy: ", damageHit);
                                        }
                                        let delayTime = (damageHit / 10) * 400;
                                        console.log("Energy left: ", pool);

                                        if (pool > damageHit) {
                                            const loadDeploy = deployLoad(battleId, battleZoneId, countryLocationId, weapQu, damageHit, skinId, _token);
                                            const deployHit = await deployDamage(loadDeploy);
                                            console.log(deployHit);
                                            await delay(delayTime);
                                        }




                                    }

                                    await delay(1000);
                                }

                                console.log("--------------");
                            }
                        }
                    }
                }
            } catch (error) {
                console.error("Error fetching data:", error);
            }
        }
    }

    //list of function

    // Function to send GET request and fetch JSON data
    async function fetchData(url) {
        try {
            const response = await fetch(url);
            if (!response.ok) {
                throw new Error(`HTTP error! Status: ${response.status}`);
            }
            const data = await response.json();
            return data;
        } catch (error) {
            throw new Error(`Failed to fetch data from ${url}: ${error.message}`);
        }
    }

    // Function to introduce a delay
    function delay(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
    }

    // Function to construct the payload from variables
    function payloadStat(battleId, zoneId, round, division, battleZoneId, _token) {
        const action = "battleStatistics";
        const type = "damage";
        const leftPage = 1;
        const rightPage = 1;

        return {
            battleId,
            zoneId,
            action,
            round,
            division,
            battleZoneId,
            type,
            leftPage,
            rightPage,
            _token
        };
    }

    // Function to send the payload using POST request
    async function battleStat(payload) {
        const url = "https://www.erepublik.com/en/military/battle-console";

        try {
            const response = await fetch(url, {
                method: "POST",
                headers: {
                    "Content-Type": "application/x-www-form-urlencoded"
                },
                body: Object.keys(payload)
                    .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(payload[key])}`)
                    .join('&')
            });

            const responseData = await response.json();
            return responseData;
        } catch (error) {
            console.error("Error:", error);
            return null;
        }
    }

    // Function to check if country.fighterData is empty and push to new array if empty
    function checkFighterDataEmpty(responseData, countryLocationId) {
        if (responseData && responseData[countryLocationId] && responseData[countryLocationId]["fighterData"]) {
            const fighterData = responseData[countryLocationId]["fighterData"];
            const isFighterDataEmpty = Object.keys(fighterData).length === 0;
            return isFighterDataEmpty;
        } else {
            console.log(`Could not find ${countryLocationId}.fighterData in the response.`);
        }
    }

    // Function to calculate the total value
    function calculateTotalValue(data, countryId) {
        let totalValue = 0;
        const fighterData = data[countryId]?.fighterData || {};

        for (const key in fighterData) {
            if (fighterData.hasOwnProperty(key)) {
                const value = fighterData[key].value;
                if (typeof value === 'string') {
                    const parsedValue = parseInt(value.replace(/,/g, ''), 10);
                    if (!isNaN(parsedValue)) {
                        totalValue += parsedValue;
                    }
                }
            }
        }

        return totalValue;
    }

    //payload for inventory
    function inventoryPayload(battleId, sideCountryId, battleZoneId, _token) {
        return {
            battleId,
            sideCountryId,
            battleZoneId,
            _token
        };
    }

    //function to check inventory
    async function inventoryCheck(payload) {
        const url = "https://www.erepublik.com/en/military/fightDeploy-getInventory";

        try {
            const response = await fetch(url, {
                method: "POST",
                headers: {
                    "Content-Type": "application/x-www-form-urlencoded"
                },
                body: Object.keys(payload)
                    .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(payload[key])}`)
                    .join('&')
            });

            const responseData = await response.json();
            return responseData;
        } catch (error) {
            console.error("Error:", error);
            return null;
        }
    }

    // Function to create a new div element inside a parent element
    function createDivElement(divId, parentId, textContent) {
        const parentElement = document.querySelector(`.${parentId}`);
        if (parentElement) {
            const newDiv = document.createElement('div');
            newDiv.id = divId;
            newDiv.textContent = textContent;
            parentElement.appendChild(newDiv);
        } else {
            console.error(`Parent element with class '${parentId}' not found.`);
        }
    }

    // Function to display any value in HTML
    function displayValueInHtml(elementId, value) {
        const element = document.getElementById(elementId);
        if (element) {
            element.textContent = `${element.textContent} ${value}`;
        } else {
            console.error(`Element with ID '${elementId}' not found.`);
        }
    }

    function displayLinkInHtml(containerId, linkText, linkUrl) {
        const containerElement = document.getElementById(containerId);
        if (containerElement) {
            const linkElement = document.createElement('a');
            linkElement.href = linkUrl;
            linkElement.target = '_blank';
            linkElement.textContent = linkText;
            containerElement.appendChild(linkElement);
            containerElement.appendChild(document.createElement('br'));
        } else {
            console.error(`Container element with ID '${containerId}' not found.`);
        }
    }


    async function checkDamage(low, mid, high, deffend, totDamage, damageBonus, campaign, cidDom, oppoidDom) {

        let domTotal = cidDom + oppoidDom;
        let domDiff = Math.abs(cidDom - oppoidDom);
        let targetDamage;
        let energyCount;
        let doubleL = low * 2;
        let doubleM = mid * 2;
        let doubleH = high * 2;
        let Hplus = high + (high * 0.05);
        let Mplus = mid + (mid * 0.1);
        let Lmin = low - (low * 0.05);
        let TDplus = totDamage + (totDamage * 0.1);
        let TDmin = totDamage - (totDamage * 0.15);


        if (campaign > 20) {
            if (deffend) {
                if (totDamage == 0 || totDamage < mid) {
                    targetDamage = mid;
                } else if (domTotal < 900 && totDamage > low && totDamage < mid) {
                    targetDamage = TDplus;
                } else if (domTotal > 900 && totDamage > low && totDamage < high) {
                    targetDamage = TDmin;
                } else if (totDamage > doubleH) {
                    targetDamage = Hplus;
                } else {
                    targetDamage = high;
                }
            } else {
                if (totDamage == 0 || totDamage < low) {
                    targetDamage = Lmin;
                } else if (totDamage > low && totDamage < mid) {
                    targetDamage = TDmin;
                } else if (totDamage > mid && totDamage < doubleM) {
                    targetDamage = mid;
                } else if (totDamage > doubleM) {
                    targetDamage = Mplus;
                }
            }
        } else if (campaign <= 20) {
            if (deffend) {
                if (totDamage == 0 || totDamage < high) {
                    targetDamage = high;
                } else {
                    targetDamage = TDplus;
                }
            } else {
                if (totDamage < doubleL) {
                    targetDamage = low;
                } else {
                    targetDamage = TDmin;
                }
            }
        }
        let exactDamage = Math.floor(damageBonus);
        energyCount = Math.ceil((targetDamage / exactDamage) * 10);
        return energyCount;
    }


    //function to deploy
    function deployLoad(battleId, battleZoneId, sideCountryId, weaponQuality, totalEnergy, skinId, _token) {
        return {
            battleId,
            battleZoneId,
            sideCountryId,
            weaponQuality,
            totalEnergy,
            skinId,
            _token
        };
    }

    // Function to send a POST request for fight deploy
    async function deployDamage(payload) {
        const url = 'https://www.erepublik.com/en/military/fightDeploy-startDeploy';

        try {
            const response = await fetch(url, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                body: Object.keys(payload)
                    .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(payload[key])}`)
                    .join('&')
            });

            const responseData = await response.json();
            return responseData;
        } catch (error) {
            console.error('Error:', error);
            return null;
        }
    }
    // Function to construct the payload from variables
    function payloadShadow(battleId, battleZoneId, sideId, _token) {
        const type = "shadow_fighter";
        const quality = 100;
        const duration = 7200;


        return {
            type,
            quality,
            duration,
            battleId,
            battleZoneId,
            sideId,
            _token
        };
    }

    // Function to send the payload using POST request
    async function shadowbooster(payload) {
        const url = "https://www.erepublik.com/en/military/fight-activateBooster";

        try {
            const response = await fetch(url, {
                method: "POST",
                headers: {
                    "Content-Type": "application/x-www-form-urlencoded"
                },
                body: Object.keys(payload)
                    .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(payload[key])}`)
                    .join('&')
            });

            const responseData = await response.json();
            return responseData;
        } catch (error) {
            console.error("Error:", error);
            return null;
        }
    }

    function getCurrentUnixTimestamp() {
        const currentTime = new Date();
        const unixTimestamp = Math.floor(currentTime.getTime() / 1000); // Convert milliseconds to seconds
        return unixTimestamp;
    }




    //end of line
    // Call the main function when the page loads
    window.addEventListener('load', mainFunction);
})();