Elethor General Purpose

Provides some general additions to Elethor

目前為 2021-01-15 提交的版本,檢視 最新版本

// ==UserScript==
// @name         Elethor General Purpose
// @description  Provides some general additions to Elethor
// @namespace    https://www.elethor.com/
// @version      1.5.0
// @author       Anders Morgan Larsen (Xortrox)
// @match        https://elethor.com/*
// @match        https://www.elethor.com/*
// @run-at       document-start
// @grant        none
// ==/UserScript==

(function() {
    const currentUserData = {};

    const moduleName = 'Elethor General Purpose';
    const version = '1.5.0'

    const profileURL = '/profile/';

    function initializeXHRHook() {
        let rawSend = XMLHttpRequest.prototype.send;

        XMLHttpRequest.prototype.send = function() {
            if (!this._hooked) {
                this._hooked = true;

                this.addEventListener('readystatechange', function() {
                    if (this.readyState === XMLHttpRequest.DONE) {
                        setupHook(this);
                    }
                }, false);
            }
            rawSend.apply(this, arguments);
        }

        function setupHook(xhr) {
            if (window.elethorGeneralPurposeOnXHR) {
                const e = new Event('EGPXHR');
                e.xhr = xhr;

                window.elethorGeneralPurposeOnXHR.dispatchEvent(e);
            }
        }
        window.elethorGeneralPurposeOnXHR = new EventTarget();

        console.log(`[${moduleName} v${version}] XHR Hook initialized.`);
    }

    function initializeUserLoadListener() {
        elethorGeneralPurposeOnXHR.addEventListener('EGPXHR', function (e) {
            if (e && e.xhr
                && e.xhr.responseURL
                && e.xhr.responseURL.endsWith
                && e.xhr.responseURL.endsWith('/game/user')
            ) {
                try {
                    const userData = JSON.parse(e.xhr.responseText);

                    if (userData) {
                        for (const key of Object.keys(userData)) {
                            currentUserData[key] = userData[key];
                        }
                    }
                } catch (e) {
                    console.log(`[${moduleName} v${version}] Error parsing userData:`, e);
                }

            }
        });

        console.log(`[${moduleName} v${version}] User Load Listener initialized.`);
    }

    function initializeToastKiller() {
        document.addEventListener('click', function(e) {
            if (e.target
                && e.target.className
                && e.target.className.includes
                && e.target.className.includes('toasted')
            ) {
                e.target.remove();
            }
        });

        console.log(`[${moduleName} v${version}] Toast Killer initialized.`);
    }

    function initializeInventoryStatsLoadListener() {
        elethorGeneralPurposeOnXHR.addEventListener('EGPXHR', function (e) {
            if (e && e.xhr
                && e.xhr.responseURL
                && e.xhr.responseURL.endsWith
                && e.xhr.responseURL.endsWith('/game/inventory/stats')
            ) {
                setTimeout(() => {
                    updateEquipmentPercentageSummary();

                    setTimeout(updateInventoryStatsPercentages, 1000);
                });
            }
        });

        console.log(`[${moduleName} v${version}] Inventory Stats Load Listener initialized.`);
    }

    function initializeProfileLoadListener2() {
        elethorGeneralPurposeOnXHR.addEventListener('EGPXHR', async function (e) {
            if (e && e.xhr
                && e.xhr.responseURL
                && e.xhr.responseURL.includes
                && e.xhr.responseURL.includes(profileURL)
            ) {
                const url = e.xhr.responseURL;
                const path = url.substr(url.indexOf(profileURL));

                // We know we have a profile lookup, and not user-data load if the length differs.
                if (path.length > profileURL.length) {
                    const userId = Number(path.substr(path.lastIndexOf('/') + 1));
                    console.log('Inspected userId:', userId);
                    console.log('Current user:', currentUserData.user.id);

                    const difference = await getExperienceDifference(currentUserData.user.id, userId);

                    console.log('Difference:', difference);
                    console.log(e);
                }
            }
        });

        console.log(`[${moduleName} v${version}] Profile Load Listener initialized.`);
    }

    function updateEquipmentPercentageSummary() {
        document.querySelector('.is-equipment>div>div').setAttribute('style', 'width: 50%')
        let percentagesTable = document.querySelector('#egpPercentagesSummary')
        if (!percentagesTable){
            percentagesTable = document.querySelector('.is-equipment>div>div:nth-child(2)').cloneNode(true);
            percentagesTable.setAttribute('style', 'width: 25%');
            percentagesTable.id='egpPercentagesSummary';
            document.querySelector('.is-equipment>div').appendChild(percentagesTable);

            for (const child of percentagesTable.children[0].children) {
                if (child && child.children && child.children[0]) {
                    child.children[0].remove();
                }
            }

            document.querySelector('#egpPercentagesSummary>table>tr:nth-child(8)').setAttribute('style', 'height:43px');
        }
    }

    function getStatSummary(equipment) {
        const summary = {
            base: {},
            energizements: {}
        };

        if (equipment) {
            for (const key of Object.keys(equipment)) {
                const item = equipment[key];

                /**
                 * Sums base attributes by name
                 * */
                if (item && item.attributes) {
                    for (const attributeName of Object.keys(item.attributes)) {
                        const attributeValue = item.attributes[attributeName];

                        if (!summary.base[attributeName]) {
                            summary.base[attributeName] = 0;
                        }

                        summary.base[attributeName] += attributeValue;
                    }
                }

                /**
                 * Sums energizements by stat name
                 * */
                if (item && item.upgrade && item.upgrade.energizements) {
                    for (const energizement of item.upgrade.energizements) {
                        if (!summary.energizements[energizement.stat]) {
                            summary.energizements[energizement.stat] = 0;
                        }

                        summary.energizements[energizement.stat] += Number(energizement.boost);
                    }
                }
            }
        }

        return summary;
    }

    function updateInventoryStatsPercentages() {
        let percentagesTable = document.querySelector('#egpPercentagesSummary')
        if (percentagesTable && currentUserData && currentUserData.equipment){
            const statSummary = getStatSummary(currentUserData.equipment);

            const baseKeys = Object.keys(statSummary.base);
            const energizementKeys = Object.keys(statSummary.energizements);

            let allKeys = baseKeys.concat(energizementKeys);
            const filterUniques = {};
            for (const key of allKeys){
                filterUniques[key] = true;
            }
            allKeys = Object.keys(filterUniques);
            allKeys.sort();

            allKeys.push('actions');

            const tableRows = percentagesTable.children[0].children;

            for(const row of tableRows) {
                if (row
                    && row.children
                    && row.children[0]
                    && row.children[0].children[0]
                ) {
                    const rowText = row.children[0].children[0];
                    rowText.innerText = '';
                }
            }

            let rowIndex = 0;
            for (const key of allKeys) {
                if (key === 'puncture') {
                    continue;
                }

                const row = tableRows[rowIndex];
                if (row
                    && row.children
                    && row.children[0]
                    && row.children[0].children[0]
                ) {
                    const rowText = row.children[0].children[0];

                    const rowBase = statSummary.base[key] || 0;
                    const rowEnergizement = (statSummary.energizements[key] || 0);
                    const rowEnergizementPercentage = (statSummary.energizements[key] || 0) * 100;

                    if (key.startsWith('+')) {
                        rowText.innerText = `${key} per 10 levels: ${rowEnergizement}`;
                    } else if (key === 'actions') {
                        const actions = currentUserData.user.bonus_actions || 0;
                        rowText.innerText = `Bonus Actions: ${actions}`;
                    } else {
                        rowText.innerText = `${key}: ${rowBase} (${rowEnergizementPercentage.toFixed(0)}%)`;
                    }

                    rowIndex++;
                }
            }
        }
    }

    function initializeLocationChangeListener() {
        let previousLocation = window.location.href;

        window.elethorGeneralPurposeOnLocationChange = new EventTarget();

        window.elethorLocationInterval = setInterval(() => {
            if (previousLocation !== window.location.href) {
                previousLocation = window.location.href;

                const e = new Event('EGPLocation');
                e.newLocation = window.location.href;
                window.elethorGeneralPurposeOnLocationChange.dispatchEvent(e);
            }

        }, 500);

        console.log(`[${moduleName} v${version}] Location Change Listener initialized.`);
    }

    function getProfileCombatElement() {
        const skillElements = document.querySelectorAll('.is-skill div>span.has-text-weight-bold');
        for (const skillElement of skillElements) {
            if (skillElement.innerText.includes('Combat')) {
                return skillElement;
            }
        }
    }

    function updateXPTracker(difference) {
        const combatElement = getProfileCombatElement();
        if (!combatElement) {
            return;
        }

        if (difference > 0) {
            combatElement.setAttribute('data-combat-experience-ahead', `(+${difference})`);
            combatElement.setAttribute('style', `color:lime`);
        } else {
            combatElement.setAttribute('data-combat-experience-ahead', `(${difference})`);
            combatElement.setAttribute('style', `color:red`);
        }
    }

    function initializeProfileLoadListener() {
        let css = 'span[data-combat-experience-ahead]::after { content: attr(data-combat-experience-ahead); padding: 12px;}';
        appendCSS(css);
        window.elethorGeneralPurposeOnLocationChange.addEventListener('EGPLocation', async function (e) {
            if (e && e.newLocation) {
                if(e.newLocation.includes('/profile/')) {
                    console.log('Profile view detected:', e);
                    const url = e.newLocation;
                    const path = url.substr(url.indexOf(profileURL));

                    // We know we have a profile lookup, and not user-data load if the length differs.
                    if (path.length > profileURL.length) {
                        const userId = Number(path.substr(path.lastIndexOf('/') + 1));

                        const difference = await getExperienceDifference(userId, currentUserData.user.id);

                        updateXPTracker(difference);
                    }
                }
            }
        });

        console.log(`[${moduleName} v${version}] Profile Load Listener initialized.`);
    }

    async function getUser(id) {
        const result = await window.axios.get(`/game/user/${id}?egpIgnoreMe=true`);
        return result.data;
    }

    function getUserCombatStats(user) {
        for (const skill of user.skills) {
            if (skill.name === 'combat') {
                return skill.pivot;
            }
        }
    }

    async function getExperienceDifference(userId1, userId2) {
        const [user1, user2] = await Promise.all([
            getUser(userId1),
            getUser(userId2)
        ]);

        const combatStats1 = getUserCombatStats(user1);
        const combatStats2 = getUserCombatStats(user2);

        return combatStats2.experience - combatStats1.experience;
    }

    (function run() {
        initializeToastKiller();
        initializeXHRHook();
        initializeUserLoadListener();
        initializeInventoryStatsLoadListener();
        initializeLocationChangeListener();
        initializeProfileLoadListener();

        console.log(`[${moduleName} v${version}] Loaded.`);
    })();

    (async function loadRerollDisableButtonModule() {
        async function waitForEcho() {
            return new Promise((resolve, reject) => {
                const interval = setInterval(() => {
                    if (window.Echo) {
                        clearInterval(interval);
                        resolve();
                    }
                }, 100);
            });
        }

        async function waitForUser() {
            return new Promise((resolve, reject) => {
                const interval = setInterval(() => {
                    if (currentUserData.user && currentUserData.user.id !== undefined) {
                        clearInterval(interval);
                        resolve();
                    }
                }, 100);
            });
        }

        await waitForEcho();
        await waitForUser();

        elethorGeneralPurposeOnXHR.addEventListener('EGPXHR', async function (e) {
            if (e && e.xhr && e.xhr.responseURL) {
                if(e.xhr.responseURL.includes('/game/energize')) {
                    const itemID = e.xhr.responseURL.substr(e.xhr.responseURL.lastIndexOf('/')+1);
                    window.lastEnergizeID = Number(itemID);
                }
            }
        });
    })();

    (function loadResourceNodeUpdater() {
        function updateExperienceRates() {
            document.querySelectorAll('.is-resource-node').forEach(visualizeResourceNodeExperienceRates);

            function visualizeResourceNodeExperienceRates(node) {
                const purity = getNodePurityPercentage(node);
                const density = getNodeDensityPercentage(node);
                const experience = getNodeExperience(node);
                const ore = 16;
                const experienceRate = getExperienceRate(density, experience);
                const oreRate = getOreRate(density, purity, ore);

                node.children[0].setAttribute('data-after', `${experienceRate} xp/h ${oreRate} ore/h`);
            }

            function getNodePurityPercentage(node) {
                const column = node.children[0].children[2];
                const label = column.getElementsByClassName('has-text-weight-bold')[0].parentElement;
                const percentage = Number(label.innerText.replace('%','').split(':')[1])
                return percentage;
            }

            function getNodeDensityPercentage(node) {
                const column = node.children[0].children[1];
                const label = column.getElementsByClassName('has-text-weight-bold')[0].parentElement;
                const percentage = Number(label.innerText.replace('%','').split(':')[1])
                return percentage;
            }

            function getNodeExperience(node) {
                const column = node.children[0].children[3];
                const label = column.getElementsByClassName('has-text-weight-bold')[0].parentElement;
                const value = Number(label.innerText.replace('%','').split(':')[1])
                return value;
            }

            function getExperienceRate(density, experience) {
                return Number((3600 / (60 / (density / 100)) * experience).toFixed(3));
            }

            function getOreRate(density, purity, ore) {
                return Number((3600 / (60 / (density / 100)) * (purity / 100) * ore).toFixed(3));
            }
        }

        updateExperienceRates();
        window.elethorResourceInterval = setInterval(updateExperienceRates, 500);
        initializeResourceNodeView();

        async function initializeResourceNodeView() {
            await waitForField(document, 'head');

            let css = '.columns.is-mobile.is-size-7-mobile::after { content: attr(data-after); padding: 12px;}';

            appendCSS(css);
        }

        async function waitForField(target, field) {
            return new Promise((resolve, reject) => {
                const interval = setInterval(() => {
                    if (target[field] !== undefined) {
                        clearInterval(interval);
                        resolve();
                    }
                }, 100);
            });
        }
    })();

    function appendCSS(css) {
        let head = document.head || document.getElementsByTagName('head')[0];
        let style = document.createElement('style');

        head.appendChild(style);

        style.type = 'text/css';
        if (style.styleSheet){
            // This is required for IE8 and below.
            style.styleSheet.cssText = css;
        } else {
            style.appendChild(document.createTextNode(css));
        }
    }
})();