-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
78 lines (68 loc) · 2.25 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import fetch from "node-fetch";
import makeConfig from "./src/config.js";
const league = process.argv.slice(2)[0].replace('--league=', '');
const config = makeConfig(league);
const debug = config.VERBOSE;
const sample = config.LEAGUES_TO_SHOW;
const country = config.COUNTRY;
const leagueNumber = config.LEAGUE_NUMBER;
const startingId = config.STARTING_ID;
const total = config.TOTAL_LEAGUES_IN_DIVISION;
const printLine = msg => {
if (!debug) return;
console.log(msg);
};
const printStream = msg => process.stdout.write(`${msg} \r`);
let fetch_number = 1;
let res_number = 1;
const fetchHT = async (id) => {
const url = `https://www.hattrick.org/en-us/World/Series/?LeagueLevelUnitID=${id}`;
printStream(`FETCH #${fetch_number} <= ${url}`);
fetch_number++;
const res = await fetch(url);
const text = await res.text();
// "This series is ranked n1 of total"
const regRes = /<span id="ctl00_ctl00_CPContent_CPMain_lblSeriesRank">(.*)<\/span>/gm.exec(text);
if (!regRes) {
printStream(`RECREATE ${res_number} => ${id}, last`);
return { id, rankNumber: total };
}
const rankText = regRes[1];
const rankNumber = rankText.split(" ")[4];
printStream(`GOT ${res_number} => ${id}, ${rankNumber}`);
res_number++;
return { id, rankNumber };
};
let samplesFound = 0;
const leagues = [];
printLine(`Adding promises for each league (${total})`);
for (let n = 0; n < total + 1; ++n) {
const id = startingId + n;
printStream(`Promise for league #${id}`);
const l = await fetchHT(id);
leagues.push(l);
if (l.rankNumber > total - sample) {
samplesFound++;
if (samplesFound === sample){
printLine(`All sample found after ${n} fetchs`);
break;
}
}
}
const lastLeagues = [];
try {
for (let n = 0; n < leagues.length; ++n) {
const { id, rankNumber } = leagues[n];
if (rankNumber > total - sample) {
lastLeagues.push({ id, position: rankNumber });
}
}
let output = `Hattrick ${country} ${leagueNumber} division: last ${sample}\n=============================================\n`;
for (let n = 0; n < lastLeagues.length; ++n) {
const { id, position } = lastLeagues[n];
output += `League with ${id} is in position ${position} of ${total}.\n`;
}
console.log(output);
} catch (e) {
console.log(e);
}