hwmBattleLinks

Быстрые ссылки на итоги боя; начало, конец, чат боя

当前为 2023-12-02 提交的版本,查看 最新版本

// ==UserScript==
// @name           hwmBattleLinks
// @author         Tamozhnya1
// @namespace      Tamozhnya1
// @description    Быстрые ссылки на итоги боя; начало, конец, чат боя
// @version        4.0
// @encoding 	   utf-8
// @include        https://*heroeswm.ru/*
// @include        https://*lordswm.com/*
// @include        https://*hwmguide.ru/*
// @exclude        */rightcol.php*
// @exclude        */ch_box.php*
// @exclude        */chat*
// @exclude        */ticker.html*
// @exclude        */frames*
// @exclude        */brd.php*
// @exclude        */auction.php*
// @grant          GM_deleteValue
// @grant          GM_getValue
// @grant          GM_listValues
// @grant          GM_setValue
// @grant 		   GM.xmlHttpRequest
// @license        MIT
// ==/UserScript==

const isEn = document.documentElement.lang == "en";
if(typeof GM_deleteValue != 'function') {
	this.GM_getValue=function (key,def) {return localStorage[key] || def;};
	this.GM_setValue=function (key,value) {return localStorage[key]=value;};
	this.GM_deleteValue=function (key) {return delete localStorage[key];};
}
GM_addStyle(`
.hwmBattleLinksBattleResult { 
    position: absolute;
    border-style: solid;
    border-color: #000000;
    border-width: 2px;
    padding: 0;
    z-index: 3
}
.hwmBattleLinksBattleResult table, .hwmBattleLinksBattleResult td {background-image: none; text-align: left; border: 0px; margin: 0px; padding: 0px; line-height: 16px; border-collapse: separate;}
.hwmBattleLinksBattleResult td, .hwmBattleLinksBattleResult a, .hwmBattleLinksBattleResult b {FONT-SIZE: 9pt; COLOR: #592C08; FONT-FAMILY: verdana, geneva, arial cyr;}
.hwmBattleLinksBattleResult font {FONT-SIZE: 9pt; FONT-FAMILY: verdana, geneva, arial cyr}
`);
main();
function main() {
    const warRefs = document.querySelectorAll("a[href*='warid=']");
    for(const warRef of warRefs) {
        const warId = getUrlParamValue(warRef.href, "warid");
        const battleLinksSpan = document.createElement('span');
        battleLinksSpan.innerHTML = `&nbsp;[<a href="/war.php?lt=-1&warid=${warId}" target="_blank">#
</a>&nbsp;<a href="/battlechat.php?warid=${warId}" target="_blank">chat
</a>&nbsp;<a href="/war.php?warid=${warId}" target="_blank">$
</a>&nbsp;<a href="/battle.php?lastturn=-3&warid=${warId}" target="_blank">E</a>]`;

        warRef.parentNode.insertBefore(battleLinksSpan, warRef.nextSibling);
        warRef.addEventListener("click", function(e) { e.preventDefault(); showBattleResult(e, this); }, false);
    }
}
async function showBattleResult(event, warRef) {
    const warId = getUrlParamValue(warRef.href, "warid");
    Array.from(document.querySelectorAll("div[id^='battleContainer']")).forEach(x => x.style.display = "none");
    let battleContainer = document.getElementById(`battleContainer${warId}`);
    if(battleContainer) {
        battleContainer.style.display = "block";
        return;
    }
    battleContainer = addElement("div", document.body, { id: `battleContainer${warId}`, class: "hwmBattleLinksBattleResult" });
    battleContainer.innerHTML = `
<table cellspacing=4 cellpadding=0 bgcolor="#f5f3ea">
    <tr>
        <td align="left">warid: ${warId}
        &nbsp;[<a href="/war.php?lt=-1&warid=${warId}" target="_blank">#</a>
        &nbsp;<a href="/battlechat.php?warid=${warId}" target="_blank">chat</a>
        &nbsp;<a href="/war.php?warid=${warId}" target="_blank">$</a>
        &nbsp;<a href="/battle.php?lastturn=-3&warid=${warId}" target="_blank">E</a>]
        </td>
        <td width=100>
        </td>
        <td align="right" id="close_div_result" title="Close" style="text-align: right; cursor: pointer;">[x]
        </td>
    </tr>
    <tr>
        <td align="left" id="war_result_cont" colspan="3"><br>${getWheelImage()}
        </td>
    </tr>
</table>`;
    //warRef.parentNode.insertBefore(battleContainer, warRef.nextSibling);
    const warRefRect = warRef.getBoundingClientRect();
    battleContainer.style.left = `${warRefRect.left}px`;
    battleContainer.style.top = `${warRefRect.bottom + 1}px`;
    battleContainer.querySelector("#close_div_result").addEventListener("click", function() { battleContainer.style.display = "none"; }, false);
    
    const responseText = await getRequestText(`/battle.php?lastturn=-2&warid=${warId}`, "text/html; charset=UTF-8");
	const battleText = responseText.split(";/", 2)[0];
    const battleResultsStartIndex = responseText.indexOf("<font");
	const battleResultContainer = battleContainer.querySelector('#war_result_cont');
	if(battleResultsStartIndex == -1) {
		battleResultContainer.innerHTML = `<br>${isEn ? "Parse error." : "Результаты боя не найдены."}`;
		return;
	}
    let battleResults = responseText.substring(battleResultsStartIndex);
    const battleResultsParts = battleResults.split("|#", 2);
    let battleResult = battleResultsParts[0];
    if(isEn && battleResultsParts.length > 1 && battleResultsParts[1].startsWith("f_en")) {
        battleResult = battleResultsParts[1].substring(4);
    }
	battleResult = battleResult.replace(/ size="18"/g, '').replace(/font color="/g, 'font style="color: ');

	const battleResultParts = battleResult.split("<br");
    const regexp_exp = isEn ? /(\d+) exp/ : /(\d+) опыт/;
    const regexp_skill = isEn ? /(\d*\.?\d+) skill/ : /(\d*\.?\d+) умения/;
    let i = 0;
	for(const battleResultPart of battleResultParts) {
        const exp1 = regexp_exp.exec(battleResultPart);
		if(exp1) {
			const skillNumber = parseFloat(regexp_skill.exec(battleResultPart)[1]);
			if(skillNumber > 0) {
                battleResultParts[i] = `${battleResultPart} (${Math.round(parseFloat(exp1[1]) / skillNumber)}).`;
			}
		}
        i++;
	}
	battleResultContainer.innerHTML = '<br>' + battleResultParts.join("<br");
}
function getWheelImage() { return '<img border="0" align="absmiddle" height="11" src="https://dcdn.heroeswm.ru/css/loading.gif">'; }
function getUrlParamValue(url, paramName) { return (new URLSearchParams(url.split("?")[1])).get(paramName); }
function addElement(type, parent, data) {
    let el = createElement(type, data);
    if(parent) {
        parent.appendChild(el);
    }
    return el;
}
function createElement(type, data) {
    let el = document.createElement(type);
    if(data) {
        for(let key in data) {
            if(key == "innerText" || key == "innerHTML") {
                el[key] = data[key];
            } else {
                el.setAttribute(key, data[key]);
            }
        }
    }
    return el;
}
function GM_addStyle(css) {
    var head = document.getElementsByTagName('head')[0];
    if (!head)
      return;
    var style = document.createElement('style');
    style.type = 'text/css';
    style.innerHTML = css;
    head.appendChild(style);
}
function getRequestText(url, overrideMimeType = "text/html; charset=windows-1251") {
    return new Promise((resolve, reject) => {
        GM.xmlHttpRequest({ method: "GET", url: url, overrideMimeType: overrideMimeType,
            onload: function(response) { resolve(response.responseText); },
            onerror: function(error) { reject(error); }
        });
    });
}