Hello There, Guest! Register

Misc Report Sharing Script
#1
This Script aids in Sharing Reports

execute the script while viewing a report.
You can either copy the report that is already formatted with bbcode to share on internal tribe forum or select a player name and mail the report to them.

Script works well for scouting now but will not show buildings in the report just troops.


Code:
javascript:(function() {
    const currentUrl = window.location.href;
    const urlParams = new URLSearchParams(window.location.search);
    const server = currentUrl.split('/')[2];
    const village = urlParams.get('village');

    if (!currentUrl.includes('=report') || !currentUrl.includes('view=')) {
        alert('Please run this script on a report page.');
        return;
    }

    const popup = document.createElement('div');
    popup.id = 'carbon-report-sharing';
    popup.style.position = 'fixed';
    popup.style.top = '50%';
    popup.style.left = '50%';
    popup.style.transform = 'translate(-50%, -50%)';
    popup.style.backgroundColor = '#f4e3c7';
    popup.style.border = '2px solid #a9865e';
    popup.style.padding = '20px';
    popup.style.zIndex = 10000;
    popup.style.width = '600px';
    popup.style.fontFamily = 'Courier New, monospace';
    document.body.appendChild(popup);

    const title = document.createElement('h2');
    title.innerText = 'Carbon\'s Report Sharing';
    title.style.color = '#54361c';
    title.style.borderBottom = '1px solid #a9865e';
    title.style.paddingBottom = '10px';
    popup.appendChild(title);

    const playerDropdown = document.createElement('select');
    playerDropdown.id = 'player-names';
    playerDropdown.style.width = '100%';
    playerDropdown.style.marginBottom = '10px';
    popup.appendChild(playerDropdown);

    const reportTextArea = document.createElement('textarea');
    reportTextArea.id = 'report-bbcode';
    reportTextArea.rows = 15;
    reportTextArea.style.width = '100%';
    reportTextArea.style.backgroundColor = '#fff8e0';
    reportTextArea.style.border = '1px solid #a9865e';
    reportTextArea.style.color = '#000';
    reportTextArea.style.padding = '10px';
    popup.appendChild(reportTextArea);

    const buttonContainer = document.createElement('div');
    buttonContainer.style.marginTop = '10px';

    const mailButton = document.createElement('button');
    mailButton.innerText = 'Mail Report';
    mailButton.style.backgroundColor = '#d9c19f';
    mailButton.style.border = '1px solid #a9865e';
    mailButton.style.marginRight = '10px';
    mailButton.onclick = sendMail;
    buttonContainer.appendChild(mailButton);

    const cancelButton = document.createElement('button');
    cancelButton.innerText = 'Cancel';
    cancelButton.style.backgroundColor = '#d9c19f';
    cancelButton.style.border = '1px solid #a9865e';
    cancelButton.onclick = () => document.body.removeChild(popup);
    buttonContainer.appendChild(cancelButton);

    popup.appendChild(buttonContainer);

    fetchPlayerNames(server, village);

    displayReportBBCode();

    function fetchPlayerNames(server, village) {
        let page = 1;
        const playerNames = [];

        function fetchPage() {
            const rankingUrl = `https://${server}/game.php?village=${village}&screen=ranking&page=${page}`;

            fetch(rankingUrl)
                .then(response => response.text())
                .then(html => {
                    const parser = new DOMParser();
                    const doc = parser.parseFromString(html, 'text/html');

                    const links = doc.querySelectorAll('a[href*="screen=info_player"]');
                    links.forEach(link => {
                        const playerName = link.innerText.trim();
                        if (playerName && !playerNames.includes(playerName)) {
                            playerNames.push(playerName);
                            const option = document.createElement('option');
                            option.value = playerName;
                            option.text = playerName;
                            playerDropdown.appendChild(option);
                        }
                    });

                    const nextPageLink = doc.querySelector(`a[href*="page=${page + 1}"]`);
                    if (nextPageLink) {
                        page++;
                        fetchPage();
                    }
                })
                .catch(error => console.error('Error fetching player names:', error));
        }

        fetchPage();
    }

    function displayReportBBCode() {
        try {
            const attackerName = document.querySelector('#attack_info_att th a')?.innerText || 'Unknown Attacker';
            const attackerVillage = document.querySelector('#attack_info_att td a')?.innerText.match(/\((\d+\|\d+)\)/)?.[1] || 'Unknown Village';
            const attackerUnits = formatUnits('#attack_info_att_units');

            const defenderName = document.querySelector('#attack_info_def th a') 
                ? document.querySelector('#attack_info_def th a').innerText 
                : 'Barbarian Village';
            const defenderVillage = document.querySelector('#attack_info_def td a')?.innerText.match(/\((\d+\|\d+)\)/)?.[1] || 'Unknown Village';
            const defenderUnits = formatUnits('#attack_info_def_units');

            const haul = document.querySelector('#attack_results td')?.innerText.trim() || 'No haul data available';

            const scoutedResources = document.querySelector('#attack_spy_resources')?.innerText.trim();
            const scoutedBuildings = document.querySelector('#attack_spy_buildings_left')?.innerText.trim();

            let bbcode = `[b]The attacker has won[/b]\n\n`;
            bbcode += `[b]Attacker:[/b] [player]${attackerName}[/player]\n`;
            bbcode += `[b]Village:[/b] [village]${attackerVillage}[/village]\n\n`;
            bbcode += `[b]Quantity:[/b]\n${attackerUnits.quantity}\n`;
            bbcode += `[b]Losses:[/b]\n${attackerUnits.losses}\n\n`;
            bbcode += `[b]Defender:[/b] ${defenderName === 'Barbarian Village' ? defenderName : `[player]${defenderName}[/player]`}\n`;
            bbcode += `[b]Village:[/b] [village]${defenderVillage}[/village]\n\n`;
            bbcode += `[b]Quantity:[/b]\n${defenderUnits.quantity}\n`;
            bbcode += `[b]Losses:[/b]\n${defenderUnits.losses}\n\n`;
            bbcode += `[b]Haul:[/b] ${haul}`;

            if (scoutedResources) {
                bbcode += `\n\n[b]Scouted Resources:[/b]\n${scoutedResources}`;
            }

            if (scoutedBuildings) {
                bbcode += `\n\n[b]Scouted Buildings:[/b]\n${scoutedBuildings}`;
            }

            reportTextArea.value = bbcode.trim();
        } catch (error) {
            console.error('Error displaying report:', error);
            reportTextArea.value = 'Failed to fetch or display report data. Please check console for details.';
        }
    }

    function formatUnits(selector) {
        const rows = document.querySelectorAll(`${selector} tr`);
        if (rows.length < 3) {
            console.error('Error: Could not find expected unit rows.');
            return { quantity: 'N/A', losses: 'N/A' };
        }

        const quantities = Array.from(rows[1].querySelectorAll('td')).slice(1).map(td => td.innerText.trim());
        const losses = Array.from(rows[2].querySelectorAll('td')).slice(1).map(td => td.innerText.trim());

        let formattedQuantities = '';
        let formattedLosses = '';
        for (let i = 0; i < quantities.length; i++) {
            formattedQuantities += `${quantities[i].padStart(4, ' ')} `;
            formattedLosses += `${losses[i].padStart(4, ' ')} `;
        }

        return {
            quantity: formattedQuantities.trim(),
            losses: formattedLosses.trim()
        };
    }

    function sendMail() {
        const recipient = playerDropdown.value;
        const bbcode = reportTextArea.value;

        if (!recipient || !bbcode) {
            alert('Please select a player and ensure the report is correctly formatted.');
            return;
        }

        const mailUrl = `https://${server}/game.php?village=${village}&screen=mail&mode=new`;
        const newTab = window.open(mailUrl, '_blank');

        newTab.onload = function() {
            const toField = newTab.document.querySelector('input#to');
            const subjectField = newTab.document.querySelector('input#subject');
            const messageField = newTab.document.querySelector('textarea#message');
            const sendButton = newTab.document.querySelector('input[name="send"]');

            if (toField && subjectField && messageField && sendButton) {
                toField.value = recipient;
                subjectField.value = 'Check this report out';
                messageField.value = bbcode;
                sendButton.click();
            } else {
                alert('Failed to prepare the mail form.');
            }
        };
    }
})();
Reply


Possibly Related Threads...
Thread Author Replies Views Last Post
  Commands Carbon's Attack Script Generator Carbon 0 203 08-10-2024, 13:44
Last Post: Carbon

Forum Jump:


Users browsing this thread: 2 Guest(s)
Current time: 21-11-2024, 13:09