Skip to content

Instantly share code, notes, and snippets.

@driversti
Last active January 8, 2024 19:40
Show Gist options
  • Select an option

  • Save driversti/eb91d3bf5ccc05bc9c1bbea808d6c7ce to your computer and use it in GitHub Desktop.

Select an option

Save driversti/eb91d3bf5ccc05bc9c1bbea808d6c7ce to your computer and use it in GitHub Desktop.

Revisions

  1. driversti revised this gist Jan 8, 2024. 1 changed file with 124 additions and 106 deletions.
    230 changes: 124 additions & 106 deletions auto_activation_3min_pp_boosters.userscript.js
    Original file line number Diff line number Diff line change
    @@ -1,7 +1,7 @@
    // ==UserScript==
    // @name 3min PP boosters activation
    // @namespace https://www.erepublik.com/
    // @version 1.0
    // @version 1.1
    // @description Activate all 3min PP boosters with one click.
    // @copyright YOU ARE NOT ALLOWED TO DISCLOSE THIS SCRIPT TO OTHERS WITHOUT MY PERMISSION!!!
    // @author driversti https://www.erepublik.com/en/citizen/profile/4690052
    @@ -13,6 +13,11 @@
    (function () {
    'use strict';

    const erpk = erepublik.settings.pomelo.authToken;
    const _token = SERVER_DATA.csrfToken;

    const timeoutBetweenActivations = 500; // in ms

    // Create regular expressions for the URLs
    //const inventoryRegex = new RegExp('/[a-z]{2}/main/inventory');
    const inventoryNewRegex = new RegExp('/[a-z]{2}/main/inventory-new');
    @@ -24,141 +29,154 @@
    }
    console.log("3min PP boosters activation script loaded");

    function getPPBoosterCount() {
    const listItem = document.getElementById("inventory_100_prestige_points_1_180_temporary_boosters");
    if (listItem) {
    const boosterCountElement = listItem.querySelector("#stock__");
    if (boosterCountElement) {
    const textContent = boosterCountElement.textContent.trim();
    const boostersCount = textContent.replace(/[^0-9]/g, '');
    return parseInt(boostersCount, 10);
    }
    }
    return 0;
    }
    function addEmojiToBoostersElement(boostersElement) {
    const emoji = document.createElement('div');
    emoji.textContent = '⚠️'; // Yellow triangle emoji
    emoji.style.position = 'absolute';
    emoji.style.cursor = 'pointer';
    emoji.style.fontSize = '24px';
    emoji.style.right = '5px';
    emoji.style.top = '0';
    emoji.style.zIndex = '1000';

    getBoostersCount()
    .then(boostersCount => {
    if (boostersCount === 0) {
    console.log('No boosters found');
    return;
    }

    function addEmojiToBooster(ppBoosterCount) {
    const listItem = document.getElementById("inventory_100_prestige_points_1_180_temporary_boosters");
    if (listItem) {
    // Create the emoji element
    const emoji = document.createElement('div');
    emoji.textContent = '⚠️'; // Yellow triangle emoji
    emoji.style.position = 'absolute';
    emoji.style.cursor = 'pointer';
    emoji.style.fontSize = '24px'; // Adjust size as needed
    emoji.style.right = '5px'; // Adjust positioning as needed
    emoji.style.top = '0'; // Adjust positioning as needed
    emoji.style.zIndex = '1000'; // Ensure it's on top

    // Add the click event listener to the emoji
    emoji.addEventListener('click', function () {
    const confirmMessage = 'Do you want to activate them all?\n' +
    'Please do not close the browser tab until all boosters are active. ' +
    'The process will end in approximately ' + (ppBoosterCount * 0.5) + ' seconds.';
    if (confirm(confirmMessage)) {
    onConfirmYes(ppBoosterCount);
    } else {
    onConfirmNo();
    }
    'The process will end in approximately ' + (boostersCount * timeoutBetweenActivations / 1000) + ' seconds.';

    emoji.addEventListener('click', () => {
    if (confirm(confirmMessage)) {
    activateBoosters(boostersCount);
    } else {
    console.log('Boosters activation canceled');
    }
    });
    })
    .catch(error => {
    console.error('Error in getBoostersCount:', error);
    });

    // Append the emoji to the <li> element
    listItem.style.position = 'relative'; // Ensure the listItem can contain absolute elements
    listItem.appendChild(emoji);
    } else {
    console.error('Booster list item not found.');
    }
    //boostersElement.style.position = 'relative';
    boostersElement.appendChild(emoji);
    }

    function onConfirmYes(ppBoosterCount) {
    function activateBoosters(boostersCount) {
    updateActivationProgress(boostersCount);

    activateBooster()
    .then(data => {
    const boostersLeft = data?.inventoryItems?.finalProducts?.items?.['100_prestige_points_1_180']?.amount ?? 0;
    if (boostersLeft === 0) {
    console.log('All boosters activated. Exiting...');
    return;
    }
    setTimeout(() => activateBoosters(boostersLeft), timeoutBetweenActivations);
    })
    .catch(error => {
    console.error('Error activating boosters:', error);
    })
    }

    const timeout = 5000; // 0.5 second timeout between activations
    function activateBooster() {
    return fetch('https://www.erepublik.com/en/economy/activateBooster', {
    method: 'POST',
    headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
    'Accept': 'application/json, text/plain, */*',
    'Origin': 'https://www.erepublik.com',
    'Referer': 'https://www.erepublik.com/en/main/inventory-new',
    'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36',
    'X-Requested-With': 'XMLHttpRequest',
    },
    body: `type=prestige_points&quality=1&duration=180&fromInventory=true&_token=${_token}`
    }).then(response => {
    if (!response.ok) {
    throw new Error(`HTTP error! status: ${response.status}`);
    }
    return response.json();
    }).catch(error => {
    console.error('Error activating booster:', error);
    });
    }

    function updateProgress(boostersLeft, timeLeft) {
    const progressText = `Boosters left to activate: ${boostersLeft}. Estimated time left: ${timeLeft.toFixed(1)} seconds.`;
    console.log(progressText); // Replace this with DOM manipulation to show progress to the user
    // You could create a progress element and update its text content with progressText
    async function getBoostersCount() {
    try {
    const data = await getInventoryJson();
    return countSpecificBooster(data, '100_prestige_points_1_180_temporary');
    } catch (error) {
    console.error('Error in getBoostersCount:', error);
    throw error; // re-throwing error so it can be handled in the caller
    }
    }

    function countSpecificBooster(activationBoosterResponse, boosterId) {
    let count = 0;

    function activateBooster(boostersLeft) {
    if (boostersLeft <= 0) {
    console.log('All boosters activated!');
    return;
    activationBoosterResponse.forEach(category => {
    if (category.items && Array.isArray(category.items)) {
    category.items.forEach(item => {
    if (item.id === boosterId) {
    count = item.amount;
    }
    });
    }
    });

    console.log(`There are ${count} boosters of type ${boosterId}`);
    return count;
    }

    const erpk = erepublik.settings.pomelo.authToken;
    const _token = SERVER_DATA.csrfToken;
    console.log(`erpk: ${erpk}, _token: ${_token}`);

    fetch('https://www.erepublik.com/en/economy/activateBooster', {
    method: 'POST',
    headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
    'Accept': 'application/json, text/plain, */*',
    'Origin': 'https://www.erepublik.com',
    'Referer': 'https://www.erepublik.com/en/main/inventory-new',
    'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36',
    'X-Requested-With': 'XMLHttpRequest',
    },
    body: `type=prestige_points&quality=1&duration=180&fromInventory=true&_token=${_token}`
    }).then(response => {
    function getInventoryJson() {
    return fetch('https://www.erepublik.com/en/economy/inventory-json', {
    method: 'GET',
    headers: {
    'Accept': 'application/json, text/plain, */*',
    'Origin': 'https://www.erepublik.com',
    'Referer': 'https://www.erepublik.com/en/main/inventory-new',
    'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36',
    'X-Requested-With': 'XMLHttpRequest'
    }
    })
    .then(response => {
    if (!response.ok) {
    throw new Error(`HTTP error! status: ${response.status}`);
    }
    return response.json();
    }).then(data => {
    console.log(data);
    // Handle the response JSON data
    const newBoostersLeft = data.inventoryItems.finalProducts.items['100_prestige_points_1_180'].amount;
    const newTimeLeft = newBoostersLeft * (timeout / 1000); // Update the time left
    updateProgress(newBoostersLeft, newTimeLeft); // Update the user on the progress

    // Schedule the next activation
    setTimeout(() => activateBooster(newBoostersLeft), timeout); // 0.5 second delay before the next activation
    }).catch(error => {
    console.error('Error activating booster:', error);
    });
    //updateProgress(boostersLeft - 1, (boostersLeft - 1) * (timeout / 1000));
    //setTimeout(() => activateBooster(boostersLeft - 1), timeout);
    }


    const timeLeft = ppBoosterCount * (timeout / 1000); // Calculate the estimated time left
    updateProgress(ppBoosterCount, timeLeft); // Update the user on the progress

    // Start the activation
    activateBooster(ppBoosterCount);
    }

    function onConfirmNo() {
    console.log('No clicked');
    function updateActivationProgress(boostersLeft) {
    const timeLeft = boostersLeft * timeoutBetweenActivations / 1000; // in seconds
    const progressText = `Boosters left: ${boostersLeft}, time left: ${timeLeft} seconds`;
    console.log(progressText);
    }

    let _3min_pp_boosters_counter = 0;
    const max_3min_pp_boosters_attempts = 5;

    function checkForChanges() {
    const ppBoosterCount = getPPBoosterCount();
    let boostersLookupCounter = 1;
    const boostersLookupAttempts = 5;

    if (ppBoosterCount > 0) {
    addEmojiToBooster(ppBoosterCount);
    async function boostersElementLookup() {
    const boostersElement = document.getElementById("inventory_100_prestige_points_1_180_temporary_boosters");
    if (boostersElement) {
    addEmojiToBoostersElement(boostersElement)
    return;
    }

    if (_3min_pp_boosters_counter >= max_3min_pp_boosters_attempts) {
    console.log(`PP Booster Count: ${ppBoosterCount}. Stop pooling`);
    if (!boostersElement && boostersLookupCounter >= boostersLookupAttempts) {
    console.log("Boosters element not found, exiting");
    return;
    }

    _3min_pp_boosters_counter++;
    console.log('Attempt #' + _3min_pp_boosters_counter);

    // Schedule the next check
    setTimeout(checkForChanges, 500); // Check every 0.5 second
    boostersLookupCounter++;
    console.log(`Boosters element not found, attempt ${boostersLookupCounter}/${boostersLookupAttempts} in 500ms`);
    setTimeout(boostersElementLookup, 500);
    }

    checkForChanges();
    boostersElementLookup()

    })();


  2. driversti created this gist Jan 7, 2024.
    164 changes: 164 additions & 0 deletions auto_activation_3min_pp_boosters.userscript.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,164 @@
    // ==UserScript==
    // @name 3min PP boosters activation
    // @namespace https://www.erepublik.com/
    // @version 1.0
    // @description Activate all 3min PP boosters with one click.
    // @copyright YOU ARE NOT ALLOWED TO DISCLOSE THIS SCRIPT TO OTHERS WITHOUT MY PERMISSION!!!
    // @author driversti https://www.erepublik.com/en/citizen/profile/4690052
    // @match https://www.erepublik.com/*
    // @icon https://www.google.com/s2/favicons?sz=64&domain=erepublik.com
    // @grant none
    // ==/UserScript==

    (function () {
    'use strict';

    // Create regular expressions for the URLs
    //const inventoryRegex = new RegExp('/[a-z]{2}/main/inventory');
    const inventoryNewRegex = new RegExp('/[a-z]{2}/main/inventory-new');

    // Check if the current URL matches one of the regular expressions
    if (!inventoryNewRegex.test(window.location.href)) {
    // console.log("Not on inventory page, exiting");
    return;
    }
    console.log("3min PP boosters activation script loaded");

    function getPPBoosterCount() {
    const listItem = document.getElementById("inventory_100_prestige_points_1_180_temporary_boosters");
    if (listItem) {
    const boosterCountElement = listItem.querySelector("#stock__");
    if (boosterCountElement) {
    const textContent = boosterCountElement.textContent.trim();
    const boostersCount = textContent.replace(/[^0-9]/g, '');
    return parseInt(boostersCount, 10);
    }
    }
    return 0;
    }

    function addEmojiToBooster(ppBoosterCount) {
    const listItem = document.getElementById("inventory_100_prestige_points_1_180_temporary_boosters");
    if (listItem) {
    // Create the emoji element
    const emoji = document.createElement('div');
    emoji.textContent = '⚠️'; // Yellow triangle emoji
    emoji.style.position = 'absolute';
    emoji.style.cursor = 'pointer';
    emoji.style.fontSize = '24px'; // Adjust size as needed
    emoji.style.right = '5px'; // Adjust positioning as needed
    emoji.style.top = '0'; // Adjust positioning as needed
    emoji.style.zIndex = '1000'; // Ensure it's on top

    // Add the click event listener to the emoji
    emoji.addEventListener('click', function () {
    const confirmMessage = 'Do you want to activate them all?\n' +
    'Please do not close the browser tab until all boosters are active. ' +
    'The process will end in approximately ' + (ppBoosterCount * 0.5) + ' seconds.';
    if (confirm(confirmMessage)) {
    onConfirmYes(ppBoosterCount);
    } else {
    onConfirmNo();
    }
    });

    // Append the emoji to the <li> element
    listItem.style.position = 'relative'; // Ensure the listItem can contain absolute elements
    listItem.appendChild(emoji);
    } else {
    console.error('Booster list item not found.');
    }
    }

    function onConfirmYes(ppBoosterCount) {

    const timeout = 5000; // 0.5 second timeout between activations

    function updateProgress(boostersLeft, timeLeft) {
    const progressText = `Boosters left to activate: ${boostersLeft}. Estimated time left: ${timeLeft.toFixed(1)} seconds.`;
    console.log(progressText); // Replace this with DOM manipulation to show progress to the user
    // You could create a progress element and update its text content with progressText
    }

    function activateBooster(boostersLeft) {
    if (boostersLeft <= 0) {
    console.log('All boosters activated!');
    return;
    }

    const erpk = erepublik.settings.pomelo.authToken;
    const _token = SERVER_DATA.csrfToken;
    console.log(`erpk: ${erpk}, _token: ${_token}`);

    fetch('https://www.erepublik.com/en/economy/activateBooster', {
    method: 'POST',
    headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
    'Accept': 'application/json, text/plain, */*',
    'Origin': 'https://www.erepublik.com',
    'Referer': 'https://www.erepublik.com/en/main/inventory-new',
    'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36',
    'X-Requested-With': 'XMLHttpRequest',
    },
    body: `type=prestige_points&quality=1&duration=180&fromInventory=true&_token=${_token}`
    }).then(response => {
    if (!response.ok) {
    throw new Error(`HTTP error! status: ${response.status}`);
    }
    return response.json();
    }).then(data => {
    console.log(data);
    // Handle the response JSON data
    const newBoostersLeft = data.inventoryItems.finalProducts.items['100_prestige_points_1_180'].amount;
    const newTimeLeft = newBoostersLeft * (timeout / 1000); // Update the time left
    updateProgress(newBoostersLeft, newTimeLeft); // Update the user on the progress

    // Schedule the next activation
    setTimeout(() => activateBooster(newBoostersLeft), timeout); // 0.5 second delay before the next activation
    }).catch(error => {
    console.error('Error activating booster:', error);
    });
    //updateProgress(boostersLeft - 1, (boostersLeft - 1) * (timeout / 1000));
    //setTimeout(() => activateBooster(boostersLeft - 1), timeout);
    }


    const timeLeft = ppBoosterCount * (timeout / 1000); // Calculate the estimated time left
    updateProgress(ppBoosterCount, timeLeft); // Update the user on the progress

    // Start the activation
    activateBooster(ppBoosterCount);
    }

    function onConfirmNo() {
    console.log('No clicked');
    }

    let _3min_pp_boosters_counter = 0;
    const max_3min_pp_boosters_attempts = 5;

    function checkForChanges() {
    const ppBoosterCount = getPPBoosterCount();

    if (ppBoosterCount > 0) {
    addEmojiToBooster(ppBoosterCount);
    return;
    }

    if (_3min_pp_boosters_counter >= max_3min_pp_boosters_attempts) {
    console.log(`PP Booster Count: ${ppBoosterCount}. Stop pooling`);
    return;
    }

    _3min_pp_boosters_counter++;
    console.log('Attempt #' + _3min_pp_boosters_counter);

    // Schedule the next check
    setTimeout(checkForChanges, 500); // Check every 0.5 second
    }

    checkForChanges();

    })();