Lulusek / Tribal wars farmrank generator - Family pl138

// ==UserScript==
// @name         Tribal wars farmrank generator - Family pl138
// @version      1.0
// @description  Rank generator for tribal wars (www.plemiona.pl/)
// @author       luluu9 
// @match        http://*.plemiona.pl/*
// @license      MIT
// ==/UserScript==


// By Lulusek - świat 136/138
function fetchPlayersOnPage(doc) {
    let rank = doc.querySelector("#in_a_day_ranking_table > tbody");
    let playersOnPage = [];
    for (let el of rank.children) {
        player = {
                "index": el.children[0].textContent, 
                "name": el.children[1].textContent.replace(`
                    
                                                    
                        
                        `, '').replace(`
                                            
                `,''), // bo wypełniony jest spacjami, nie wiem po co
                "tribe": el.children[2].textContent.replace(/\s/g,''),
                "score": el.children[3].textContent.replace(/\s/g,''),
                "date": el.children[4].textContent.replace(/\s/g,'')
                };
		if (player.index != "Ranking") { playersOnPage.push(player) };
    }
    return playersOnPage;
}

function getTextToPost(players) {
    script = "[spoiler=Ranking farmerów, "+new Date().toLocaleDateString()+`][table]
[**]LP[||]Gracz[||]Człon[||]Wynik[||]Ranking ogólny[/**]`;
    i = 1;
    for (let player of players) {
        script = script + "[*]" + i + "[|][player]" + player.name + "[/player][|][ally]" + player.tribe + "[/ally][|][b]" + player.score + "[/b][|]" + player.index + "\n";
	 	i++;
    }
    script = script + "[/table][/spoiler]";
    console.log(script);
    el = document.getElementById("generateRank");
    el.insertAdjacentHTML("afterend", '<textarea style="margin-bottom: -12px">'+script+'</textarea>')


} 
   
function getAllPlayers(amount=5, tribes=[], world=138) {
	allPlayers = [];
	matchPlayers = [];
	i = 0;
    get = function() { new Promise(function(ok, reject) {
            setTimeout(function() { ok("") }, i*5); // bo jeśli za dużo requestów w jednej chwili to wywala błąd
        }).then(function(result) {
            return new Promise(function(ok, reject) { // musimy zrobić to synchronicznie 
                urlOffset = i*25;
		if (urlOffset >= 3025) { console.log("Przestaje szukac (przeszukano 3000 wpisów)"); getTextToPost(matchPlayers); return; } // zapobiegamy infinite-loop
                url = 'https://pl'+world+'.plemiona.pl/guest.php?screen=ranking&mode=in_a_day&offset='+urlOffset+'&type=loot_res';
                data = $.get(url, function(data){ return data; });
                ok(data);
            })
        }).then(function(data) {
            return new Promise(function(ok, reject) {  
                parser = new DOMParser();
                ok([parser, data]);
            })
        }).then(function(result) {
            return new Promise(function(ok, reject) {
                doc = result[0].parseFromString(result[1], "text/html"); // tworzymy dokument ze stringa
                ok(doc);
            });
        }).then(function(doc) {
            return new Promise(function(ok, reject) {
                players = fetchPlayersOnPage(doc);
                ok(players);
            });
        }).then(function(players) { 
            return new Promise(function(ok, reject) {
                matchPlayers = matchPlayers.concat(players.sort(function(a, b) { 
                    return a.index - b.index;
                }).filter(player => tribes.includes(player.tribe))); // sortujemy po indeksach i wyrzucamy nie z plemienia
                console.log("Mam już " + matchPlayers.length + " graczy z podanych plemion");
				if (matchPlayers.length >= amount) { 
                    matchPlayers.length = amount; // żeby było dokładnie ile wynosi amount
                    getTextToPost(matchPlayers); 
                }
                else {
                    i++; 
                    get(); // za mało, więc powtarzamy z kolejną stroną
                }
            });
        })
	}
	get();
}

function generateRank() {
	tribesToGenerate = document.getElementById("tribesInput").value.replace(/\s/g, "").split(",");
	amount = parseInt(document.getElementById("amountInput").value)
	world = window.location.host.replace("pl", "").replace(".plemiona.pl", "");
	console.log(amount, tribesToGenerate, world);
	if (tribesToGenerate.length == 0) { return }
	if (isNaN(amount) || amount <= 0) { return }
	console.log(amount, tribesToGenerate, world)
	getAllPlayers(amount, tribesToGenerate, world)
}
                             
el = document.getElementById("header_info");
el.insertAdjacentHTML("afterbegin", '<table class="vis" style="margin-bottom: 5px"> <tr> <td>Plemiona: </td> <td> <input id="tribesInput" class="unitsInput" value="Family, F@mily, F4mily" style="width: 83px;"> </input> </td> </tr> <tr> <td>Ilość:</td> <td> <input id="amountInput" class="unitsInput" value="90", style="width: 83px;"> </input> </td> </tr> </table> <button id="generateRank" type="button" onclick="generateRank()" style="margin-bottom: 16px" class="btn"> Generuj </button>')