-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.js
More file actions
240 lines (198 loc) · 8.12 KB
/
content.js
File metadata and controls
240 lines (198 loc) · 8.12 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
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
// content.js
// RarePatternsScanHelperExtension
// Copyright (C) 2025 Romanus101
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
(() => {
// Fixed delay per page (as before)
let WAIT_TIME = 6000; // 6000 because i see it optimal for not getting 429 err too quick
// Behavior switches
const REQUIRE_PATTERN = true; // игнорировать записи без паттерна
const MIN_SEED_LEN = 1; // минимальная длина паттерна (пустые не берём)
const CHECK_EVERY = 400; // частота опроса DOM на появление паттернов
const MAX_RENDER_WAIT = 4000; // максимум дополнительного ожидания появления паттернов (поверх WAIT_TIME)
// Selectors (centralized)
const SEL = {
pageInput: ".go_page input",
infoBar: ".info",
row: ".market_listing_row",
patternDiv: ".paint_seed_container .paint_seed_block div",
floatVal: ".itemfloat .value",
name: ".market_listing_item_name",
price: ".market_listing_price_with_fee",
nextBtnPrimary: "a.sih_button.next_page",
nextBtnFallback: "a.pagebtn[href*='start=']"
};
let foundPatterns = [];
let scannedPages = new Set();
let seenIds = new Set(); // дедуп по listingid
let stopRequested = false;
let inProgress = false;
// Commands from popup
chrome.runtime.onMessage.addListener((msg, _sender, sendResponse) => {
if (msg?.type === "start") {
if (inProgress) {
sendResponse?.({ status: "already_running" });
return true;
}
resetState();
inProgress = true;
// Подхватываем задержку из popup
if (msg.delay && Number.isFinite(msg.delay)) {
WAIT_TIME = msg.delay;
log(`⏱ Delay set to ${WAIT_TIME} ms`);
}
const totalPages = getTotalPages();
const current = getCurrentPageNumber();
log(`▶ Scanning started. Page ${current ?? "?"} of ~${totalPages}`);
sendProgress(`Start: page ${current ?? "?"} of ~${totalPages}`);
// Старт: подождём рендер паттернов на текущей странице, затем извлечение
waitFixedThenRenderCheck().then(() => {
extractPatterns();
goToNextPage(totalPages);
});
sendResponse?.({ status: "started" });
return true;
}
if (msg?.type === "stop") {
stopRequested = true;
sendProgress("Stop requested");
log("⏹ Stop requested");
sendResponse?.({ status: "stop_requested" });
return true;
}
});
function resetState() {
foundPatterns = [];
scannedPages.clear();
seenIds.clear();
stopRequested = false;
inProgress = false;
chrome.runtime.sendMessage({ type: "results", data: [] });
sendProgress("List cleared");
}
function sendProgress(text) {
chrome.runtime.sendMessage({ type: "progress", text });
}
function log(msg) {
console.log(msg);
}
function getCurrentPageNumber() {
const input = document.querySelector(SEL.pageInput);
const val = input ? parseInt(input.value.trim(), 10) : NaN;
return Number.isFinite(val) ? val : null;
}
function getTotalPages() {
const info = document.querySelector(SEL.infoBar);
if (!info) return 1;
// Берём все числа из строки
const nums = info.textContent.match(/\d+/g);
if (nums && nums.length >= 2) {
const total = parseInt(nums[1], 10);
return Number.isFinite(total) ? total : 1;
}
console.log("total pages found");
return 1;
}
function getNextButton() {
return document.querySelector(SEL.nextBtnPrimary) || document.querySelector(SEL.nextBtnFallback);
}
function sleep(ms) {
return new Promise((r) => setTimeout(r, ms));
}
// Wait the fixed time, then poll for pattern elements to appear (up to MAX_RENDER_WAIT)
async function waitFixedThenRenderCheck() {
// жёсткая пауза «как раньше»
await sleep(WAIT_TIME);
// доп. ожидание появления паттернов, если их ещё нет
const start = Date.now();
while (Date.now() - start < MAX_RENDER_WAIT) {
const hasPatterns = document.querySelector(SEL.patternDiv);
if (hasPatterns) return true;
await sleep(CHECK_EVERY);
}
// если не появились — всё равно продолжаем, но предупреждаем
sendProgress("Patterns not loading — continue with existing data");
return false;
}
function extractPatterns() {
const page = getCurrentPageNumber();
if (page == null) {
sendProgress("Page number not detected — skipping");
return;
}
if (scannedPages.has(page)) return;
scannedPages.add(page);
const rows = document.querySelectorAll(SEL.row);
if (!rows.length) {
sendProgress(`Page. ${page}: no elements ${SEL.row}`);
}
let added = 0;
rows.forEach((row) => {
const patternEl = row.querySelector(SEL.patternDiv);
const floatEl = row.querySelector(SEL.floatVal);
// Строгая фильтрация: без паттерна — игнор
const patternText = patternEl?.textContent?.trim() || "";
if (REQUIRE_PATTERN && patternText.length < MIN_SEED_LEN) return;
// Дедуп по listingid, если доступен
const idAttr = row.getAttribute("id") || "";
const idMatch = idAttr.match(/listing_(\d+)/);
const listingid = idMatch?.[1] || "";
if (listingid && seenIds.has(listingid)) return;
if (listingid) seenIds.add(listingid);
const name = row.querySelector(SEL.name)?.textContent?.trim() || "—";
const price = row.querySelector(SEL.price)?.textContent?.trim() || "—";
const float = floatEl?.textContent?.trim() || "—";
const result = { page, listingid, name, price, pattern: patternText, float };
foundPatterns.push(result);
added += 1;
console.log(
`%c🎯 Found: Page ${result.page} | ${result.name} | Pattern: ${result.pattern} | Float: ${result.float} | Price: ${result.price}`,
"color: limegreen; font-weight: bold;"
);
});
sendProgress(`Стр. ${page}: +${added}, total ${foundPatterns.length}`);
chrome.runtime.sendMessage({ type: "results", data: foundPatterns });
}
function goToNextPage(totalPages) {
if (stopRequested) return showSummary();
const page = getCurrentPageNumber();
if (page != null && page >= totalPages) return showSummary();
const nextBtn = getNextButton();
if (!nextBtn) {
sendProgress("Button Next not found - finishing");
return showSummary();
}
nextBtn.click();
sendProgress("Getting on the next page…");
// жёсткая пауза, затем проверка отрисовки паттернов
waitFixedThenRenderCheck().then(() => {
extractPatterns();
goToNextPage(totalPages);
});
//Progress bar
chrome.runtime.sendMessage({
type: "progress_page",
current: page,
total: totalPages
});
}
function showSummary() {
inProgress = false;
const total = foundPatterns.length;
console.log(`📊 Scanning done. Found ${total} skins with patterns.`);
sendProgress(`Done. Found ${total}`);
chrome.runtime.sendMessage({ type: "results", data: foundPatterns });
}
})();