-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscrape.js
More file actions
158 lines (128 loc) · 4.69 KB
/
Copy pathscrape.js
File metadata and controls
158 lines (128 loc) · 4.69 KB
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
import fs from "fs";
import fetch from "node-fetch";
import { parse } from "csv-parse/sync";
// URL do Google Sheets exportado como CSV
const SHEET_ID = "18VTy_8wcXHh-8zI-5KODC6Vk9JPb__LESdVKo2X78Mc";
const GID = "0";
const CSV_URL = `https://docs.google.com/spreadsheets/d/${SHEET_ID}/export?format=csv&gid=${GID}`;
async function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
function parsePrice(priceText) {
if (!priceText || priceText.trim() === "" || priceText === "-" || priceText.toLowerCase() === "n/a") {
return null;
}
// Remove vírgulas de milhares e espaços
const cleaned = priceText.toString().replace(/,/g, "").replace(/\s/g, "");
const num = Number(cleaned);
return isNaN(num) ? null : num;
}
async function scrape() {
await sleep(2000); // 2 segundos de delay por educação
const res = await fetch(CSV_URL, {
headers: {
"User-Agent": "Moonlighter-Price-Checker/1.0 (manual update; github)"
}
});
if (!res.ok) {
throw new Error(`HTTP error ${res.status}`);
}
const csvText = await res.text();
const rows = parse(csvText, {
relax_column_count: true,
skip_empty_lines: false
});
const DEBUG = process.env.DEBUG === "1";
const relics = [];
const seen = new Set();
// Primeira linha: nomes das regiões
const headerRow = rows[0] || [];
// Segunda linha: headers (Relic, Rarity, Cheap, Perfect, Expensive, Overpriced)
const columnHeaders = rows[1] || [];
// Identificar onde começam as colunas de cada região
// Cada região ocupa 6 colunas: Relic, Rarity, Cheap, Perfect, Expensive, Overpriced
// Procuramos por "Relic" na linha de headers para identificar o início de cada região
const regions = [];
for (let i = 0; i < columnHeaders.length; i++) {
if ((columnHeaders[i] || "").trim() === "Relic") {
// Tentar encontrar o nome da região na linha anterior (headerRow)
let regionName = (headerRow[i] || "").trim();
// Se não encontrou na mesma coluna, procurar nas colunas anteriores
if (!regionName || regionName === "") {
// Procurar nas colunas anteriores até encontrar algo
for (let j = i - 1; j >= 0 && j >= i - 6; j--) {
const candidate = (headerRow[j] || "").trim();
if (candidate && candidate !== "Relic" &&
!["Rarity", "Cheap", "Perfect", "Expensive", "Overpriced"].includes(candidate)) {
regionName = candidate;
break;
}
}
}
// Se ainda não encontrou, usar um nome padrão
if (!regionName || regionName === "") {
regionName = `Region_${regions.length + 1}`;
}
regions.push({
name: regionName,
startCol: i
});
}
}
if (DEBUG) {
console.log("DEBUG: Regiões encontradas:", regions);
}
// Processar linhas de dados (começando da linha 2, índice 2)
for (let rowIdx = 2; rowIdx < rows.length; rowIdx++) {
const row = rows[rowIdx] || [];
// Processar cada região
for (const region of regions) {
const relicName = (row[region.startCol] || "").trim();
const rarity = (row[region.startCol + 1] || "").trim();
// Se não tem nome de relic, pular
if (!relicName || relicName === "") {
continue;
}
const key = `${relicName}|${region.name}`;
// Pula se já vimos esta combinação relic+region
if (seen.has(key)) {
if (DEBUG) {
console.log(`DEBUG: Duplicata ignorada - ${key}`);
}
continue;
}
seen.add(key);
// Extrair todos os preços
const cheap = parsePrice(row[region.startCol + 2]);
const perfect = parsePrice(row[region.startCol + 3]);
const expensive = parsePrice(row[region.startCol + 4]);
const overpriced = parsePrice(row[region.startCol + 5]);
const parsedItem = {
relic: relicName,
rarity: rarity,
region: region.name,
prices: {
cheap: cheap,
perfect: perfect,
expensive: expensive,
overpriced: overpriced
}
};
// Manter compatibilidade com código antigo: adicionar price (perfect) no nível raiz
parsedItem.price = perfect;
if (DEBUG) {
console.log("DEBUG:", parsedItem);
}
relics.push(parsedItem);
}
}
fs.writeFileSync(
"data.js",
"const relics = " + JSON.stringify(relics, null, 2) + ";\n"
);
console.log(`OK — ${relics.length} relics updated`);
}
scrape().catch(err => {
console.error("Erro:", err);
process.exit(1);
});