forked from jltwheeler/glasto-helper-2025
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpuppets.js
236 lines (219 loc) · 6.84 KB
/
puppets.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
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
// Logger configuration
const logger = require("./log");
// Tab class for managing individual browser tabs
const Tab = require("./tab");
class Puppets {
constructor(url, rateLimitPerMinute, registrationPageInnerText) {
this.tabs = [];
this.url = url;
this.refreshRateInMs = (60 / rateLimitPerMinute) * 1000;
this.registrationPageInnerText = registrationPageInnerText;
this.paused = false;
this.similarityThreshold = 75;
this.lastHighScorer = -1;
}
setPaused(paused) {
if (paused) {
logger.info(
"Pausing operation. Tabs will finish their current page load."
);
} else {
logger.info("Resuming operation.");
}
this.paused = paused;
}
getPaused() {
return this.paused;
}
async initializeTabs(tabQuantity) {
this.tabs = [];
for (let i = 0; i < tabQuantity; i++) {
let retries = 3;
let delay = 1000;
// Implements an exponential backoff retry when initializing tabs as I
// have found that spawning them too quickly can cause frequent crashes
while (retries > 0) {
try {
await this.sleep(delay);
let tab = new Tab(this.url);
await tab.initialiseTab();
this.tabs.push(tab);
logger.info({ tab: i, message: "Tab initialized successfully" });
break;
} catch (error) {
retries -= 1;
if (retries === 0) {
logger.error({
tab: i,
message: `Failed to initialize tab after 3 attempts: ${error}`,
});
} else {
logger.warn({
tab: i,
message: `Tab initialization failed, retrying... (${retries} attempts left)`,
});
delay *= 2; // Exponential backoff
}
}
}
}
}
async restartTab(tabIndex) {
try {
await this.tabs[tabIndex].close();
} catch (error) {
logger.warn({
tab: tabIndex,
message: `Error closing tab: ${error.message}`,
});
}
let retries = 3;
while (retries > 0) {
try {
let tab = new Tab(this.url);
await tab.initialiseTab();
this.tabs[tabIndex] = tab;
logger.info({ tab: tabIndex, message: "Tab restarted successfully" });
return;
} catch (error) {
retries--;
if (retries === 0) {
logger.error({
tab: tabIndex,
message: `Failed to restart tab after 3 attempts: ${error.message}`,
});
} else {
logger.warn({
tab: tabIndex,
message: `Tab restart failed, retrying... (${retries} attempts left)`,
});
await this.sleep(1000 * (4 - retries)); // Increasing delay between retries
}
}
}
}
async closeTabs() {
for (let i = 0; i < this.tabs.length; i++) {
await this.tabs[i].close();
}
}
calculateSimilarity(retrievedText, desiredText) {
const retrievedTextTokens = retrievedText
.replace(/(\r\n|\n|\r)/gm, "")
.toLowerCase()
.split(" ");
const desiredTextTokens = desiredText
.replace(/(\r\n|\n|\r)/gm, "")
.toLowerCase()
.split(" ");
let countOfMatchingWords = 0;
for (let i = 0; i < desiredTextTokens.length; i++) {
if (retrievedTextTokens.includes(desiredTextTokens[i])) {
countOfMatchingWords++;
}
}
const score = (countOfMatchingWords / desiredTextTokens.length) * 100;
return score;
}
async getHighestScoringTabIndex() {
let highestScorer = null;
for (let i = 0; i < this.tabs.length; i++) {
if (highestScorer === null) {
highestScorer = i;
continue;
}
if (
(await this.tabs[i].getSimilarityScore()) >
(await this.tabs[highestScorer].getSimilarityScore())
) {
highestScorer = i;
}
}
return highestScorer;
}
async loadPagesAtRate() {
while (true) {
for (let i = 0; i < this.tabs.length; i++) {
while (this.paused === true) {
await this.sleep(10);
}
if (
i !== (await this.getHighestScoringTabIndex()) ||
(await this.tabs[i].getSimilarityScore()) === -1
) {
if ((await this.tabs[i].getReady()) === true) {
logger.info({ tab: i, message: "Loading page" });
try {
const page = await this.tabs[i].loadPage();
logger.info({
tab: i,
message: `Loaded page in ${
Date.now() - this.tabs[i].getStartTime()
}ms`,
});
await this.tabs[i]
.getInnerHtmlTextOfAllElements()
.then(async (pageInnerHtmlText) => {
const similarityScore = await this.calculateSimilarity(
pageInnerHtmlText,
this.registrationPageInnerText
);
await this.tabs[i].setSimilarityScore(similarityScore);
logger.info({
tab: i,
message: `${similarityScore.toFixed(2)}% similarity found`,
});
if (similarityScore > this.similarityThreshold) {
this.paused = true;
logger.info({
tab: i,
message: `Paused operation as page with > ${this.similarityThreshold}% found`,
});
}
const highestScoringTab =
await this.getHighestScoringTabIndex();
if (highestScoringTab !== this.lastHighScorer) {
this.lastHighScorer = highestScoringTab;
await this.tabs[highestScoringTab].bringToFront();
}
await this.tabs[i].setReady(true);
});
} catch (error) {
if (error.message === "Page crashed!") {
logger.error({
tab: i,
message: "Page crashed, restarting tab",
});
await this.restartTab(i);
continue;
} else {
logger.error({
tab: i,
message: `Error loading page: ${error.message}`,
});
}
} finally {
await this.tabs[i].setReady(true);
}
const finishTime = Date.now();
if (
finishTime - this.tabs[i].getStartTime() <
this.refreshRateInMs
) {
await this.sleep(
this.refreshRateInMs -
(finishTime - this.tabs[i].getStartTime())
);
}
} else {
await this.sleep(10);
}
}
}
}
}
sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
}
module.exports = Puppets;