-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain-proxy.js
More file actions
373 lines (332 loc) · 11.4 KB
/
Copy pathmain-proxy.js
File metadata and controls
373 lines (332 loc) · 11.4 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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
const fs = require("fs");
const path = require("path");
const axios = require("axios");
const colors = require("colors");
const { HttpsProxyAgent } = require("https-proxy-agent");
const readline = require("readline");
const user_agents = require("./config/userAgents");
const settings = require("./config/config");
const { sleep, loadData, getRandomNumber, saveToken, isTokenExpired, saveJson, updateEnv } = require("./utils");
const { Worker, isMainThread, parentPort, workerData } = require("worker_threads");
const { checkBaseUrl } = require("./checkAPI");
const headers = require("./core/header");
class ClientAPI {
constructor(queryId, accountIndex, proxy, baseURL) {
this.headers = headers;
this.baseURL = baseURL;
this.queryId = queryId;
this.accountIndex = accountIndex;
this.proxy = proxy;
this.proxyIP = null;
this.session_name = null;
this.session_user_agents = this.#load_session_data();
}
#load_session_data() {
try {
const filePath = path.join(process.cwd(), "session_user_agents.json");
const data = fs.readFileSync(filePath, "utf8");
return JSON.parse(data);
} catch (error) {
if (error.code === "ENOENT") {
return {};
} else {
throw error;
}
}
}
#get_random_user_agent() {
const randomIndex = Math.floor(Math.random() * user_agents.length);
return user_agents[randomIndex];
}
#get_user_agent() {
if (this.session_user_agents[this.session_name]) {
return this.session_user_agents[this.session_name];
}
console.log(`[Tài khoản ${this.accountIndex + 1}] Tạo user agent...`.blue);
const newUserAgent = this.#get_random_user_agent();
this.session_user_agents[this.session_name] = newUserAgent;
this.#save_session_data(this.session_user_agents);
return newUserAgent;
}
#save_session_data(session_user_agents) {
const filePath = path.join(process.cwd(), "session_user_agents.json");
fs.writeFileSync(filePath, JSON.stringify(session_user_agents, null, 2));
}
#get_platform(userAgent) {
const platformPatterns = [
{ pattern: /iPhone/i, platform: "ios" },
{ pattern: /Android/i, platform: "android" },
{ pattern: /iPad/i, platform: "ios" },
];
for (const { pattern, platform } of platformPatterns) {
if (pattern.test(userAgent)) {
return platform;
}
}
return "Unknown";
}
#set_headers() {
const platform = this.#get_platform(this.#get_user_agent());
this.headers["sec-ch-ua"] = `Not)A;Brand";v="99", "${platform} WebView";v="127", "Chromium";v="127`;
this.headers["sec-ch-ua-platform"] = platform;
this.headers["User-Agent"] = this.#get_user_agent();
}
createUserAgent() {
try {
const telegramauth = this.queryId;
const userData = JSON.parse(decodeURIComponent(telegramauth.split("user=")[1].split("&")[0]));
this.session_name = userData.id;
this.#get_user_agent();
} catch (error) {
this.log(`Can't create user agent, try get new query_id: ${error.message}`, "error");
return;
}
}
async log(msg, type = "info") {
const timestamp = new Date().toLocaleTimeString();
const accountPrefix = `[Tài khoản ${this.accountIndex + 1}]`;
const ipPrefix = this.proxyIP ? `[${this.proxyIP}]` : "[Unknown IP]";
let logMessage = "";
switch (type) {
case "success":
logMessage = `${accountPrefix}${ipPrefix} ${msg}`.green;
break;
case "error":
logMessage = `${accountPrefix}${ipPrefix} ${msg}`.red;
break;
case "warning":
logMessage = `${accountPrefix}${ipPrefix} ${msg}`.yellow;
break;
case "custom":
logMessage = `${accountPrefix}${ipPrefix} ${msg}`.magenta;
break;
default:
logMessage = `${accountPrefix}${ipPrefix} ${msg}`.blue;
}
console.log(logMessage);
}
async checkProxyIP() {
try {
const proxyAgent = new HttpsProxyAgent(this.proxy);
const response = await axios.get("https://api.ipify.org?format=json", { httpsAgent: proxyAgent });
if (response.status === 200) {
this.proxyIP = response.data.ip;
return response.data.ip;
} else {
throw new Error(`Cannot check proxy IP. Status code: ${response.status}`);
}
} catch (error) {
throw new Error(`Error checking proxy IP: ${error.message}`);
}
}
async makeRequest(
url,
method,
data = {},
options = {
retries: 1,
isAuth: false,
}
) {
const { retries, isAuth } = options;
const headers = {
...this.headers,
Authorization: `tma ${this.queryId}`,
};
if (!isAuth) {
headers["Authorization"] = `Bearer ${this.token}`;
}
const proxyAgent = new HttpsProxyAgent(this.proxy);
let currRetries = 0,
success = false;
do {
try {
const response = await axios({
method,
url: `${url}`,
data,
headers,
httpsAgent: proxyAgent,
timeout: 30000,
});
success = true;
return { success: true, data: response.data.data };
} catch (error) {
if (error.status == 400) {
return { success: false, error: error.message };
}
this.log(`Yêu cầu thất bại: ${url} | ${error.message} | đang thử lại...`, "warning");
success = false;
await sleep(settings.DELAY_BETWEEN_REQUESTS);
if (currRetries == retries) return { success: false, error: error.message };
}
currRetries++;
} while (currRetries <= retries && !success);
}
async auth() {
return this.makeRequest(`${this.baseURL}/auth/create-user`, "post", { refCode: "Iil4QcC4TF" }, { isAuth: true });
}
async getUserInfo() {
return this.makeRequest(`${this.baseURL}/user`, "get");
}
async getQuests() {
return this.makeRequest(`${this.baseURL}/user/quest`, "get");
}
async getValidToken() {
const userId = this.session_name;
const existingToken = this.token;
let loginResult = null;
const isExp = isTokenExpired(existingToken);
if (existingToken && !isExp) {
this.log("Using valid token", "success");
return token;
} else {
this.log("Token not found or expired, logging in...", "warning");
loginResult = await this.auth();
}
if (loginResult?.success) {
const { token } = loginResult?.data;
if (token) {
saveToken(userId, token);
this.token = token;
}
return token;
} else {
this.log(`Can't get token, try get new query_id!`, "warning");
}
return null;
}
async runAccount() {
try {
this.proxyIP = await this.checkProxyIP();
} catch (error) {
this.log(`Cannot check proxy IP: ${error.message}`, "warning");
return;
}
const accountIndex = this.accountIndex;
const initData = this.queryId;
const queryData = JSON.parse(decodeURIComponent(initData.split("user=")[1].split("&")[0]));
const firstName = queryData.first_name || "";
const lastName = queryData.last_name || "";
this.session_name = queryData.id;
const timesleep = getRandomNumber(settings.DELAY_START_BOT[0], settings.DELAY_START_BOT[1]);
console.log(`=========Tài khoản ${accountIndex + 1}| ${firstName + " " + lastName} | ${this.proxyIP} | Bắt đầu sau ${timesleep} giây...`.green);
this.#set_headers();
await sleep(timesleep);
const token = await this.getValidToken();
if (!token) return this.log(`Can't get token for account ${this.accountIndex + 1}, skipping...`, "error");
let userData = { success: false },
retries = 0;
do {
userData = await this.getUserInfo();
if (userData?.success) break;
retries++;
} while (retries < 2);
// process.exit(0);
if (userData.success) {
//
//start processing here================
//
} else {
return this.log("Can't get use info...skipping", "error");
}
}
}
async function runWorker(workerData) {
const { queryId, accountIndex, proxy, hasIDAPI } = workerData;
const to = new ClientAPI(queryId, accountIndex, proxy, hasIDAPI);
try {
await Promise.race([to.runAccount(), new Promise((_, reject) => setTimeout(() => reject(new Error("Timeout")), 24 * 60 * 60 * 1000))]);
parentPort.postMessage({
accountIndex,
});
} catch (error) {
parentPort.postMessage({ accountIndex, error: error.message });
} finally {
if (!isMainThread) {
parentPort.postMessage("taskComplete");
}
}
}
async function main() {
const queryIds = loadData("data.txt");
const proxies = loadData("proxy.txt");
if (queryIds.length > proxies.length) {
console.log("Số lượng proxy và data phải bằng nhau.".red);
console.log(`Data: ${queryIds.length}`);
console.log(`Proxy: ${proxies.length}`);
process.exit(1);
}
console.log("Tool được phát triển bởi nhóm tele Airdrop Hunter Siêu Tốc (https://t.me/airdrophuntersieutoc)".yellow);
let maxThreads = settings.MAX_THEADS;
const { endpoint: hasIDAPI, message } = await checkBaseUrl();
if (!hasIDAPI) return console.log(`Không thể tìm thấy ID API, thử lại sau!`.red);
console.log(`${message}`.yellow);
// process.exit();
queryIds.map((val, i) => new ClientAPI(val, i, proxies[i], hasIDAPI).createUserAgent());
await sleep(1);
while (true) {
let currentIndex = 0;
const errors = [];
while (currentIndex < queryIds.length) {
const workerPromises = [];
const batchSize = Math.min(maxThreads, queryIds.length - currentIndex);
for (let i = 0; i < batchSize; i++) {
const worker = new Worker(__filename, {
workerData: {
hasIDAPI,
queryId: queryIds[currentIndex],
accountIndex: currentIndex,
proxy: proxies[currentIndex % proxies.length],
},
});
workerPromises.push(
new Promise((resolve) => {
worker.on("message", (message) => {
if (message === "taskComplete") {
worker.terminate();
}
if (settings.ENABLE_DEBUG) {
console.log(message);
}
resolve();
});
worker.on("error", (error) => {
console.log(`Lỗi worker cho tài khoản ${currentIndex}: ${error.message}`);
worker.terminate();
resolve();
});
worker.on("exit", (code) => {
worker.terminate();
if (code !== 0) {
errors.push(`Worker cho tài khoản ${currentIndex} thoát với mã: ${code}`);
}
resolve();
});
})
);
currentIndex++;
}
await Promise.all(workerPromises);
if (errors.length > 0) {
errors.length = 0;
}
if (currentIndex < queryIds.length) {
await new Promise((resolve) => setTimeout(resolve, 3000));
}
}
await updateEnv("AUTO_CODE_GATEWAY", "false");
await sleep(3);
console.log("Tool được phát triển bởi nhóm tele Airdrop Hunter Siêu Tốc (https://t.me/airdrophuntersieutoc)".yellow);
console.log(`=============Hoàn thành tất cả tài khoản | Chờ ${settings.TIME_SLEEP} phút=============`.magenta);
await sleep(settings.TIME_SLEEP * 60);
}
}
if (isMainThread) {
main().catch((error) => {
console.log("Lỗi rồi:", error);
process.exit(1);
});
} else {
runWorker(workerData);
}