Greasy Fork is available in English.

New Kit

try to take over the medals!

// ==UserScript==
// @name         New Kit
// @namespace    erepfarm
// @version      2024.3
// @description  try to take over the medals!
// @author       Enemy of the eRepublik
// @match        https://www.erepublik.com/en
// @icon         https://www.google.com/s2/favicons?sz=64&domain=erepublik.com
// @grant        none
// ==/UserScript==
(function() {
    'use strict';

    window.addEventListener('load', function() {
        const captcha = checkSessionValidationExists();
        if (!captcha) {
            mainFunction();
        }
    });


    //main function on progress-------------------------------------------------------------------------------------------
    //task-> add ally into target array

    async function mainFunction() {
        const _token = csrfToken;
        const eday = erepublik.settings.eDay;
        const energymin = 31;
        const weapQu = 10;
        const energy = erepublik.citizen.energy;
        const countryLocationId = erepublik.citizen.countryLocationId;
        const division = erepublik.citizen.division;
        const ownId = erepublik.citizen.citizenId;

        const dataDay = readLocalStorage('dayKit');
        const initialT = readLocalStorage('initialTarget');

        const countryIds = [48, 49, 66, 45, 14, 67, 47, 59];

        let checked;
        try {
            checked = JSON.parse(readLocalStorage('battleChecked'));
        } catch (error) {
            checked = []; // Set default value as an empty array
        }
                console.log("CHECKED",checked);


        //set the target (begin)
        if (eday !== dataDay) {
            await delay(1000);
            const targetSet = new Set();
            const pregion = payloadRegion(0, _token);
            const urlT = "https://www.erepublik.com/en/main/travelData";
            const region = await PostRequest(pregion, urlT);

            countryIds.forEach(countryId => {
                const occupyingCountryIds = findOccupyingCountries(region, countryId);
                if (occupyingCountryIds) {
                    occupyingCountryIds.forEach(id => {
                        targetSet.add(id); // Add each ID to the Set
                    });
                }
            });
            const targetArray = targetSet.size > 0 ? [...targetSet] : [];
            console.log(targetArray);



            targetArray.forEach(function(element) {
                // Perform some action on each element
                console.log(element);
            });

            const newTarget = JSON.stringify(targetArray);
            updateLocalStorage('initialTarget', newTarget);
            updateLocalStorage('dayKit', eday);
            emptyLocalStorageValue('battleChecked');

            await delay(2000);
            redirectToErepublik();
            //end if
        } else {
            //if target already in local storage
            console.log("TARGET ALREADY CORRECT");
            console.log("--------------------");
        }
        //end of set the target

        //fetch battle data and set the list

        await delay(1000);
        const fetchTime = getCurrentUnixTimestamp();
        const max = fetchTime - (75 * 60);
        const fetchlist = await fetchData(`https://www.erepublik.com/en/military/campaignsJson/list?${fetchTime}`);
        await delay(1000);
        const zoneList = await fetchData(`https://www.erepublik.com/en/military/campaignsJson/citizen?${fetchTime}`);

        const storedArray = JSON.parse(initialT);
        // Assuming storedArray contains the array retrieved from local storage
        let alliesArray = [];

        storedArray.forEach(value => {
            const country = fetchlist.countries[value];
            if (country) {
                const allies = country.allies;
                if (allies.length > 0) {
                    alliesArray.push(...allies);
                }
            } else {
                console.log(`Country with id ${value} not found.`);
            }
        });

        let countryList = [...storedArray, ...alliesArray];
        const countries = fetchlist.countries;
        // Create an empty array to store the country names
            const countryNames = [];

            // Iterate through the countryList and retrieve names
            for (const countryId of countryList) {
                if (countries.hasOwnProperty(countryId)) {
                    countryNames.push(countries[countryId].name);
                }
            }

        //end of set the list
        let location = [];
        location.push(countryLocationId);

        const ally = fetchlist.countries[countryLocationId].allies;
        if (ally.length > 0) {
            ally.forEach(element => {
                location.push(element);
            });
        }

        //start filter the battle
        const list = Object.values(fetchlist.battles).filter(battle => {
            return (
                battle.war_type === "direct" &&
                (location.includes(battle.inv.id) || location.includes(battle.def.id)) &&
                (countryList.includes(battle.inv.id) && countryList.includes(battle.def.id)) &&
                battle.start < fetchTime
            );
        });

        createDivElement('allbattle', 'sidebar', 'Filtered Battle by Loc:');
        displayValueInHtml('allbattle', list.length);
        createDivElement('emptyBattle', 'sidebar', 'Battle List: ');
        createDivElement('list', 'sidebar', '');

        //check all filtered

        for (const battle of list) {
            await delay(500);
            let idBattle = battle.id;
            let round = battle.zone_id;
            let battleZoneId = zoneList.battles[idBattle].groundZoneId;
            let start = battle.start;


            //set current side vs opposite side
            let current;
            let opposite;
            if (location.includes(battle.inv.id)) {
                current = battle.inv.id;
                opposite = battle.def.id;
            } else if (location.includes(battle.def.id)) {
                current = battle.def.id;
                opposite = battle.inv.id;
            }
            const region = battle.region.name;
            const idchecked = current.toString() + battleZoneId.toString();

            //check wall (quick method)
            const wall = battle.div[battleZoneId].wall.dom;

            if(!checked.includes(idchecked)){
                // if not checked
                if(wall == 50 || wall == 100) {
                    const checkLoad = payloadStat(idBattle, round, round, division, battleZoneId, _token);
                    const battleStatURL = `https://www.erepublik.com/en/military/battle-console`;
                    const stat = await PostRequest(checkLoad, battleStatURL);

                    let hit = false;
                    const empty = checkFighterDataEmpty(stat, current);
                    const oppositeEmpty = checkFighterDataEmpty(stat, opposite);
                    const hitOpposite = checkCitizen(stat, opposite, ownId);

                    if (hitOpposite && (empty || getRawValue(stat, current) < 10000)) {
                        hit = true;
                    } else if (empty && oppositeEmpty) {
                        hit = true;
                    }

                    //end of check battlestat
                    //add another condition when late battle
                    if (hit && empty && oppositeEmpty && start < max && battle.def.id == current) {
                        hit = false;
                    }

                    console.log("HIT", hit);

                    //preparing to hit
                    const roundData = stat.rounds[battleZoneId];
                    const started = roundData.started;
                    const finished = roundData.finished;

                    if (hit && started == 1 && finished == 0) {
                        await delay(2000);
                        //check inventory
                        const invLoad = inventoryPayload(idBattle, current, battleZoneId, _token);
                        const invURL = `https://www.erepublik.com/en/military/fightDeploy-getInventory`;
                        const inventory = await PostRequest(invLoad, invURL);

                        const listweapon = inventory.weapons;
                        const vehicles = inventory.vehicles;

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

                        if (skinRecommended) {
                            skinId = skinRecommended.id;
                        }

                        // Find the object with quality 10 in the weapons response array
                        const objectWithQuality = listweapon.find(item => item.quality === weapQu);
                        let weaponAmount;
                        let totalEnergy;
                        if (objectWithQuality) {
                            weaponAmount = objectWithQuality.amount;
                        }
                        if (weaponAmount >= 2 && energy > energymin) {
                            totalEnergy = 11;
                            const depLoad = deployLoad(idBattle, battleZoneId, current, weapQu, totalEnergy, skinId, _token);
                            const depURL = `https://www.erepublik.com/en/military/fightDeploy-startDeploy`;
                            await PostRequest(depLoad, depURL);
                            await delay(1000);

                            checked.push(idchecked);
                            const linkText = `${region} - HIT`;
                            const linkUrl = `https://www.erepublik.com/en/military/battlefield/${idBattle}/${battleZoneId}`;
                            displayLinkInHtml('list', linkText, linkUrl);
                            await delay(2000);
                        }


                        //end of hit
                    } else {
                        const linkText = `${region} - SKIP`;
                        const linkUrl = `https://www.erepublik.com/en/military/battlefield/${idBattle}/${battleZoneId}`;
                        displayLinkInHtml('list', linkText, linkUrl);
                    }
                    //end of check battle stat
                }
                //end of check battle stat
            }

            //end of each battle check
        }
        updateLocalStorage('battleChecked', JSON.stringify(checked));
        console.log("END");
        createDivElement('end', 'sidebar', '---END---');
        createDivElement('listCountry', 'sidebar', 'List Country:');
            countryNames.forEach(function(countryName) {
                createDivElement('countryName', 'sidebar', countryName);
            });
    }


    //payload--------------------------------------------------------------------------------------------------------------------
    // 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
        };
    }

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

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

    //common erepublik function library---------------------------------------------------------------------------------
    function checkSessionValidationExists() {
        if (typeof SERVER_DATA !== 'undefined' && SERVER_DATA.sessionValidation !== undefined) {
            return true;
        } else {
            return false;
        }
    }

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

    function delay(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
    }

    function redirectToErepublik() {
        window.location.href = "https://www.erepublik.com/en";
    }

    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 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;
    }

    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.`);
        }
    }

    function countryName(inputId) {
        const country = countriesData.find(country => country.id === inputId);
        return country ? `${country.flag} ${country.name}` : "Country not found";
    }



    // Function to read from local storage
    function readLocalStorage(key) {
        if (typeof Storage !== 'undefined') {
            let storedValue = localStorage.getItem(key);

            if (storedValue === null) {
                console.error(`No value found for key '${key}' in local storage. Adding key with value 0.`);
                localStorage.setItem(key, '0');
                storedValue = '0';
            }

            // Check the type of the stored value and return accordingly
            if (!isNaN(storedValue)) {
                return parseInt(storedValue); // Return as number if it's a valid number
            } else if (storedValue === 'true' || storedValue === 'false') {
                return storedValue === 'true'; // Return as boolean for 'true' or 'false'
            } else {
                return storedValue; // Return as string if it's not a number or boolean
            }
        } else {
            console.error('Local storage is not supported in this browser.');
            return null;
        }
    }

    // Function to update local storage
    function updateLocalStorage(key, value) {
        if (typeof Storage !== 'undefined') {
            if (value !== undefined) {
                // Check the type of the value being passed
                if (typeof value === 'boolean') {
                    localStorage.setItem(key, value.toString()); // Store boolean as string
                    console.log(`Local storage with key '${key}' has been updated with a boolean.`);
                } else if (typeof value === 'string') {
                    localStorage.setItem(key, value); // Store string value directly
                    console.log(`Local storage with key '${key}' has been updated with a string.`);
                } else {
                    // Store other types of values as is (number, object, etc.)
                    localStorage.setItem(key, value);
                    console.log(`Local storage with key '${key}' has been updated with a value of type '${typeof value}'.`);
                }
            } else {
                console.error('Please provide a value to update in local storage.');
            }
        } else {
            console.error('Local storage is not supported in this browser.');
        }
    }

    // Function to empty value associated with a key in local storage
function emptyLocalStorageValue(key) {
    if (typeof Storage !== 'undefined') {
        localStorage.setItem(key, ''); // Set the value to an empty string
        console.log(`Value associated with key '${key}' in local storage has been emptied.`);
    } else {
        console.error('Local storage is not supported in this browser.');
    }
}

    async function PostRequest(payload, url) {

        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 checkhit(citizenStats, country) {
        if (citizenStats == null) {
            return true;
        } else {
            if (citizenStats[country] != null && citizenStats[country].current === 0) {
                return true;
            } else {
                return false;
            }
        }
    }

    function getRawValue(responseData, countryId) {
        // Check if responseData contains the specified countryId
        if (responseData.hasOwnProperty(countryId)) {
            // Access the raw_value property of fighterData.1 directly
            return responseData[countryId].fighterData['1'].raw_value;
        } else {
            // Country ID does not exist in the responseData
            console.error(`Country ID ${countryId} does not exist in the responseData`);
            return null;
        }
    }

    // other function-----------------------------------------------------------------------------------------------------------------



    function payloadRegion(regionId, _token) {
        const holdingId = 0;
        const battleId = '';

        return {
            _token,
            holdingId,
            battleId,
            regionId
        };
    }

    function findOccupyingCountries(countriesData, countryId) {
        const country = countriesData.countries[countryId];
        if (!country || !country.regionsOccupiedByOthers) {
            return null;
        }

        let regionsOccupied = [];
        if (typeof country.regionsOccupiedByOthers === 'string') {
            regionsOccupied = country.regionsOccupiedByOthers.split(',').map(Number);
        } else if (Array.isArray(country.regionsOccupiedByOthers)) {
            regionsOccupied = country.regionsOccupiedByOthers.map(Number);
        }

        const resultCountries = new Set();

        for (const regionId of regionsOccupied) {
            for (const otherCountryId in countriesData.countries) {
                if (otherCountryId !== countryId) {
                    const otherCountry = countriesData.countries[otherCountryId];
                    const regions = otherCountry.regions || [];

                    if (regions.includes(regionId)) {
                        resultCountries.add(parseInt(otherCountryId));
                    }
                }
            }
        }

        return resultCountries.size > 0 ? [...resultCountries] : null;
    }

    function checkCitizen(stat, countryId, citizenId) {
    // Check if the countryId exists in the stat object
    if (stat.hasOwnProperty(countryId)) {
        // Check if the citizenId exists within the fighterData of the specified countryId
        if (stat[countryId].hasOwnProperty('fighterData')) {
            const fighterData = stat[countryId].fighterData;
            // Iterate through each citizenData object within fighterData
            for (const key in fighterData) {
                if (fighterData.hasOwnProperty(key)) {
                    // Check if the citizenId matches
                    if (fighterData[key].citizenId === citizenId) {
                        return true; // Citizen found
                    }
                }
            }
        }
    }
    return false; // Citizen not found
}




})();