-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathformAutomation.js
More file actions
233 lines (196 loc) · 6.7 KB
/
Copy pathformAutomation.js
File metadata and controls
233 lines (196 loc) · 6.7 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
const puppeteer = require('puppeteer-extra');
const StealthPlugin = require('puppeteer-extra-plugin-stealth');
const UserPreferencesPlugin = require('puppeteer-extra-plugin-user-preferences');
const { faker } = require('@faker-js/faker');
const config = require('./config');
const GeoDetector = require('./geoDetector');
// Add stealth plugin to avoid detection
puppeteer.use(StealthPlugin());
// Add user preferences plugin for more realistic browser behavior
puppeteer.use(UserPreferencesPlugin({
userPrefs: {
profile: {
default_content_setting_values: {
images: 1, // Allow images
javascript: 1, // Allow JavaScript
plugins: 1, // Allow plugins
popups: 2, // Block popups
geolocation: 2, // Block geolocation
notifications: 2, // Block notifications
media_stream: 2, // Block media stream
}
}
}
}));
class FormAutomation {
constructor() {
this.browser = null;
this.page = null;
this.geoDetector = new GeoDetector();
this.startTime = null;
}
/**
* Initialize browser with stealth settings
*/
async initializeBrowser() {
try {
console.log('Initializing browser with stealth mode...');
this.browser = await puppeteer.launch({
headless: config.browser.headless,
slowMo: config.browser.slowMo,
defaultViewport: config.browser.defaultViewport,
args: config.browser.args,
ignoreDefaultArgs: ['--enable-automation'],
executablePath: process.env.CHROME_PATH || undefined
});
this.page = await this.browser.newPage();
// Set realistic user agent
await this.page.setUserAgent(faker.internet.userAgent());
// Set extra headers to appear more human-like
await this.page.setExtraHTTPHeaders({
'Accept-Language': 'en-US,en;q=0.9',
'Accept-Encoding': 'gzip, deflate, br',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'DNT': '1',
'Connection': 'keep-alive',
'Upgrade-Insecure-Requests': '1'
});
// Set viewport to a realistic size
await this.page.setViewport({
width: 1920,
height: 1080,
deviceScaleFactor: 1,
});
console.log('Browser initialized successfully');
} catch (error) {
console.error('Error initializing browser:', error.message);
throw error;
}
}
/**
* Add human-like delays and movements
*/
async humanDelay(min = 1000, max = 3000) {
const delay = Math.floor(Math.random() * (max - min + 1)) + min;
await this.page.waitForTimeout(delay);
}
/**
* Type text with human-like delays
*/
async humanType(selector, text) {
await this.page.click(selector);
await this.humanDelay(500, 1000);
for (let char of text) {
await this.page.type(selector, char, {
delay: Math.random() * 100 + 50 // 50-150ms delay between characters
});
}
}
/**
* Move mouse in a human-like way
*/
async humanMouseMove(selector) {
const element = await this.page.$(selector);
if (element) {
const box = await element.boundingBox();
const x = box.x + box.width / 2;
const y = box.y + box.height / 2;
// Move mouse in a curved path
await this.page.mouse.move(x, y, { steps: 10 });
}
}
/**
* Fill form with lead data
*/
async fillForm(leadData) {
try {
console.log('Starting form filling process...');
// Navigate to the form page
await this.page.goto(config.targetUrl, {
waitUntil: 'networkidle2',
timeout: 30000
});
await this.humanDelay(2000, 4000);
// Fill form fields with human-like behavior
const formFields = [
{ selector: config.formSelectors.firstName, value: leadData.first_name },
{ selector: config.formSelectors.lastName, value: leadData.last_name },
{ selector: config.formSelectors.email, value: leadData.email },
{ selector: config.formSelectors.phone, value: leadData.phone },
{ selector: config.formSelectors.address, value: leadData.address },
{ selector: config.formSelectors.city, value: leadData.city },
{ selector: config.formSelectors.zipCode, value: leadData.zip_code }
];
for (const field of formFields) {
try {
await this.humanMouseMove(field.selector);
await this.humanType(field.selector, field.value);
await this.humanDelay(1000, 2000);
} catch (error) {
console.warn(`Could not fill field ${field.selector}:`, error.message);
}
}
// Handle state dropdown if it exists
if (leadData.state) {
try {
await this.page.select(config.formSelectors.state, leadData.state);
await this.humanDelay(1000, 2000);
} catch (error) {
console.warn('Could not select state:', error.message);
}
}
// Scroll down to submit button
await this.page.evaluate(() => {
window.scrollTo(0, document.body.scrollHeight);
});
await this.humanDelay(1000, 2000);
// Click submit button
await this.humanMouseMove(config.formSelectors.submitButton);
await this.page.click(config.formSelectors.submitButton);
console.log('Form submitted successfully');
// Wait for submission to complete
await this.page.waitForTimeout(5000);
} catch (error) {
console.error('Error filling form:', error.message);
throw error;
}
}
/**
* Check if we're within the time limit
*/
isWithinTimeLimit() {
if (!this.startTime) return true;
const elapsed = Date.now() - this.startTime;
return elapsed < config.proxy.formFillingTimeout;
}
/**
* Main automation process
*/
async runAutomation() {
try {
this.startTime = Date.now();
console.log('Starting automation process...');
// Initialize browser
await this.initializeBrowser();
// Get matching lead based on current IP location
const { lead, ipInfo } = await this.geoDetector.getMatchingLead();
console.log(`Using lead from ${ipInfo.region}: ${lead.first_name} ${lead.last_name}`);
// Fill the form
await this.fillForm(lead);
// Mark lead as used
await this.geoDetector.markLeadAsUsed(lead.id);
console.log('Automation completed successfully');
} catch (error) {
console.error('Automation failed:', error.message);
throw error;
} finally {
if (this.browser) {
await this.browser.close();
}
if (this.geoDetector) {
await this.geoDetector.close();
}
}
}
}
module.exports = FormAutomation;