This repository was archived by the owner on Feb 11, 2025. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuserAgentManager.js
More file actions
79 lines (66 loc) · 2.51 KB
/
userAgentManager.js
File metadata and controls
79 lines (66 loc) · 2.51 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
const fs = require("fs");
const path = require("path");
const querystring = require("querystring");
class UserAgentManager {
constructor(
tokensFile = "data.txt",
userAgentsFile = "user_agents.json",
userAgentsListFile = "user_agents_list.txt"
) {
this.tokensFile = tokensFile;
this.userAgentsFile = userAgentsFile;
this.userAgentsListFile = userAgentsListFile;
}
readFileLines(filePath) {
try {
return fs
.readFileSync(filePath, "utf-8")
.split("\n")
.filter((line) => line.trim() !== "");
} catch (error) {
console.error(`File reading error ${filePath}: ${error.message}`);
return [];
}
}
generateUserAgent(availableUserAgents) {
if (availableUserAgents.length === 0) {
return "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36";
}
const randomIndex = Math.floor(Math.random() * availableUserAgents.length);
return availableUserAgents[randomIndex].trim();
}
extractFirstName(initData) {
try {
return JSON.parse(decodeURIComponent(querystring.parse(initData).user))?.first_name;
} catch (error) {
console.error("Name extraction error:", error);
return null;
}
}
initializeUserAgents() {
const tokens = this.readFileLines(this.tokensFile);
const availableUserAgents = this.readFileLines(this.userAgentsListFile);
let userAgents = {};
if (fs.existsSync(this.userAgentsFile)) {
try {
userAgents = JSON.parse(fs.readFileSync(this.userAgentsFile, "utf-8"));
} catch (error) {
console.warn("Failure to read existing user_agents.json, creation of a new one");
}
}
tokens.forEach((token) => {
const firstName = this.extractFirstName(token);
if (firstName && !userAgents[firstName]) {
userAgents[firstName] = this.generateUserAgent(availableUserAgents);
}
});
fs.writeFileSync(this.userAgentsFile, JSON.stringify(userAgents, null, 2), "utf-8");
return userAgents;
}
getUserAgent(token) {
const userAgents = this.initializeUserAgents();
const firstName = this.extractFirstName(token);
return firstName ? userAgents[firstName] : null;
}
}
module.exports = UserAgentManager;