@xkwdstore/agent 2.0.1 → 2.0.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +251 -244
- package/package.json +54 -54
- package/src/actions/comment.js +137 -137
- package/src/actions/dbc.js +149 -149
- package/src/actions/follow.js +82 -82
- package/src/actions/helpers.js +753 -753
- package/src/actions/index.js +94 -94
- package/src/actions/like.js +244 -244
- package/src/actions/session.js +1610 -1610
- package/src/actions/tweet.js +90 -90
- package/src/challengeCodec.js +31 -31
- package/src/chromeDetector.js +154 -154
- package/src/cli.js +664 -528
- package/src/configStore.js +97 -97
- package/src/deviceKeyStore.js +947 -700
- package/src/enrollmentClient.js +588 -445
- package/src/fingerprint.js +261 -261
- package/src/fingerprintStore.js +125 -125
- package/src/leaseClient.js +84 -84
- package/src/processLock.js +148 -148
- package/src/profilePath.js +1116 -1116
- package/src/proxyEgress.js +338 -338
- package/src/proxyPolicy.js +76 -76
- package/src/secretStore.js +132 -132
- package/src/sessionHandler.js +618 -452
- package/src/stealth.js +1250 -1250
- package/src/wsClient.js +233 -233
package/src/actions/session.js
CHANGED
|
@@ -1,1611 +1,1611 @@
|
|
|
1
|
-
'use strict';
|
|
2
|
-
|
|
3
|
-
/**
|
|
4
|
-
* Session actions — login, check login state, check account status.
|
|
5
|
-
* Ported from src/login.js + backend/routes/browser.js.
|
|
6
|
-
* Includes DBC captcha solving for login challenges.
|
|
7
|
-
*/
|
|
8
|
-
|
|
9
|
-
const { sleep, humanDelay, randDelay, safeFill, safeClick, humanClick, getBodyText, detectStage, waitForLoggedIn, generateTOTP, injectCookies, SELECTORS, humanHover, idleMouseJitter, humanScroll, logNormalDelay, highlightElement } = require('./helpers');
|
|
10
|
-
const dbc = require('./dbc');
|
|
11
|
-
|
|
12
|
-
// Simple log — writes to agent log via console (captured by agent's log system)
|
|
13
|
-
function log(msg) { console.log(`[session-action] ${msg}`); }
|
|
14
|
-
|
|
15
|
-
// ── Captcha detection ────────────────────────────────────────────────────────
|
|
16
|
-
|
|
17
|
-
/**
|
|
18
|
-
* Detect if there's a captcha/challenge on the page.
|
|
19
|
-
* Returns { hasCaptcha, type, imageSelector } or null.
|
|
20
|
-
*/
|
|
21
|
-
async function detectCaptcha(page) {
|
|
22
|
-
try {
|
|
23
|
-
const bodyText = await getBodyText(page);
|
|
24
|
-
|
|
25
|
-
// Twitter/X challenge patterns
|
|
26
|
-
if (/verify you are human|unusual activity|login challenge|confirm you are a person/i.test(bodyText)) {
|
|
27
|
-
// Look for Arkose Labs / Funcaptcha iframe
|
|
28
|
-
const arkoseFrame = page.frameLocator('iframe[src*="arkose"], iframe[src*="funcaptcha"], iframe[title*="captcha"]');
|
|
29
|
-
if (await arkoseFrame.locator('body').isVisible({ timeout: 2000 }).catch(() => false)) {
|
|
30
|
-
return { hasCaptcha: true, type: 'arkose', imageSelector: null };
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
// Look for image captcha (img tag with captcha)
|
|
34
|
-
const captchaImg = page.locator('img[src*="captcha"], img[alt*="captcha"], #captcha, .captcha img').first();
|
|
35
|
-
if (await captchaImg.isVisible({ timeout: 2000 }).catch(() => false)) {
|
|
36
|
-
return { hasCaptcha: true, type: 'image', imageSelector: 'img[src*="captcha"], img[alt*="captcha"], #captcha img, .captcha img' };
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
// Generic captcha container
|
|
40
|
-
const captchaContainer = page.locator('[data-testid="captcha"], [aria-label*="captcha"], canvas').first();
|
|
41
|
-
if (await captchaContainer.isVisible({ timeout: 2000 }).catch(() => false)) {
|
|
42
|
-
return { hasCaptcha: true, type: 'image', imageSelector: '[data-testid="captcha"], [aria-label*="captcha"], canvas' };
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
// Challenge present but no recognizable captcha element
|
|
46
|
-
return { hasCaptcha: true, type: 'unknown', imageSelector: null };
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
return null;
|
|
50
|
-
} catch {
|
|
51
|
-
return null;
|
|
52
|
-
}
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
/**
|
|
56
|
-
* Attempt to solve an image captcha using DBC.
|
|
57
|
-
* Captures the captcha image, sends to DBC, enters the answer.
|
|
58
|
-
*/
|
|
59
|
-
async function solveCaptchaWithDBC(page, captchaInfo) {
|
|
60
|
-
if (!dbc.isEnabled()) {
|
|
61
|
-
console.log('[captcha] DBC not configured — cannot solve captcha automatically');
|
|
62
|
-
return false;
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
if (captchaInfo.type === 'arkose') {
|
|
66
|
-
// Arkose Labs / Funcaptcha — DBC supports this via token-based solving
|
|
67
|
-
// but it requires a different API flow. For now, log and return false.
|
|
68
|
-
console.log('[captcha] Arkose/FunCaptcha detected — DBC image solver cannot handle this type');
|
|
69
|
-
return false;
|
|
70
|
-
}
|
|
71
|
-
|
|
72
|
-
if (captchaInfo.type !== 'image') {
|
|
73
|
-
console.log(`[captcha] Unknown captcha type: ${captchaInfo.type}`);
|
|
74
|
-
return false;
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
try {
|
|
78
|
-
// Capture the captcha image as screenshot
|
|
79
|
-
const imgLocator = page.locator(captchaInfo.imageSelector).first();
|
|
80
|
-
await imgLocator.waitFor({ state: 'visible', timeout: 5000 });
|
|
81
|
-
|
|
82
|
-
// Take a screenshot of the captcha element
|
|
83
|
-
const imageBuffer = await imgLocator.screenshot();
|
|
84
|
-
console.log(`[captcha] Captured captcha image (${imageBuffer.length} bytes)`);
|
|
85
|
-
|
|
86
|
-
// Send to DBC for solving
|
|
87
|
-
const result = await dbc.solveImageCaptcha(imageBuffer, { timeoutMs: 90000 });
|
|
88
|
-
console.log(`[captcha] DBC returned: "${result.text}"`);
|
|
89
|
-
|
|
90
|
-
// Find the input field for the captcha answer
|
|
91
|
-
const captchaInput = page.locator('input[name="captcha"], input[type="text"][placeholder*="captcha"], input[aria-label*="captcha"], input[name="text"]').first();
|
|
92
|
-
if (await captchaInput.isVisible({ timeout: 5000 }).catch(() => false)) {
|
|
93
|
-
await safeFill(page, captchaInput, result.text);
|
|
94
|
-
await humanDelay(300, 600);
|
|
95
|
-
|
|
96
|
-
// Look for a submit/verify button
|
|
97
|
-
const submitBtn = page.locator('button:has-text("Verify"), button:has-text("Submit"), button:has-text("Continue"), button:has-text("Next"), [role="button"]:has-text("Verify")').first();
|
|
98
|
-
if (await submitBtn.isVisible({ timeout: 3000 }).catch(() => false)) {
|
|
99
|
-
await humanClick(page, submitBtn);
|
|
100
|
-
} else {
|
|
101
|
-
await page.keyboard.press('Enter');
|
|
102
|
-
}
|
|
103
|
-
|
|
104
|
-
await randDelay(3000, 5000);
|
|
105
|
-
return true;
|
|
106
|
-
} else {
|
|
107
|
-
console.log('[captcha] No captcha input field found');
|
|
108
|
-
return false;
|
|
109
|
-
}
|
|
110
|
-
} catch (err) {
|
|
111
|
-
console.log(`[captcha] DBC solve failed: ${err.message}`);
|
|
112
|
-
return false;
|
|
113
|
-
}
|
|
114
|
-
}
|
|
115
|
-
|
|
116
|
-
// ── Auto-login ───────────────────────────────────────────────────────────────
|
|
117
|
-
async function autoLogin(page, payload) {
|
|
118
|
-
const { username, password, totpSecret, cookies, dbcUsername, dbcPassword } = payload;
|
|
119
|
-
|
|
120
|
-
// Configure DBC if credentials provided
|
|
121
|
-
if (dbcUsername && dbcPassword) {
|
|
122
|
-
dbc.configure(dbcUsername, dbcPassword);
|
|
123
|
-
}
|
|
124
|
-
|
|
125
|
-
// Navigate to login — try clicking Sign in on the current page first
|
|
126
|
-
// (navigating directly to x.com/i/flow/login can crash Firefox with some proxies)
|
|
127
|
-
try {
|
|
128
|
-
// Make sure we're on x.com
|
|
129
|
-
const currentUrl = page.url();
|
|
130
|
-
if (!currentUrl.includes('x.com')) {
|
|
131
|
-
await page.goto('https://x.com', { waitUntil: 'domcontentloaded', timeout: 60000 });
|
|
132
|
-
}
|
|
133
|
-
await randDelay(2000, 4000);
|
|
134
|
-
|
|
135
|
-
// Check if we're already on the login page
|
|
136
|
-
const url = page.url();
|
|
137
|
-
if (url.includes('/login') || url.includes('/i/flow')) {
|
|
138
|
-
// Already on login page — wait for it to load
|
|
139
|
-
await randDelay(2000, 4000);
|
|
140
|
-
} else {
|
|
141
|
-
// Click the Sign in button using JavaScript (more reliable than locator)
|
|
142
|
-
await page.evaluate(() => {
|
|
143
|
-
const signInEl = document.querySelector('a[href="/login"], a[href="/i/flow/login"], [data-testid="loginButton"]');
|
|
144
|
-
if (signInEl) signInEl.click();
|
|
145
|
-
});
|
|
146
|
-
await randDelay(3000, 6000);
|
|
147
|
-
}
|
|
148
|
-
} catch (e) {
|
|
149
|
-
// Fallback: try direct navigation
|
|
150
|
-
try {
|
|
151
|
-
await page.goto('https://x.com/i/flow/login', { waitUntil: 'commit', timeout: 60000 });
|
|
152
|
-
await randDelay(3000, 6000);
|
|
153
|
-
} catch (e2) {
|
|
154
|
-
throw new Error(`Failed to navigate to login page: ${e2.message}`);
|
|
155
|
-
}
|
|
156
|
-
}
|
|
157
|
-
|
|
158
|
-
// Check if the page is still alive
|
|
159
|
-
try {
|
|
160
|
-
await page.evaluate(() => document.title);
|
|
161
|
-
} catch {
|
|
162
|
-
throw new Error('Browser closed after navigating to login page');
|
|
163
|
-
}
|
|
164
|
-
|
|
165
|
-
// Step 1: Enter username
|
|
166
|
-
const usernameInput = page.locator(SELECTORS.usernameInput).first();
|
|
167
|
-
await usernameInput.waitFor({ state: 'visible', timeout: 30000 });
|
|
168
|
-
await safeFill(page, usernameInput, username);
|
|
169
|
-
await humanDelay(300, 600);
|
|
170
|
-
|
|
171
|
-
// Click Next
|
|
172
|
-
const nextBtn = page.locator('button:has-text("Next"), [role="button"]:has-text("Next")').first();
|
|
173
|
-
if (await nextBtn.isVisible({ timeout: 3000 }).catch(() => false)) {
|
|
174
|
-
await humanClick(page, nextBtn);
|
|
175
|
-
} else {
|
|
176
|
-
await page.keyboard.press('Enter');
|
|
177
|
-
}
|
|
178
|
-
await randDelay(2000, 4000);
|
|
179
|
-
|
|
180
|
-
// Step 2: Enter password
|
|
181
|
-
const passwordInput = page.locator(SELECTORS.passwordInput).first();
|
|
182
|
-
await passwordInput.waitFor({ state: 'visible', timeout: 15000 });
|
|
183
|
-
await safeFill(page, passwordInput, password);
|
|
184
|
-
await humanDelay(300, 600);
|
|
185
|
-
|
|
186
|
-
// Click Log in
|
|
187
|
-
const loginBtn = page.locator('[data-testid="LoginForm_Login_Button"], button:has-text("Log in")').first();
|
|
188
|
-
if (await loginBtn.isVisible({ timeout: 3000 }).catch(() => false)) {
|
|
189
|
-
await humanClick(page, loginBtn);
|
|
190
|
-
} else {
|
|
191
|
-
await page.keyboard.press('Enter');
|
|
192
|
-
}
|
|
193
|
-
await randDelay(3000, 5000);
|
|
194
|
-
|
|
195
|
-
// Step 3: Check for captcha/challenge
|
|
196
|
-
const captchaInfo = await detectCaptcha(page);
|
|
197
|
-
if (captchaInfo) {
|
|
198
|
-
console.log(`[login] Captcha detected: ${captchaInfo.type}`);
|
|
199
|
-
const solved = await solveCaptchaWithDBC(page, captchaInfo);
|
|
200
|
-
if (!solved) {
|
|
201
|
-
return { success: false, state: 'captcha', message: 'Captcha detected but could not be solved automatically. Manual intervention required.' };
|
|
202
|
-
}
|
|
203
|
-
await randDelay(2000, 4000);
|
|
204
|
-
}
|
|
205
|
-
|
|
206
|
-
// Step 4: Check for 2FA
|
|
207
|
-
const stage = await detectStage(page);
|
|
208
|
-
if (stage === 'unknown') {
|
|
209
|
-
// Might need 2FA
|
|
210
|
-
const twoFactorInput = page.locator('input[name="text"], input[type="text"]').first();
|
|
211
|
-
if (await twoFactorInput.isVisible({ timeout: 5000 }).catch(() => false)) {
|
|
212
|
-
if (totpSecret) {
|
|
213
|
-
const code = generateTOTP(totpSecret);
|
|
214
|
-
await safeFill(page, twoFactorInput, code);
|
|
215
|
-
await page.keyboard.press('Enter');
|
|
216
|
-
await randDelay(3000, 5000);
|
|
217
|
-
} else {
|
|
218
|
-
throw new Error('2FA required but no TOTP secret provided');
|
|
219
|
-
}
|
|
220
|
-
}
|
|
221
|
-
}
|
|
222
|
-
|
|
223
|
-
// Step 5: Check for captcha again (after 2FA)
|
|
224
|
-
const captchaInfo2 = await detectCaptcha(page);
|
|
225
|
-
if (captchaInfo2) {
|
|
226
|
-
console.log(`[login] Post-2FA captcha detected: ${captchaInfo2.type}`);
|
|
227
|
-
const solved = await solveCaptchaWithDBC(page, captchaInfo2);
|
|
228
|
-
if (!solved) {
|
|
229
|
-
return { success: false, state: 'captcha', message: 'Captcha after 2FA could not be solved automatically.' };
|
|
230
|
-
}
|
|
231
|
-
await randDelay(2000, 4000);
|
|
232
|
-
}
|
|
233
|
-
|
|
234
|
-
// Wait for login to complete
|
|
235
|
-
const loggedIn = await waitForLoggedIn(page, { timeoutMs: 25000 });
|
|
236
|
-
if (loggedIn) {
|
|
237
|
-
return { success: true, state: 'home_logged_in', message: 'Login successful' };
|
|
238
|
-
}
|
|
239
|
-
|
|
240
|
-
const finalStage = await detectStage(page);
|
|
241
|
-
if (finalStage === 'login_username_step' || finalStage === 'login_password_step') {
|
|
242
|
-
return { success: false, state: finalStage, message: 'Login failed — check credentials' };
|
|
243
|
-
}
|
|
244
|
-
|
|
245
|
-
return { success: false, state: finalStage || 'unknown', message: 'Login may require manual intervention' };
|
|
246
|
-
}
|
|
247
|
-
|
|
248
|
-
// ── Check login state ────────────────────────────────────────────────────────
|
|
249
|
-
async function checkLoginState(page, payload) {
|
|
250
|
-
const stage = await detectStage(page);
|
|
251
|
-
const loggedIn = stage === 'home_logged_in';
|
|
252
|
-
return {
|
|
253
|
-
success: true,
|
|
254
|
-
loggedIn,
|
|
255
|
-
state: loggedIn ? 'logged_in' : stage === 'unknown' ? 'unknown' : 'login_required',
|
|
256
|
-
url: page.url(),
|
|
257
|
-
};
|
|
258
|
-
}
|
|
259
|
-
|
|
260
|
-
// ── Check account status (active/suspended/inactive) ─────────────────────────
|
|
261
|
-
async function checkStatus(page, payload) {
|
|
262
|
-
const { username } = payload;
|
|
263
|
-
const cleanUsername = String(username).replace(/^@/, '');
|
|
264
|
-
|
|
265
|
-
// Navigate to home
|
|
266
|
-
await page.goto('https://x.com/home', { waitUntil: 'domcontentloaded', timeout: 30000 }).catch(() => {});
|
|
267
|
-
await sleep(3000);
|
|
268
|
-
|
|
269
|
-
const homeUrl = page.url();
|
|
270
|
-
if (homeUrl.includes('/login') || homeUrl.includes('/i/flow')) {
|
|
271
|
-
return { success: true, status: 'inactive', reason: 'login_required', message: 'Account requires login' };
|
|
272
|
-
}
|
|
273
|
-
|
|
274
|
-
// Check for suspension banner on home
|
|
275
|
-
const homeBody = await getBodyText(page);
|
|
276
|
-
if (homeBody.includes('account suspended') || homeBody.includes('your account is suspended')) {
|
|
277
|
-
return { success: true, status: 'suspended', reason: 'home_suspension_banner', message: 'Account is suspended' };
|
|
278
|
-
}
|
|
279
|
-
|
|
280
|
-
// Navigate to profile
|
|
281
|
-
await page.goto(`https://x.com/${cleanUsername}`, { waitUntil: 'domcontentloaded', timeout: 30000 }).catch(() => {});
|
|
282
|
-
await sleep(3000);
|
|
283
|
-
|
|
284
|
-
const profileUrl = page.url();
|
|
285
|
-
if (profileUrl.includes('/login') || profileUrl.includes('/i/flow')) {
|
|
286
|
-
return { success: true, status: 'inactive', reason: 'login_required', message: 'Account requires login' };
|
|
287
|
-
}
|
|
288
|
-
|
|
289
|
-
const profileBody = await getBodyText(page);
|
|
290
|
-
if (profileBody.includes('account suspended') || profileBody.includes('your account is suspended')) {
|
|
291
|
-
return { success: true, status: 'suspended', reason: 'profile_suspension_detected', message: 'Account is suspended' };
|
|
292
|
-
}
|
|
293
|
-
if (profileBody.includes("this account doesn't exist") || profileBody.includes("account doesn't exist")) {
|
|
294
|
-
return { success: true, status: 'suspended', reason: 'account_not_found', message: 'Account does not exist' };
|
|
295
|
-
}
|
|
296
|
-
|
|
297
|
-
// Check if profile loaded
|
|
298
|
-
const profileLoaded = await page.$('[data-testid="primaryColumn"], [data-testid="UserName"]');
|
|
299
|
-
if (profileLoaded) {
|
|
300
|
-
return { success: true, status: 'active', reason: 'profile_accessible', message: 'Account is active' };
|
|
301
|
-
}
|
|
302
|
-
|
|
303
|
-
return { success: true, status: 'unknown', reason: 'unable_to_determine', message: 'Unable to determine status' };
|
|
304
|
-
}
|
|
305
|
-
|
|
306
|
-
// ── Get profile info ────────────────────────────────────────────────────────
|
|
307
|
-
async function getProfileInfo(page, payload) {
|
|
308
|
-
const { username } = payload;
|
|
309
|
-
const cleanUsername = String(username).replace(/^@/, '');
|
|
310
|
-
|
|
311
|
-
// Navigate to the profile page — use a fresh page to avoid closing the main one
|
|
312
|
-
// Try up to 3 times in case the page crashes through the proxy
|
|
313
|
-
let data = null;
|
|
314
|
-
for (let attempt = 0; attempt < 3 && !data; attempt++) {
|
|
315
|
-
try {
|
|
316
|
-
await page.goto(`https://x.com/${cleanUsername}`, { waitUntil: 'domcontentloaded', timeout: 45000 });
|
|
317
|
-
await page.waitForLoadState('networkidle', { timeout: 10000 }).catch(() => {});
|
|
318
|
-
await page.waitForSelector('[data-testid="UserName"], [data-testid="UserProfileHeader_Items"]', { timeout: 15000 }).catch(() => {});
|
|
319
|
-
await sleep(2500);
|
|
320
|
-
|
|
321
|
-
// Check if page is still alive before evaluate
|
|
322
|
-
try {
|
|
323
|
-
await page.evaluate(() => document.title);
|
|
324
|
-
} catch (e) {
|
|
325
|
-
log(`[getProfileInfo] Page closed on attempt ${attempt + 1}: ${e.message}`);
|
|
326
|
-
// Navigate back to home to recover the page
|
|
327
|
-
await page.goto('https://x.com/home', { waitUntil: 'domcontentloaded', timeout: 30000 }).catch(() => {});
|
|
328
|
-
continue;
|
|
329
|
-
}
|
|
330
|
-
|
|
331
|
-
data = await page.evaluate(() => {
|
|
332
|
-
let name = '', username = '', bio = '', avatarUrl = '', headerUrl = '';
|
|
333
|
-
const nameEl = document.querySelector('[data-testid="UserName"]');
|
|
334
|
-
if (nameEl) {
|
|
335
|
-
const spans = nameEl.querySelectorAll('span');
|
|
336
|
-
for (const sp of spans) {
|
|
337
|
-
const t = (sp.innerText || sp.textContent || '').trim();
|
|
338
|
-
if (!t || t === '·') continue;
|
|
339
|
-
if (!name && !t.startsWith('@')) name = t;
|
|
340
|
-
if (!username && t.startsWith('@')) username = t.replace(/^@/, '');
|
|
341
|
-
if (name && username) break;
|
|
342
|
-
}
|
|
343
|
-
}
|
|
344
|
-
const bioEl = document.querySelector('[data-testid="UserDescription"]');
|
|
345
|
-
bio = bioEl ? (bioEl.innerText || bioEl.textContent || '').trim() : '';
|
|
346
|
-
for (const img of document.querySelectorAll('img')) {
|
|
347
|
-
const src = img.src || '';
|
|
348
|
-
if (!avatarUrl && /pbs\.twimg\.com\/profile_images\//i.test(src)) {
|
|
349
|
-
avatarUrl = src.replace(/_(normal|mini|bigger|200x200|400x400|orig)(\.[a-z]+)$/i, '_400x400$2');
|
|
350
|
-
}
|
|
351
|
-
if (!headerUrl && /pbs\.twimg\.com\/profile_banners\//i.test(src)) headerUrl = src;
|
|
352
|
-
if (avatarUrl && headerUrl) break;
|
|
353
|
-
}
|
|
354
|
-
return { name, username, bio, avatarUrl, headerUrl };
|
|
355
|
-
});
|
|
356
|
-
} catch (e) {
|
|
357
|
-
log(`[getProfileInfo] Attempt ${attempt + 1} failed: ${e.message}`);
|
|
358
|
-
// Try to recover by going home
|
|
359
|
-
await page.goto('https://x.com/home', { waitUntil: 'domcontentloaded', timeout: 30000 }).catch(() => {});
|
|
360
|
-
await sleep(2000);
|
|
361
|
-
}
|
|
362
|
-
}
|
|
363
|
-
|
|
364
|
-
if (!data) {
|
|
365
|
-
// All attempts failed — return empty data (the frontend will use existing DB values)
|
|
366
|
-
log(`[getProfileInfo] All attempts failed for @${cleanUsername}, returning empty`);
|
|
367
|
-
return { name: '', username: cleanUsername, bio: '', avatarUrl: '', headerUrl: '' };
|
|
368
|
-
}
|
|
369
|
-
|
|
370
|
-
if (!data.username) data.username = cleanUsername;
|
|
371
|
-
return data;
|
|
372
|
-
}
|
|
373
|
-
|
|
374
|
-
// ── Helper: image URL or base64 → temp file ─────────────────────────────────
|
|
375
|
-
async function imageToTempFile(imageUrl, imageBase64) {
|
|
376
|
-
const fs = require('fs');
|
|
377
|
-
const path = require('path');
|
|
378
|
-
const os = require('os');
|
|
379
|
-
const https = require('https');
|
|
380
|
-
const http = require('http');
|
|
381
|
-
|
|
382
|
-
const extFromMime = (mime) => {
|
|
383
|
-
const m = String(mime || '').toLowerCase();
|
|
384
|
-
if (m.includes('png')) return 'png';
|
|
385
|
-
if (m.includes('webp')) return 'webp';
|
|
386
|
-
if (m.includes('jpeg') || m.includes('jpg')) return 'jpg';
|
|
387
|
-
return null;
|
|
388
|
-
};
|
|
389
|
-
|
|
390
|
-
if (imageBase64) {
|
|
391
|
-
const mimeMatch = imageBase64.match(/^data:(image\/[\w.+-]+);base64,/i);
|
|
392
|
-
const ext = extFromMime(mimeMatch?.[1]);
|
|
393
|
-
if (!ext) throw new Error(`Unsupported profile image type: ${mimeMatch?.[1] || 'unknown'}`);
|
|
394
|
-
const tempFile = path.join(os.tmpdir(), `tw-img-${Date.now()}.${ext}`);
|
|
395
|
-
const base64Data = imageBase64.replace(/^data:image\/[\w.+-]+;base64,/i, '');
|
|
396
|
-
fs.writeFileSync(tempFile, Buffer.from(base64Data, 'base64'));
|
|
397
|
-
return tempFile;
|
|
398
|
-
}
|
|
399
|
-
|
|
400
|
-
if (!imageUrl) throw new Error('No image provided');
|
|
401
|
-
|
|
402
|
-
let tempFile = null;
|
|
403
|
-
await new Promise((resolve, reject) => {
|
|
404
|
-
const protocol = imageUrl.startsWith('https') ? https : http;
|
|
405
|
-
protocol.get(imageUrl, (response) => {
|
|
406
|
-
if (response.statusCode !== 200) {
|
|
407
|
-
reject(new Error(`HTTP ${response.statusCode}`));
|
|
408
|
-
return;
|
|
409
|
-
}
|
|
410
|
-
let ext = extFromMime(response.headers['content-type']);
|
|
411
|
-
try {
|
|
412
|
-
const urlExt = path.extname(new URL(imageUrl).pathname).replace('.', '').toLowerCase();
|
|
413
|
-
if (/^(png|jpe?g|webp)$/.test(urlExt)) ext = urlExt === 'jpeg' ? 'jpg' : urlExt;
|
|
414
|
-
} catch {}
|
|
415
|
-
if (!ext) {
|
|
416
|
-
reject(new Error(`Unsupported profile image content type: ${response.headers['content-type'] || 'unknown'}`));
|
|
417
|
-
return;
|
|
418
|
-
}
|
|
419
|
-
tempFile = path.join(os.tmpdir(), `tw-img-${Date.now()}.${ext}`);
|
|
420
|
-
const file = fs.createWriteStream(tempFile);
|
|
421
|
-
response.pipe(file);
|
|
422
|
-
file.on('finish', () => { file.close(); resolve(); });
|
|
423
|
-
}).on('error', (err) => {
|
|
424
|
-
if (tempFile) try { fs.unlinkSync(tempFile); } catch {}
|
|
425
|
-
reject(err);
|
|
426
|
-
});
|
|
427
|
-
});
|
|
428
|
-
return tempFile;
|
|
429
|
-
}
|
|
430
|
-
|
|
431
|
-
// ── Helper: click banner/avatar trigger, upload file, apply crop ─────────────
|
|
432
|
-
async function uploadProfileImage(page, tempFile, kind) {
|
|
433
|
-
const label = kind === 'header' ? 'header banner' : 'profile avatar';
|
|
434
|
-
log(`[updateProfile] Uploading ${label}...`);
|
|
435
|
-
|
|
436
|
-
// Scroll to top so both upload buttons are in viewport
|
|
437
|
-
await page.evaluate(() => window.scrollTo(0, 0)).catch(() => {});
|
|
438
|
-
await sleep(400);
|
|
439
|
-
|
|
440
|
-
// ── PRIMARY: click the camera/add-photo button on the avatar or header area ──
|
|
441
|
-
// On X's profile editor, the avatar and header each have a camera button that
|
|
442
|
-
// opens a file chooser. We click the correct one based on kind, then set the
|
|
443
|
-
// file via the filechooser event — this is the most reliable method.
|
|
444
|
-
try {
|
|
445
|
-
const trigger = await findUploadTrigger(page, kind);
|
|
446
|
-
if (trigger) {
|
|
447
|
-
log(`[updateProfile] ${label}: found trigger at y=${Math.round(trigger.y)}, hint="${trigger.hint}"`);
|
|
448
|
-
const jx = trigger.x + (Math.random() * 4 - 2);
|
|
449
|
-
const jy = trigger.y + (Math.random() * 4 - 2);
|
|
450
|
-
await page.mouse.move(jx, jy, { steps: 8 });
|
|
451
|
-
await randDelay(80, 160);
|
|
452
|
-
const chooserPromise = page.waitForEvent('filechooser', { timeout: 5000 }).catch(() => null);
|
|
453
|
-
await page.mouse.click(jx, jy);
|
|
454
|
-
const chooser = await chooserPromise;
|
|
455
|
-
if (chooser) {
|
|
456
|
-
await chooser.setFiles(tempFile);
|
|
457
|
-
log(`[updateProfile] ${label}: file set via filechooser`);
|
|
458
|
-
// Wait longer for X to process the image and open the cropper (was 1.5s, now 3s)
|
|
459
|
-
await sleep(3000);
|
|
460
|
-
const applied = await confirmMediaEdit(page, kind);
|
|
461
|
-
if (applied) {
|
|
462
|
-
log(`[updateProfile] ${label}: uploaded and confirmed`);
|
|
463
|
-
// Wait for the cropper to fully close and image to be staged
|
|
464
|
-
await sleep(2000);
|
|
465
|
-
return true;
|
|
466
|
-
}
|
|
467
|
-
// Apply not found — maybe no cropper shown
|
|
468
|
-
log(`[updateProfile] ${label}: Apply not shown — assuming upload succeeded`);
|
|
469
|
-
await sleep(1000);
|
|
470
|
-
return true;
|
|
471
|
-
}
|
|
472
|
-
log(`[updateProfile] ${label}: click produced no filechooser — trying input method`);
|
|
473
|
-
} else {
|
|
474
|
-
log(`[updateProfile] ${label}: no trigger button found — trying input method`);
|
|
475
|
-
}
|
|
476
|
-
} catch (e) {
|
|
477
|
-
log(`[updateProfile] ${label}: trigger click failed: ${e.message} — trying input method`);
|
|
478
|
-
}
|
|
479
|
-
|
|
480
|
-
// ── FALLBACK: set file directly on the correct hidden input ──────────────
|
|
481
|
-
try {
|
|
482
|
-
const inputs = page.locator('input[type="file"], [data-testid="fileInput"]');
|
|
483
|
-
const count = await inputs.count().catch(() => 0);
|
|
484
|
-
if (count > 0) {
|
|
485
|
-
// Try to resolve the correct input index
|
|
486
|
-
const inputIndex = await resolveFileInputIndex(page, kind);
|
|
487
|
-
if (inputIndex >= 0 && count > inputIndex) {
|
|
488
|
-
await inputs.nth(inputIndex).setInputFiles(tempFile);
|
|
489
|
-
log(`[updateProfile] ${label}: file set on resolved input[${inputIndex}]`);
|
|
490
|
-
await sleep(3000);
|
|
491
|
-
const applied = await clickApplyButtonSimple(page, kind);
|
|
492
|
-
if (applied) {
|
|
493
|
-
log(`[updateProfile] ${label}: Apply clicked — uploaded`);
|
|
494
|
-
await sleep(2000);
|
|
495
|
-
return true;
|
|
496
|
-
}
|
|
497
|
-
log(`[updateProfile] ${label}: Apply not shown — assuming upload succeeded`);
|
|
498
|
-
await sleep(1000);
|
|
499
|
-
return true;
|
|
500
|
-
}
|
|
501
|
-
|
|
502
|
-
// If we can't resolve which input, try each one (for single-input pages)
|
|
503
|
-
if (count === 1) {
|
|
504
|
-
await inputs.nth(0).setInputFiles(tempFile);
|
|
505
|
-
log(`[updateProfile] ${label}: file set on only input[0]`);
|
|
506
|
-
await sleep(3000);
|
|
507
|
-
const applied = await clickApplyButtonSimple(page, kind);
|
|
508
|
-
if (applied) {
|
|
509
|
-
log(`[updateProfile] ${label}: Apply clicked — uploaded`);
|
|
510
|
-
await sleep(2000);
|
|
511
|
-
return true;
|
|
512
|
-
}
|
|
513
|
-
log(`[updateProfile] ${label}: Apply not shown — assuming upload succeeded`);
|
|
514
|
-
await sleep(1000);
|
|
515
|
-
return true;
|
|
516
|
-
}
|
|
517
|
-
|
|
518
|
-
log(`[updateProfile] ${label}: could not resolve a safe file input from ${count} input(s)`);
|
|
519
|
-
|
|
520
|
-
// Last resort: for avatar, try the LAST input (lowest on page = avatar)
|
|
521
|
-
// For header, try the FIRST input (topmost = header)
|
|
522
|
-
if (count >= 2) {
|
|
523
|
-
const fallbackIndex = kind === 'header' ? 0 : count - 1;
|
|
524
|
-
log(`[updateProfile] ${label}: trying fallback input[${fallbackIndex}]`);
|
|
525
|
-
await inputs.nth(fallbackIndex).setInputFiles(tempFile);
|
|
526
|
-
log(`[updateProfile] ${label}: file set on fallback input[${fallbackIndex}]`);
|
|
527
|
-
await sleep(3000);
|
|
528
|
-
const applied = await clickApplyButtonSimple(page, kind);
|
|
529
|
-
if (applied) {
|
|
530
|
-
log(`[updateProfile] ${label}: Apply clicked — uploaded (fallback)`);
|
|
531
|
-
await sleep(2000);
|
|
532
|
-
return true;
|
|
533
|
-
}
|
|
534
|
-
log(`[updateProfile] ${label}: Apply not shown — assuming upload succeeded (fallback)`);
|
|
535
|
-
await sleep(1000);
|
|
536
|
-
return true;
|
|
537
|
-
}
|
|
538
|
-
}
|
|
539
|
-
} catch (e) {
|
|
540
|
-
log(`[updateProfile] ${label}: input upload failed: ${e.message}`);
|
|
541
|
-
}
|
|
542
|
-
|
|
543
|
-
log(`[updateProfile] All upload paths exhausted for ${label}`);
|
|
544
|
-
return false;
|
|
545
|
-
}
|
|
546
|
-
|
|
547
|
-
// ── Helper: find the upload trigger button for avatar or header ──────────────
|
|
548
|
-
// On X's profile editor, the avatar has a camera button and the header has an
|
|
549
|
-
// "Add photo" button. We find them by aria-label, data-testid, or position.
|
|
550
|
-
async function findUploadTrigger(page, kind) {
|
|
551
|
-
const trigger = await page.evaluate((imageKind) => {
|
|
552
|
-
// Header-specific: must contain header/banner/cover keywords
|
|
553
|
-
const HEADER_RE = /header|banner|cover|غلاف|خلفية|add banner|add header/i;
|
|
554
|
-
// Avatar-specific: must contain avatar/profile photo keywords (NOT just "add photo")
|
|
555
|
-
const AVATAR_RE = /avatar|profile.?photo|profile.?picture|صورة.?شخصية|صورة.?ملف|add.*photo|camera|كاميرا/i;
|
|
556
|
-
// Generic media-related (for fallback)
|
|
557
|
-
const MEDIA_RE = /photo|image|avatar|header|banner|cover|edit|media|upload|add|غلاف|صورة|تحرير|رفع|كاميرا|camera|svg|icon/i;
|
|
558
|
-
const BACK_RE = /^back$|^رجوع$|^السابق$/i;
|
|
559
|
-
// Only skip clearly unrelated elements (don't skip profileheader — it's the container)
|
|
560
|
-
const SKIP_RE = /tweet-user-avatar|profilebackground|verified|follow|share|save|back|رجوع/i;
|
|
561
|
-
|
|
562
|
-
const seen = new Set();
|
|
563
|
-
const candidates = [];
|
|
564
|
-
|
|
565
|
-
// Look for buttons, role=button, and also divs with click handlers near avatar/header
|
|
566
|
-
// Also look for SVG-containing buttons (camera icons have no text)
|
|
567
|
-
const SELS = [
|
|
568
|
-
'button[aria-label]', '[role="button"][aria-label]',
|
|
569
|
-
'button', '[role="button"]',
|
|
570
|
-
'[data-testid*="banner" i]', '[data-testid*="avatar" i]',
|
|
571
|
-
'[data-testid*="header" i]', '[data-testid*="photo" i]',
|
|
572
|
-
'[data-testid*="edit" i]', '[data-testid*="camera" i]',
|
|
573
|
-
'[data-testid*="upload" i]', '[data-testid*="image" i]',
|
|
574
|
-
// Camera icon buttons — often have no text, just SVG
|
|
575
|
-
'button:has(svg)', '[role="button"]:has(svg)',
|
|
576
|
-
];
|
|
577
|
-
for (const sel of SELS) {
|
|
578
|
-
document.querySelectorAll(sel).forEach((el) => {
|
|
579
|
-
if (seen.has(el)) return; seen.add(el);
|
|
580
|
-
const rect = el.getBoundingClientRect();
|
|
581
|
-
if (rect.width < 8 || rect.height < 8) return;
|
|
582
|
-
if (rect.bottom < 0 || rect.top > window.innerHeight) return;
|
|
583
|
-
const cs = window.getComputedStyle(el);
|
|
584
|
-
if (cs.visibility === 'hidden' || cs.display === 'none' || cs.opacity === '0') return;
|
|
585
|
-
const hint = `${el.getAttribute('aria-label') || ''} ${el.getAttribute('data-testid') || ''} ${el.innerText || ''} ${el.title || ''}`.trim();
|
|
586
|
-
if (BACK_RE.test(hint.trim())) return;
|
|
587
|
-
if (SKIP_RE.test(hint)) return;
|
|
588
|
-
// For SVG-only buttons (camera icons), check if they're positioned over the avatar/header area
|
|
589
|
-
const hasSvg = el.querySelector('svg') !== null;
|
|
590
|
-
if (!MEDIA_RE.test(hint) && !hasSvg) return;
|
|
591
|
-
// If it has an SVG but no text, it might be a camera button — include it
|
|
592
|
-
if (hasSvg && !hint) {
|
|
593
|
-
candidates.push({
|
|
594
|
-
x: rect.left + rect.width / 2,
|
|
595
|
-
y: rect.top + rect.height / 2,
|
|
596
|
-
isHeader: false, // will be determined by position
|
|
597
|
-
isAvatar: false, // will be determined by position
|
|
598
|
-
hint: 'svg-icon-button',
|
|
599
|
-
hasSvg: true,
|
|
600
|
-
rect: { top: rect.top, left: rect.left, width: rect.width, height: rect.height },
|
|
601
|
-
});
|
|
602
|
-
return;
|
|
603
|
-
}
|
|
604
|
-
candidates.push({
|
|
605
|
-
x: rect.left + rect.width / 2,
|
|
606
|
-
y: rect.top + rect.height / 2,
|
|
607
|
-
isHeader: HEADER_RE.test(hint),
|
|
608
|
-
isAvatar: AVATAR_RE.test(hint),
|
|
609
|
-
hint,
|
|
610
|
-
hasSvg,
|
|
611
|
-
rect: { top: rect.top, left: rect.left, width: rect.width, height: rect.height },
|
|
612
|
-
});
|
|
613
|
-
});
|
|
614
|
-
}
|
|
615
|
-
|
|
616
|
-
if (!candidates.length) return null;
|
|
617
|
-
|
|
618
|
-
// Prefer explicit semantic match
|
|
619
|
-
const headerCands = candidates.filter(c => c.isHeader);
|
|
620
|
-
const avatarCands = candidates.filter(c => c.isAvatar);
|
|
621
|
-
if (imageKind === 'header' && headerCands.length) {
|
|
622
|
-
headerCands.sort((a, b) => a.y - b.y);
|
|
623
|
-
return headerCands[0];
|
|
624
|
-
}
|
|
625
|
-
if (imageKind === 'avatar' && avatarCands.length) {
|
|
626
|
-
avatarCands.sort((a, b) => b.y - a.y);
|
|
627
|
-
return avatarCands[0];
|
|
628
|
-
}
|
|
629
|
-
|
|
630
|
-
// Position fallback: header button is ALWAYS above the avatar button
|
|
631
|
-
// On X profile editor: header is at top (~y=100-200), avatar is below (~y=200-350)
|
|
632
|
-
candidates.sort((a, b) => a.y - b.y);
|
|
633
|
-
if (imageKind === 'header') return candidates[0];
|
|
634
|
-
|
|
635
|
-
// For avatar: pick the lowest candidate that's not the header
|
|
636
|
-
// Or if there are SVG-only buttons, pick the one closest to the avatar position
|
|
637
|
-
const svgButtons = candidates.filter(c => c.hasSvg && !c.isHeader);
|
|
638
|
-
if (svgButtons.length > 0 && imageKind === 'avatar') {
|
|
639
|
-
// Avatar camera button is typically the lowest SVG button
|
|
640
|
-
svgButtons.sort((a, b) => b.y - a.y);
|
|
641
|
-
return svgButtons[0];
|
|
642
|
-
}
|
|
643
|
-
|
|
644
|
-
return candidates[candidates.length - 1];
|
|
645
|
-
}, kind).catch(() => null);
|
|
646
|
-
|
|
647
|
-
return trigger;
|
|
648
|
-
}
|
|
649
|
-
|
|
650
|
-
// ── Helper: pick the correct hidden file input index (banner vs avatar) ─────
|
|
651
|
-
// First tries semantic hints in ancestor elements (English + Arabic).
|
|
652
|
-
// Falls back to Y-position of the closest visible ancestor container:
|
|
653
|
-
// top-most container = banner/header, lower container = avatar.
|
|
654
|
-
async function resolveFileInputIndex(page, kind) {
|
|
655
|
-
const index = await page.evaluate((imageKind) => {
|
|
656
|
-
const inputs = Array.from(document.querySelectorAll('input[type="file"]'));
|
|
657
|
-
if (inputs.length === 0) return -1;
|
|
658
|
-
if (inputs.length === 1) return 0; // Only one input — use it
|
|
659
|
-
|
|
660
|
-
const HEADER_RE = /banner|header|cover|غلاف|خلفية/i;
|
|
661
|
-
const AVATAR_RE = /avatar|profile.?photo|profile.?picture|صورة.?شخصية|صورة.?ملف/i;
|
|
662
|
-
const wanted = imageKind === 'header' ? HEADER_RE : AVATAR_RE;
|
|
663
|
-
|
|
664
|
-
// Semantic pass: walk up to 25 ancestors looking for matching hint
|
|
665
|
-
for (let i = 0; i < inputs.length; i++) {
|
|
666
|
-
let el = inputs[i];
|
|
667
|
-
for (let depth = 0; depth < 25 && el; depth++) {
|
|
668
|
-
const hint = `${el.getAttribute('aria-label') || ''} ${el.getAttribute('data-testid') || ''} ${el.innerText || ''}`;
|
|
669
|
-
if (wanted.test(hint)) return i;
|
|
670
|
-
el = el.parentElement;
|
|
671
|
-
}
|
|
672
|
-
}
|
|
673
|
-
|
|
674
|
-
// Position fallback: find each input's nearest visible ancestor container.
|
|
675
|
-
// On X settings/profile the banner container is above the avatar container.
|
|
676
|
-
const getRect = (el) => {
|
|
677
|
-
let cur = el.parentElement;
|
|
678
|
-
while (cur && cur !== document.body) {
|
|
679
|
-
const r = cur.getBoundingClientRect();
|
|
680
|
-
if (r.width > 10 && r.height > 10) return r;
|
|
681
|
-
cur = cur.parentElement;
|
|
682
|
-
}
|
|
683
|
-
return null;
|
|
684
|
-
};
|
|
685
|
-
|
|
686
|
-
const ranked = inputs
|
|
687
|
-
.map((inp, i) => ({ i, y: (getRect(inp) || { top: 99999 }).top }))
|
|
688
|
-
.sort((a, b) => a.y - b.y);
|
|
689
|
-
|
|
690
|
-
// topmost container = banner/header input, lowest = avatar input
|
|
691
|
-
// For avatar: return the LAST (lowest) input
|
|
692
|
-
// For header: return the FIRST (topmost) input
|
|
693
|
-
if (imageKind === 'header') return ranked[0].i;
|
|
694
|
-
return ranked[ranked.length - 1].i;
|
|
695
|
-
}, kind).catch(() => -1);
|
|
696
|
-
|
|
697
|
-
log(`[updateProfile] resolveFileInputIndex => ${index} for ${kind}`);
|
|
698
|
-
return index;
|
|
699
|
-
}
|
|
700
|
-
|
|
701
|
-
// ── Helper: click Apply on the Edit-media cropper (simple, multi-selector) ──
|
|
702
|
-
// Used by the recorded input-index upload method. Tries the Apply button with
|
|
703
|
-
// multiple selectors (data-testid, role+text, button-text — matches the
|
|
704
|
-
// recorded real-user flow) plus Arabic "تطبيق" variants.
|
|
705
|
-
async function clickApplyButtonSimple(page, kind) {
|
|
706
|
-
const applySelectors = [
|
|
707
|
-
'[data-testid="applyButton"]',
|
|
708
|
-
'div[role="button"]:has-text("Apply")',
|
|
709
|
-
'button:has-text("Apply")',
|
|
710
|
-
'[role="button"]:has-text("تطبيق")',
|
|
711
|
-
'button:has-text("تطبيق")',
|
|
712
|
-
];
|
|
713
|
-
|
|
714
|
-
// Wait briefly for the cropper/Apply button to appear
|
|
715
|
-
for (let i = 0; i < 10; i++) {
|
|
716
|
-
for (const selector of applySelectors) {
|
|
717
|
-
const btn = page.locator(selector).last();
|
|
718
|
-
if (await btn.isVisible({ timeout: 400 }).catch(() => false)) {
|
|
719
|
-
const enabled = await btn.isEnabled({ timeout: 1000 }).catch(() => true);
|
|
720
|
-
if (!enabled) { await sleep(400); continue; }
|
|
721
|
-
try {
|
|
722
|
-
await btn.click({ timeout: 5000 });
|
|
723
|
-
log(`[updateProfile] ${kind}: Apply clicked (selector: ${selector})`);
|
|
724
|
-
await sleep(1500);
|
|
725
|
-
return true;
|
|
726
|
-
} catch (e) {
|
|
727
|
-
log(`[updateProfile] ${kind}: Apply click failed: ${e.message}`);
|
|
728
|
-
}
|
|
729
|
-
}
|
|
730
|
-
}
|
|
731
|
-
await sleep(400);
|
|
732
|
-
}
|
|
733
|
-
return false;
|
|
734
|
-
}
|
|
735
|
-
|
|
736
|
-
// ── Helper: wait for cropper preview image to finish loading ────────────────
|
|
737
|
-
async function waitForCropperReady(page, kind, timeoutMs = 30000) {
|
|
738
|
-
log(`[updateProfile] ${kind}: waiting for cropper to be ready...`);
|
|
739
|
-
const applyBtn = page.getByRole('button', { name: /^Apply$/i });
|
|
740
|
-
const deadline = Date.now() + timeoutMs;
|
|
741
|
-
|
|
742
|
-
while (Date.now() < deadline) {
|
|
743
|
-
if (!(await isEditMediaOpen(page))) return false;
|
|
744
|
-
|
|
745
|
-
// Best signal: Apply button visible AND enabled means X finished loading the image
|
|
746
|
-
const applyVisible = await applyBtn.isVisible({ timeout: 300 }).catch(() => false);
|
|
747
|
-
if (applyVisible) {
|
|
748
|
-
const applyEnabled = await applyBtn.isEnabled().catch(() => false);
|
|
749
|
-
if (applyEnabled) {
|
|
750
|
-
log(`[updateProfile] ${kind}: Apply button enabled — cropper ready`);
|
|
751
|
-
await sleep(1500);
|
|
752
|
-
return true;
|
|
753
|
-
}
|
|
754
|
-
}
|
|
755
|
-
|
|
756
|
-
// Fallback: visible blob/canvas preview inside cropper
|
|
757
|
-
const hasPreview = await page.evaluate(() => {
|
|
758
|
-
for (const el of document.querySelectorAll('img, canvas')) {
|
|
759
|
-
const rect = el.getBoundingClientRect();
|
|
760
|
-
if (rect.width < 80 || rect.height < 80) continue;
|
|
761
|
-
if (el.tagName === 'CANVAS') return true;
|
|
762
|
-
if (el.tagName === 'IMG') {
|
|
763
|
-
const src = el.src || '';
|
|
764
|
-
if ((src.startsWith('blob:') || src.startsWith('data:')) && el.complete && el.naturalWidth > 0) {
|
|
765
|
-
return true;
|
|
766
|
-
}
|
|
767
|
-
}
|
|
768
|
-
}
|
|
769
|
-
return false;
|
|
770
|
-
}).catch(() => false);
|
|
771
|
-
|
|
772
|
-
if (hasPreview) {
|
|
773
|
-
log(`[updateProfile] ${kind}: cropper preview visible — waiting for Apply to enable`);
|
|
774
|
-
}
|
|
775
|
-
await sleep(500);
|
|
776
|
-
}
|
|
777
|
-
|
|
778
|
-
log(`[updateProfile] ${kind}: cropper ready wait timed out`);
|
|
779
|
-
return false;
|
|
780
|
-
}
|
|
781
|
-
|
|
782
|
-
async function clickApplyButton(page, kind) {
|
|
783
|
-
const applyBtn = page.getByRole('button', { name: /^Apply$/i });
|
|
784
|
-
if (!(await applyBtn.isVisible({ timeout: 2000 }).catch(() => false))) return false;
|
|
785
|
-
|
|
786
|
-
// Wait up to 10s for Apply to become enabled
|
|
787
|
-
for (let i = 0; i < 20; i++) {
|
|
788
|
-
if (await applyBtn.isEnabled().catch(() => false)) break;
|
|
789
|
-
await sleep(500);
|
|
790
|
-
}
|
|
791
|
-
|
|
792
|
-
try {
|
|
793
|
-
const box = await applyBtn.boundingBox();
|
|
794
|
-
if (box) {
|
|
795
|
-
const cx = box.x + box.width / 2 + (Math.random() * 4 - 2);
|
|
796
|
-
const cy = box.y + box.height / 2 + (Math.random() * 4 - 2);
|
|
797
|
-
await page.mouse.move(cx, cy, { steps: 4 });
|
|
798
|
-
await randDelay(100, 200);
|
|
799
|
-
await page.mouse.click(cx, cy);
|
|
800
|
-
log(`[updateProfile] ${kind} Apply clicked via mouse`);
|
|
801
|
-
return true;
|
|
802
|
-
}
|
|
803
|
-
await applyBtn.click({ force: true, timeout: 5000 });
|
|
804
|
-
log(`[updateProfile] ${kind} Apply clicked via getByRole`);
|
|
805
|
-
return true;
|
|
806
|
-
} catch (e) {
|
|
807
|
-
log(`[updateProfile] ${kind} Apply click failed: ${e.message}`);
|
|
808
|
-
}
|
|
809
|
-
|
|
810
|
-
// JS fallback
|
|
811
|
-
return page.evaluate(() => {
|
|
812
|
-
const applyBtns = [];
|
|
813
|
-
document.querySelectorAll('[role="button"], button').forEach((el) => {
|
|
814
|
-
const ariaLabel = (el.getAttribute('aria-label') || '').trim().toLowerCase();
|
|
815
|
-
const text = (el.innerText || '').trim();
|
|
816
|
-
if (ariaLabel === 'back' || ariaLabel === 'رجوع') return;
|
|
817
|
-
if (text !== 'Apply' && text !== 'تطبيق') return;
|
|
818
|
-
const rect = el.getBoundingClientRect();
|
|
819
|
-
if (rect.width < 8 || rect.height < 8) return;
|
|
820
|
-
applyBtns.push({ el, right: rect.right });
|
|
821
|
-
});
|
|
822
|
-
if (!applyBtns.length) return false;
|
|
823
|
-
applyBtns.sort((a, b) => b.right - a.right);
|
|
824
|
-
applyBtns[0].el.click();
|
|
825
|
-
return true;
|
|
826
|
-
}).catch(() => false);
|
|
827
|
-
}
|
|
828
|
-
|
|
829
|
-
// ── Helper: confirm "Edit media" cropper (click Apply — NOT Back) ───────────
|
|
830
|
-
// X opens an "Edit media" sheet after file selection. Top-left = Back arrow,
|
|
831
|
-
// top-right = Apply (black filled button). We must wait for the image preview,
|
|
832
|
-
// click Apply, then wait for the sheet to close before touching Save.
|
|
833
|
-
async function isEditMediaOpen(page) {
|
|
834
|
-
return page.getByText('Edit media', { exact: true }).first()
|
|
835
|
-
.isVisible({ timeout: 800 }).catch(() => false);
|
|
836
|
-
}
|
|
837
|
-
|
|
838
|
-
async function confirmMediaEdit(page, kind) {
|
|
839
|
-
// Wait for the cropper sheet to appear (up to 8s)
|
|
840
|
-
let modalOpen = false;
|
|
841
|
-
for (let i = 0; i < 16; i++) {
|
|
842
|
-
if (await isEditMediaOpen(page)) { modalOpen = true; break; }
|
|
843
|
-
await sleep(500);
|
|
844
|
-
}
|
|
845
|
-
|
|
846
|
-
if (!modalOpen) {
|
|
847
|
-
log(`[updateProfile] ${kind}: no Edit media modal — nothing to confirm`);
|
|
848
|
-
return true;
|
|
849
|
-
}
|
|
850
|
-
|
|
851
|
-
log(`[updateProfile] ${kind}: Edit media modal detected`);
|
|
852
|
-
|
|
853
|
-
// Critical: wait for Apply to become enabled before clicking
|
|
854
|
-
await waitForCropperReady(page, kind);
|
|
855
|
-
|
|
856
|
-
for (let attempt = 1; attempt <= 5; attempt++) {
|
|
857
|
-
if (!(await isEditMediaOpen(page))) {
|
|
858
|
-
log(`[updateProfile] ${kind}: cropper already closed`);
|
|
859
|
-
await sleep(1500);
|
|
860
|
-
return true;
|
|
861
|
-
}
|
|
862
|
-
|
|
863
|
-
log(`[updateProfile] ${kind}: Apply attempt ${attempt}`);
|
|
864
|
-
await clickApplyButton(page, kind);
|
|
865
|
-
await sleep(1200);
|
|
866
|
-
|
|
867
|
-
if (!(await isEditMediaOpen(page))) {
|
|
868
|
-
log(`[updateProfile] ${kind}: cropper closed after Apply (attempt ${attempt})`);
|
|
869
|
-
await sleep(2000);
|
|
870
|
-
return true;
|
|
871
|
-
}
|
|
872
|
-
await sleep(800);
|
|
873
|
-
}
|
|
874
|
-
|
|
875
|
-
log(`[updateProfile] ${kind} Edit media still open after 5 Apply attempts`);
|
|
876
|
-
return false;
|
|
877
|
-
}
|
|
878
|
-
|
|
879
|
-
// ── Helper: wait until the profile Save button is enabled ─────────────────
|
|
880
|
-
async function waitForSaveButtonReady(page, label, timeoutMs = 15000) {
|
|
881
|
-
const saveBtn = page.locator('[data-testid="Profile_Save_Button"]').first();
|
|
882
|
-
const deadline = Date.now() + timeoutMs;
|
|
883
|
-
while (Date.now() < deadline) {
|
|
884
|
-
const visible = await saveBtn.isVisible({ timeout: 500 }).catch(() => false);
|
|
885
|
-
if (!visible) { await sleep(400); continue; }
|
|
886
|
-
const enabled = await saveBtn.isEnabled().catch(() => false);
|
|
887
|
-
if (enabled) {
|
|
888
|
-
log(`[updateProfile] Save button ready (${label})`);
|
|
889
|
-
return saveBtn;
|
|
890
|
-
}
|
|
891
|
-
await sleep(400);
|
|
892
|
-
}
|
|
893
|
-
log(`[updateProfile] Save button not ready within ${timeoutMs}ms (${label})`);
|
|
894
|
-
return null;
|
|
895
|
-
}
|
|
896
|
-
|
|
897
|
-
// ── Helper: click Save and wait for X to finish persisting ──────────────────
|
|
898
|
-
async function waitForSaveComplete(page, label, timeoutMs = 25000) {
|
|
899
|
-
const saveBtn = page.locator('[data-testid="Profile_Save_Button"]').first();
|
|
900
|
-
const deadline = Date.now() + timeoutMs;
|
|
901
|
-
while (Date.now() < deadline) {
|
|
902
|
-
const url = page.url();
|
|
903
|
-
if (url.includes('/home') || url === 'https://x.com/' || url === 'https://x.com') {
|
|
904
|
-
log(`[updateProfile] Save complete — redirected to home (${label})`);
|
|
905
|
-
await sleep(2500);
|
|
906
|
-
return true;
|
|
907
|
-
}
|
|
908
|
-
|
|
909
|
-
const bodyText = await getBodyText(page).catch(() => '');
|
|
910
|
-
if (/profile.*updated|changes saved|saved successfully/i.test(bodyText)) {
|
|
911
|
-
log(`[updateProfile] Save complete — success message (${label})`);
|
|
912
|
-
await sleep(2000);
|
|
913
|
-
return true;
|
|
914
|
-
}
|
|
915
|
-
|
|
916
|
-
// Still on settings: Save button disabled = no pending changes = saved
|
|
917
|
-
if (url.includes('/settings/profile')) {
|
|
918
|
-
const saveVisible = await saveBtn.isVisible({ timeout: 300 }).catch(() => false);
|
|
919
|
-
if (saveVisible) {
|
|
920
|
-
const enabled = await saveBtn.isEnabled().catch(() => true);
|
|
921
|
-
if (!enabled) {
|
|
922
|
-
log(`[updateProfile] Save complete — Save button disabled (${label})`);
|
|
923
|
-
await sleep(2000);
|
|
924
|
-
return true;
|
|
925
|
-
}
|
|
926
|
-
}
|
|
927
|
-
}
|
|
928
|
-
|
|
929
|
-
await sleep(500);
|
|
930
|
-
}
|
|
931
|
-
log(`[updateProfile] Save did not confirm within ${timeoutMs}ms (${label}), URL: ${page.url()}`);
|
|
932
|
-
return false;
|
|
933
|
-
}
|
|
934
|
-
|
|
935
|
-
// ── Update profile by clicks only ───────────────────────────────────────────
|
|
936
|
-
// No page.goto(). Browser must already be on X and logged in.
|
|
937
|
-
|
|
938
|
-
async function updateProfile(page, payload = {}) {
|
|
939
|
-
const {
|
|
940
|
-
name,
|
|
941
|
-
bio,
|
|
942
|
-
location,
|
|
943
|
-
avatarUrl,
|
|
944
|
-
avatarBase64,
|
|
945
|
-
headerUrl,
|
|
946
|
-
headerBase64,
|
|
947
|
-
} = payload;
|
|
948
|
-
|
|
949
|
-
const fs = require('fs');
|
|
950
|
-
const path = require('path');
|
|
951
|
-
const os = require('os');
|
|
952
|
-
|
|
953
|
-
const hasOwn = (obj, key) => Object.prototype.hasOwnProperty.call(obj, key);
|
|
954
|
-
|
|
955
|
-
const wants = {
|
|
956
|
-
header: !!(headerBase64 || headerUrl),
|
|
957
|
-
avatar: !!(avatarBase64 || avatarUrl),
|
|
958
|
-
name: typeof name === 'string' && name.trim().length > 0,
|
|
959
|
-
bio: hasOwn(payload, 'bio') && typeof bio === 'string',
|
|
960
|
-
location: hasOwn(payload, 'location') && typeof location === 'string',
|
|
961
|
-
};
|
|
962
|
-
|
|
963
|
-
const requestedFields = Object.keys(wants).filter((key) => wants[key]);
|
|
964
|
-
const stagedFields = new Set();
|
|
965
|
-
const partialFailures = [];
|
|
966
|
-
|
|
967
|
-
const logMsg = (msg) => {
|
|
968
|
-
if (typeof log === 'function') log(msg);
|
|
969
|
-
else console.log(msg);
|
|
970
|
-
};
|
|
971
|
-
|
|
972
|
-
const wait = async (ms) => {
|
|
973
|
-
if (typeof sleep === 'function') return sleep(ms);
|
|
974
|
-
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
975
|
-
};
|
|
976
|
-
|
|
977
|
-
const locatorFrom = (spec) => {
|
|
978
|
-
if (typeof spec === 'function') return spec(page);
|
|
979
|
-
return page.locator(spec);
|
|
980
|
-
};
|
|
981
|
-
|
|
982
|
-
async function isVisible(locator, timeout = 3000) {
|
|
983
|
-
try {
|
|
984
|
-
await locator.first().waitFor({ state: 'visible', timeout });
|
|
985
|
-
return true;
|
|
986
|
-
} catch {
|
|
987
|
-
return false;
|
|
988
|
-
}
|
|
989
|
-
}
|
|
990
|
-
|
|
991
|
-
async function firstVisible(specs, label, timeout = 8000) {
|
|
992
|
-
for (const spec of specs) {
|
|
993
|
-
try {
|
|
994
|
-
const locator = locatorFrom(spec).first();
|
|
995
|
-
await locator.waitFor({ state: 'visible', timeout });
|
|
996
|
-
return locator;
|
|
997
|
-
} catch {}
|
|
998
|
-
}
|
|
999
|
-
|
|
1000
|
-
throw new Error(`Could not find visible element: ${label}`);
|
|
1001
|
-
}
|
|
1002
|
-
|
|
1003
|
-
async function clickFirst(specs, label, timeout = 8000) {
|
|
1004
|
-
const locator = await firstVisible(specs, label, timeout);
|
|
1005
|
-
|
|
1006
|
-
try {
|
|
1007
|
-
if (typeof humanHover === 'function') {
|
|
1008
|
-
await humanHover(page, locator).catch(() => {});
|
|
1009
|
-
}
|
|
1010
|
-
|
|
1011
|
-
if (typeof highlightElement === 'function') {
|
|
1012
|
-
await highlightElement(page, locator, '#00ff00', label).catch(() => {});
|
|
1013
|
-
}
|
|
1014
|
-
|
|
1015
|
-
await locator.click({ timeout });
|
|
1016
|
-
logMsg(`[updateProfile] Clicked: ${label}`);
|
|
1017
|
-
return locator;
|
|
1018
|
-
} catch (e) {
|
|
1019
|
-
throw new Error(`Could not click ${label}: ${e.message}`);
|
|
1020
|
-
}
|
|
1021
|
-
}
|
|
1022
|
-
|
|
1023
|
-
async function fillFirst(specs, value, label) {
|
|
1024
|
-
const locator = await firstVisible(specs, label, 8000);
|
|
1025
|
-
|
|
1026
|
-
try {
|
|
1027
|
-
if (typeof humanHover === 'function') {
|
|
1028
|
-
await humanHover(page, locator).catch(() => {});
|
|
1029
|
-
}
|
|
1030
|
-
|
|
1031
|
-
if (typeof highlightElement === 'function') {
|
|
1032
|
-
await highlightElement(page, locator, '#00ff00', label).catch(() => {});
|
|
1033
|
-
}
|
|
1034
|
-
|
|
1035
|
-
await locator.click({ timeout: 8000 });
|
|
1036
|
-
await page.keyboard.press('Control+A').catch(() => {});
|
|
1037
|
-
await page.keyboard.press('Backspace').catch(() => {});
|
|
1038
|
-
|
|
1039
|
-
if (typeof safeFill === 'function') {
|
|
1040
|
-
await safeFill(page, locator, value);
|
|
1041
|
-
} else {
|
|
1042
|
-
await locator.fill(value, { timeout: 8000 });
|
|
1043
|
-
}
|
|
1044
|
-
|
|
1045
|
-
await wait(500);
|
|
1046
|
-
logMsg(`[updateProfile] Filled ${label}: ${value}`);
|
|
1047
|
-
return true;
|
|
1048
|
-
} catch (e) {
|
|
1049
|
-
throw new Error(`Could not fill ${label}: ${e.message}`);
|
|
1050
|
-
}
|
|
1051
|
-
}
|
|
1052
|
-
|
|
1053
|
-
function markFail(field, reason) {
|
|
1054
|
-
partialFailures.push({ field, reason });
|
|
1055
|
-
logMsg(`[updateProfile] PARTIAL FAILURE — ${field}: ${reason}`);
|
|
1056
|
-
}
|
|
1057
|
-
|
|
1058
|
-
async function assertLoggedInByClicksUI() {
|
|
1059
|
-
const url = page.url();
|
|
1060
|
-
|
|
1061
|
-
if (
|
|
1062
|
-
url.includes('/login') ||
|
|
1063
|
-
url.includes('/i/flow/login') ||
|
|
1064
|
-
url.includes('/account/access')
|
|
1065
|
-
) {
|
|
1066
|
-
throw new Error('Session expired — account needs manual login first');
|
|
1067
|
-
}
|
|
1068
|
-
|
|
1069
|
-
const sidebarReady = await isVisible(
|
|
1070
|
-
page.locator(
|
|
1071
|
-
'[data-testid="AppTabBar_Profile_Link"], [data-testid="AppTabBar_Home_Link"]'
|
|
1072
|
-
),
|
|
1073
|
-
12000
|
|
1074
|
-
);
|
|
1075
|
-
|
|
1076
|
-
if (!sidebarReady) {
|
|
1077
|
-
throw new Error(
|
|
1078
|
-
'X sidebar not found. Open X manually and login first. This function does not paste URLs.'
|
|
1079
|
-
);
|
|
1080
|
-
}
|
|
1081
|
-
}
|
|
1082
|
-
|
|
1083
|
-
async function openProfileEditorByClicks() {
|
|
1084
|
-
await page.bringToFront().catch(() => {});
|
|
1085
|
-
await assertLoggedInByClicksUI();
|
|
1086
|
-
|
|
1087
|
-
const editorAlreadyOpen = await isVisible(
|
|
1088
|
-
page.locator('input[name="displayName"], input[aria-label^="Name"]').first(),
|
|
1089
|
-
1500
|
|
1090
|
-
);
|
|
1091
|
-
|
|
1092
|
-
if (editorAlreadyOpen) {
|
|
1093
|
-
logMsg('[updateProfile] Profile editor already open');
|
|
1094
|
-
return;
|
|
1095
|
-
}
|
|
1096
|
-
|
|
1097
|
-
const editVisible = await isVisible(
|
|
1098
|
-
page.locator('[data-testid="editProfileButton"], div[role="button"]:has-text("Edit profile")'),
|
|
1099
|
-
1500
|
|
1100
|
-
);
|
|
1101
|
-
|
|
1102
|
-
if (!editVisible) {
|
|
1103
|
-
await clickFirst(
|
|
1104
|
-
[
|
|
1105
|
-
'[data-testid="AppTabBar_Profile_Link"]',
|
|
1106
|
-
(p) => p.getByRole('link', { name: /^Profile$/i }),
|
|
1107
|
-
'a[aria-label="Profile"]',
|
|
1108
|
-
'text=Profile',
|
|
1109
|
-
],
|
|
1110
|
-
'Profile'
|
|
1111
|
-
);
|
|
1112
|
-
|
|
1113
|
-
await wait(2500);
|
|
1114
|
-
}
|
|
1115
|
-
|
|
1116
|
-
await clickFirst(
|
|
1117
|
-
[
|
|
1118
|
-
'[data-testid="editProfileButton"]',
|
|
1119
|
-
(p) => p.getByRole('button', { name: /^Edit profile$/i }),
|
|
1120
|
-
'div[role="button"]:has-text("Edit profile")',
|
|
1121
|
-
'button:has-text("Edit profile")',
|
|
1122
|
-
'text=Edit profile',
|
|
1123
|
-
],
|
|
1124
|
-
'Edit profile'
|
|
1125
|
-
);
|
|
1126
|
-
|
|
1127
|
-
await firstVisible(
|
|
1128
|
-
[
|
|
1129
|
-
'input[name="displayName"]',
|
|
1130
|
-
'input[aria-label^="Name"]',
|
|
1131
|
-
],
|
|
1132
|
-
'profile name input',
|
|
1133
|
-
12000
|
|
1134
|
-
);
|
|
1135
|
-
|
|
1136
|
-
logMsg('[updateProfile] Profile editor opened by clicks');
|
|
1137
|
-
}
|
|
1138
|
-
|
|
1139
|
-
async function imageToTempFileLocal(url, base64, label) {
|
|
1140
|
-
if (typeof imageToTempFile === 'function') {
|
|
1141
|
-
return imageToTempFile(url, base64);
|
|
1142
|
-
}
|
|
1143
|
-
|
|
1144
|
-
// Detect actual image format from base64 data URI prefix
|
|
1145
|
-
let ext = 'jpg';
|
|
1146
|
-
if (base64 && base64.includes(',')) {
|
|
1147
|
-
const prefix = base64.split(',').shift().toLowerCase();
|
|
1148
|
-
if (prefix.includes('png')) ext = 'png';
|
|
1149
|
-
else if (prefix.includes('webp')) ext = 'webp';
|
|
1150
|
-
else if (prefix.includes('jpeg') || prefix.includes('jpg')) ext = 'jpg';
|
|
1151
|
-
}
|
|
1152
|
-
|
|
1153
|
-
const tmpFile = path.join(os.tmpdir(), `x-${label}-${Date.now()}.${ext}`);
|
|
1154
|
-
|
|
1155
|
-
if (base64) {
|
|
1156
|
-
const cleanBase64 = base64.includes(',')
|
|
1157
|
-
? base64.split(',').pop()
|
|
1158
|
-
: base64;
|
|
1159
|
-
|
|
1160
|
-
fs.writeFileSync(tmpFile, Buffer.from(cleanBase64, 'base64'));
|
|
1161
|
-
logMsg(`[updateProfile] ${label}: temp file created: ${tmpFile} (${ext}, ${(Buffer.from(cleanBase64, 'base64').length / 1024).toFixed(1)} KB)`);
|
|
1162
|
-
return tmpFile;
|
|
1163
|
-
}
|
|
1164
|
-
|
|
1165
|
-
if (url) {
|
|
1166
|
-
if (typeof fetch !== 'function') {
|
|
1167
|
-
throw new Error('fetch is not available. Use avatarBase64/headerBase64 instead of URL.');
|
|
1168
|
-
}
|
|
1169
|
-
|
|
1170
|
-
const res = await fetch(url);
|
|
1171
|
-
if (!res.ok) throw new Error(`Image download failed: ${res.status}`);
|
|
1172
|
-
|
|
1173
|
-
const buffer = Buffer.from(await res.arrayBuffer());
|
|
1174
|
-
fs.writeFileSync(tmpFile, buffer);
|
|
1175
|
-
return tmpFile;
|
|
1176
|
-
}
|
|
1177
|
-
|
|
1178
|
-
throw new Error(`No image source provided for ${label}`);
|
|
1179
|
-
}
|
|
1180
|
-
|
|
1181
|
-
async function stageImage(field, url, base64) {
|
|
1182
|
-
let tmpFile = null;
|
|
1183
|
-
|
|
1184
|
-
try {
|
|
1185
|
-
tmpFile = await imageToTempFileLocal(url, base64, field);
|
|
1186
|
-
logMsg(`[updateProfile] ${field} temp file: ${tmpFile} (${url ? 'url' : 'base64'} source)`);
|
|
1187
|
-
|
|
1188
|
-
if (typeof humanScroll === 'function') {
|
|
1189
|
-
await humanScroll(page, 40 + Math.random() * 80).catch(() => {});
|
|
1190
|
-
}
|
|
1191
|
-
|
|
1192
|
-
await wait(700);
|
|
1193
|
-
|
|
1194
|
-
if (typeof uploadProfileImage !== 'function') {
|
|
1195
|
-
throw new Error('uploadProfileImage helper is missing');
|
|
1196
|
-
}
|
|
1197
|
-
|
|
1198
|
-
const uploaded = await uploadProfileImage(page, tmpFile, field);
|
|
1199
|
-
|
|
1200
|
-
if (!uploaded) {
|
|
1201
|
-
markFail(field, 'upload trigger or file input not found');
|
|
1202
|
-
return false;
|
|
1203
|
-
}
|
|
1204
|
-
|
|
1205
|
-
stagedFields.add(field);
|
|
1206
|
-
logMsg(`[updateProfile] ${field} staged successfully`);
|
|
1207
|
-
return true;
|
|
1208
|
-
} catch (e) {
|
|
1209
|
-
markFail(field, e.message);
|
|
1210
|
-
return false;
|
|
1211
|
-
} finally {
|
|
1212
|
-
if (tmpFile) {
|
|
1213
|
-
try {
|
|
1214
|
-
fs.unlinkSync(tmpFile);
|
|
1215
|
-
} catch {}
|
|
1216
|
-
}
|
|
1217
|
-
}
|
|
1218
|
-
}
|
|
1219
|
-
|
|
1220
|
-
async function clickSaveOnce() {
|
|
1221
|
-
// STEP 1: Make sure no "Edit media" cropper is open — close it first by clicking Apply
|
|
1222
|
-
if (typeof isEditMediaOpen === 'function') {
|
|
1223
|
-
let mediaOpen = await isEditMediaOpen(page).catch(() => false);
|
|
1224
|
-
let attempts = 0;
|
|
1225
|
-
while (mediaOpen && attempts < 3) {
|
|
1226
|
-
logMsg(`[updateProfile] Edit media modal still open — clicking Apply (attempt ${attempts + 1})`);
|
|
1227
|
-
if (typeof confirmMediaEdit === 'function') {
|
|
1228
|
-
const closed = await confirmMediaEdit(page, 'All');
|
|
1229
|
-
if (!closed) {
|
|
1230
|
-
logMsg('[updateProfile] ⚠️ Could not close Edit media modal');
|
|
1231
|
-
break;
|
|
1232
|
-
}
|
|
1233
|
-
}
|
|
1234
|
-
await wait(1500);
|
|
1235
|
-
mediaOpen = await isEditMediaOpen(page).catch(() => false);
|
|
1236
|
-
attempts += 1;
|
|
1237
|
-
}
|
|
1238
|
-
if (mediaOpen) {
|
|
1239
|
-
logMsg('[updateProfile] ⚠️ Edit media modal still open after all attempts — pressing Escape');
|
|
1240
|
-
await page.keyboard.press('Escape').catch(() => {});
|
|
1241
|
-
await wait(1000);
|
|
1242
|
-
}
|
|
1243
|
-
}
|
|
1244
|
-
|
|
1245
|
-
// STEP 2: Wait for any pending image processing (cropper, upload, etc.)
|
|
1246
|
-
// X needs a moment to fully process the image after Apply before Save is enabled
|
|
1247
|
-
logMsg('[updateProfile] Waiting for image to finish processing...');
|
|
1248
|
-
await wait(3000);
|
|
1249
|
-
|
|
1250
|
-
// STEP 3: Wait for the profile Save button to become enabled
|
|
1251
|
-
let saveBtn = null;
|
|
1252
|
-
logMsg('[updateProfile] Waiting for Save button to be ready...');
|
|
1253
|
-
if (typeof waitForSaveButtonReady === 'function') {
|
|
1254
|
-
saveBtn = await waitForSaveButtonReady(page, 'All', 20000);
|
|
1255
|
-
}
|
|
1256
|
-
|
|
1257
|
-
if (!saveBtn) {
|
|
1258
|
-
// Retry once more — maybe the image is still processing
|
|
1259
|
-
logMsg('[updateProfile] Save button not ready, waiting longer and retrying...');
|
|
1260
|
-
await wait(3000);
|
|
1261
|
-
if (typeof waitForSaveButtonReady === 'function') {
|
|
1262
|
-
saveBtn = await waitForSaveButtonReady(page, 'All', 15000);
|
|
1263
|
-
}
|
|
1264
|
-
}
|
|
1265
|
-
|
|
1266
|
-
if (!saveBtn) {
|
|
1267
|
-
// Final fallback — just find any visible Save button
|
|
1268
|
-
saveBtn = await firstVisible(
|
|
1269
|
-
[
|
|
1270
|
-
'[data-testid="Profile_Save_Button"]',
|
|
1271
|
-
(p) => p.getByRole('button', { name: /^Save$/i }),
|
|
1272
|
-
'div[role="button"]:has-text("Save")',
|
|
1273
|
-
'button:has-text("Save")',
|
|
1274
|
-
'text=Save',
|
|
1275
|
-
],
|
|
1276
|
-
'Save button',
|
|
1277
|
-
10000
|
|
1278
|
-
);
|
|
1279
|
-
}
|
|
1280
|
-
|
|
1281
|
-
if (typeof highlightElement === 'function') {
|
|
1282
|
-
await highlightElement(page, saveBtn, 'red', 'SAVE').catch(() => {});
|
|
1283
|
-
}
|
|
1284
|
-
|
|
1285
|
-
if (typeof randDelay === 'function') {
|
|
1286
|
-
await randDelay(500, 1000).catch(() => {});
|
|
1287
|
-
} else {
|
|
1288
|
-
await wait(800);
|
|
1289
|
-
}
|
|
1290
|
-
|
|
1291
|
-
// STEP 4: Click Save
|
|
1292
|
-
await saveBtn.click({ timeout: 10000 });
|
|
1293
|
-
logMsg('[updateProfile] ✅ Save clicked');
|
|
1294
|
-
|
|
1295
|
-
// STEP 5: Wait for save to complete
|
|
1296
|
-
if (typeof waitForSaveComplete === 'function') {
|
|
1297
|
-
return waitForSaveComplete(page, 'All');
|
|
1298
|
-
}
|
|
1299
|
-
|
|
1300
|
-
await wait(6000);
|
|
1301
|
-
return true;
|
|
1302
|
-
}
|
|
1303
|
-
|
|
1304
|
-
async function getBodyTextSafe() {
|
|
1305
|
-
if (typeof getBodyText === 'function') {
|
|
1306
|
-
return getBodyText(page);
|
|
1307
|
-
}
|
|
1308
|
-
|
|
1309
|
-
return page.locator('body').innerText({ timeout: 5000 }).catch(() => '');
|
|
1310
|
-
}
|
|
1311
|
-
|
|
1312
|
-
async function reopenEditorForVerify() {
|
|
1313
|
-
const nameInputVisible = await isVisible(
|
|
1314
|
-
page.locator('input[name="displayName"], input[aria-label^="Name"]').first(),
|
|
1315
|
-
1000
|
|
1316
|
-
);
|
|
1317
|
-
|
|
1318
|
-
if (nameInputVisible) return true;
|
|
1319
|
-
|
|
1320
|
-
await clickFirst(
|
|
1321
|
-
[
|
|
1322
|
-
'[data-testid="editProfileButton"]',
|
|
1323
|
-
(p) => p.getByRole('button', { name: /^Edit profile$/i }),
|
|
1324
|
-
'div[role="button"]:has-text("Edit profile")',
|
|
1325
|
-
'button:has-text("Edit profile")',
|
|
1326
|
-
'text=Edit profile',
|
|
1327
|
-
],
|
|
1328
|
-
'Edit profile for verification',
|
|
1329
|
-
10000
|
|
1330
|
-
);
|
|
1331
|
-
|
|
1332
|
-
await firstVisible(
|
|
1333
|
-
[
|
|
1334
|
-
'input[name="displayName"]',
|
|
1335
|
-
'input[aria-label^="Name"]',
|
|
1336
|
-
],
|
|
1337
|
-
'profile editor for verification',
|
|
1338
|
-
10000
|
|
1339
|
-
);
|
|
1340
|
-
|
|
1341
|
-
return true;
|
|
1342
|
-
}
|
|
1343
|
-
|
|
1344
|
-
async function verifyTextFields() {
|
|
1345
|
-
const needVerify = stagedFields.has('name') || stagedFields.has('bio') || stagedFields.has('location');
|
|
1346
|
-
if (!needVerify) return;
|
|
1347
|
-
|
|
1348
|
-
await reopenEditorForVerify();
|
|
1349
|
-
|
|
1350
|
-
if (stagedFields.has('name')) {
|
|
1351
|
-
const currentName = await page
|
|
1352
|
-
.locator('input[name="displayName"], input[aria-label^="Name"]')
|
|
1353
|
-
.first()
|
|
1354
|
-
.inputValue()
|
|
1355
|
-
.catch(() => '');
|
|
1356
|
-
|
|
1357
|
-
if (currentName.trim() !== name.trim()) {
|
|
1358
|
-
markFail('name', `did not persist. Expected "${name}", got "${currentName}"`);
|
|
1359
|
-
}
|
|
1360
|
-
}
|
|
1361
|
-
|
|
1362
|
-
if (stagedFields.has('bio')) {
|
|
1363
|
-
const currentBio = await page
|
|
1364
|
-
.locator('textarea[name="description"], textarea[aria-label^="Bio"]')
|
|
1365
|
-
.first()
|
|
1366
|
-
.inputValue()
|
|
1367
|
-
.catch(() => '');
|
|
1368
|
-
|
|
1369
|
-
if (currentBio.trim() !== bio.trim()) {
|
|
1370
|
-
markFail('bio', `did not persist. Expected "${bio}", got "${currentBio}"`);
|
|
1371
|
-
}
|
|
1372
|
-
}
|
|
1373
|
-
|
|
1374
|
-
if (stagedFields.has('location')) {
|
|
1375
|
-
const currentLocation = await page
|
|
1376
|
-
.locator('input[name="location"], input[aria-label^="Location"]')
|
|
1377
|
-
.first()
|
|
1378
|
-
.inputValue()
|
|
1379
|
-
.catch(() => '');
|
|
1380
|
-
|
|
1381
|
-
if (currentLocation.trim() !== location.trim()) {
|
|
1382
|
-
markFail('location', `did not persist. Expected "${location}", got "${currentLocation}"`);
|
|
1383
|
-
}
|
|
1384
|
-
}
|
|
1385
|
-
|
|
1386
|
-
await page.keyboard.press('Escape').catch(() => {});
|
|
1387
|
-
}
|
|
1388
|
-
|
|
1389
|
-
async function captureFailureContext(reason) {
|
|
1390
|
-
const ctx = { reason };
|
|
1391
|
-
|
|
1392
|
-
try {
|
|
1393
|
-
const shot = await page.screenshot({
|
|
1394
|
-
type: 'png',
|
|
1395
|
-
fullPage: false,
|
|
1396
|
-
timeout: 5000,
|
|
1397
|
-
});
|
|
1398
|
-
|
|
1399
|
-
ctx.screenshotBase64 = shot.toString('base64');
|
|
1400
|
-
} catch (e) {
|
|
1401
|
-
ctx.screenshotError = e.message;
|
|
1402
|
-
}
|
|
1403
|
-
|
|
1404
|
-
return ctx;
|
|
1405
|
-
}
|
|
1406
|
-
|
|
1407
|
-
// ── Start ────────────────────────────────────────────────────────────────
|
|
1408
|
-
|
|
1409
|
-
await openProfileEditorByClicks();
|
|
1410
|
-
|
|
1411
|
-
if (wants.avatar) {
|
|
1412
|
-
await stageImage('avatar', avatarUrl, avatarBase64);
|
|
1413
|
-
}
|
|
1414
|
-
|
|
1415
|
-
if (wants.header) {
|
|
1416
|
-
await stageImage('header', headerUrl, headerBase64);
|
|
1417
|
-
}
|
|
1418
|
-
|
|
1419
|
-
if (wants.name) {
|
|
1420
|
-
try {
|
|
1421
|
-
await fillFirst(
|
|
1422
|
-
[
|
|
1423
|
-
'input[name="displayName"]',
|
|
1424
|
-
'input[aria-label^="Name"]',
|
|
1425
|
-
],
|
|
1426
|
-
name,
|
|
1427
|
-
'Name'
|
|
1428
|
-
);
|
|
1429
|
-
|
|
1430
|
-
stagedFields.add('name');
|
|
1431
|
-
} catch (e) {
|
|
1432
|
-
markFail('name', e.message);
|
|
1433
|
-
}
|
|
1434
|
-
}
|
|
1435
|
-
|
|
1436
|
-
if (wants.bio) {
|
|
1437
|
-
try {
|
|
1438
|
-
await fillFirst(
|
|
1439
|
-
[
|
|
1440
|
-
'textarea[name="description"]',
|
|
1441
|
-
'textarea[aria-label^="Bio"]',
|
|
1442
|
-
],
|
|
1443
|
-
bio,
|
|
1444
|
-
'Bio'
|
|
1445
|
-
);
|
|
1446
|
-
|
|
1447
|
-
stagedFields.add('bio');
|
|
1448
|
-
} catch (e) {
|
|
1449
|
-
markFail('bio', e.message);
|
|
1450
|
-
}
|
|
1451
|
-
}
|
|
1452
|
-
|
|
1453
|
-
if (wants.location) {
|
|
1454
|
-
try {
|
|
1455
|
-
await fillFirst(
|
|
1456
|
-
[
|
|
1457
|
-
'input[name="location"]',
|
|
1458
|
-
'input[aria-label^="Location"]',
|
|
1459
|
-
],
|
|
1460
|
-
location,
|
|
1461
|
-
'Location'
|
|
1462
|
-
);
|
|
1463
|
-
|
|
1464
|
-
stagedFields.add('location');
|
|
1465
|
-
} catch (e) {
|
|
1466
|
-
markFail('location', e.message);
|
|
1467
|
-
}
|
|
1468
|
-
}
|
|
1469
|
-
|
|
1470
|
-
if (stagedFields.size === 0) {
|
|
1471
|
-
const ctx = await captureFailureContext('No requested changes were staged');
|
|
1472
|
-
throw Object.assign(
|
|
1473
|
-
new Error('Profile update failed — no requested changes were staged'),
|
|
1474
|
-
{ failureContext: ctx, partialFailures }
|
|
1475
|
-
);
|
|
1476
|
-
}
|
|
1477
|
-
|
|
1478
|
-
await wait(1200);
|
|
1479
|
-
|
|
1480
|
-
const saved = await clickSaveOnce();
|
|
1481
|
-
|
|
1482
|
-
if (!saved) {
|
|
1483
|
-
for (const field of stagedFields) {
|
|
1484
|
-
markFail(field, 'Save did not complete');
|
|
1485
|
-
}
|
|
1486
|
-
|
|
1487
|
-
const ctx = await captureFailureContext('Save did not complete');
|
|
1488
|
-
throw Object.assign(
|
|
1489
|
-
new Error('Profile update failed — Save did not complete'),
|
|
1490
|
-
{ failureContext: ctx, partialFailures }
|
|
1491
|
-
);
|
|
1492
|
-
}
|
|
1493
|
-
|
|
1494
|
-
await wait(4000);
|
|
1495
|
-
|
|
1496
|
-
const bodyText = (await getBodyTextSafe()).toLowerCase();
|
|
1497
|
-
|
|
1498
|
-
const errorPhrases = [
|
|
1499
|
-
'something went wrong',
|
|
1500
|
-
'please try again',
|
|
1501
|
-
'failed to update',
|
|
1502
|
-
"couldn't update",
|
|
1503
|
-
"name can't be blank",
|
|
1504
|
-
'bio is too long',
|
|
1505
|
-
'there was an error',
|
|
1506
|
-
'unable to save',
|
|
1507
|
-
'some media was not uploaded',
|
|
1508
|
-
'media was not uploaded',
|
|
1509
|
-
];
|
|
1510
|
-
|
|
1511
|
-
const hasError = errorPhrases.some((phrase) => bodyText.includes(phrase));
|
|
1512
|
-
|
|
1513
|
-
if (hasError) {
|
|
1514
|
-
const ctx = await captureFailureContext('X rejected the profile update');
|
|
1515
|
-
throw Object.assign(
|
|
1516
|
-
new Error('X rejected the profile update. Account may need manual check.'),
|
|
1517
|
-
{ failureContext: ctx, partialFailures }
|
|
1518
|
-
);
|
|
1519
|
-
}
|
|
1520
|
-
|
|
1521
|
-
await verifyTextFields();
|
|
1522
|
-
|
|
1523
|
-
const failedFields = new Set(partialFailures.map((f) => f.field));
|
|
1524
|
-
const allRequestedFailed =
|
|
1525
|
-
requestedFields.length > 0 &&
|
|
1526
|
-
requestedFields.every((field) => failedFields.has(field));
|
|
1527
|
-
|
|
1528
|
-
if (allRequestedFailed) {
|
|
1529
|
-
const ctx = await captureFailureContext('All requested fields failed');
|
|
1530
|
-
throw Object.assign(
|
|
1531
|
-
new Error('Profile update failed — all requested fields failed'),
|
|
1532
|
-
{ failureContext: ctx, partialFailures }
|
|
1533
|
-
);
|
|
1534
|
-
}
|
|
1535
|
-
|
|
1536
|
-
const result = {
|
|
1537
|
-
success: true,
|
|
1538
|
-
message: 'Profile updated by clicks and verified',
|
|
1539
|
-
};
|
|
1540
|
-
|
|
1541
|
-
if (partialFailures.length) {
|
|
1542
|
-
result.partialFailures = partialFailures;
|
|
1543
|
-
}
|
|
1544
|
-
|
|
1545
|
-
logMsg('[updateProfile] Profile update completed');
|
|
1546
|
-
return result;
|
|
1547
|
-
}
|
|
1548
|
-
|
|
1549
|
-
// ── Change password ──────────────────────────────────────────────────────────
|
|
1550
|
-
async function changePassword(page, payload) {
|
|
1551
|
-
const { currentPassword, newPassword } = payload;
|
|
1552
|
-
|
|
1553
|
-
await page.goto('https://x.com/settings/password', { waitUntil: 'domcontentloaded', timeout: 30000 }).catch(() => {});
|
|
1554
|
-
await sleep(2000);
|
|
1555
|
-
|
|
1556
|
-
if (page.url().includes('/login') || page.url().includes('/i/flow/login')) {
|
|
1557
|
-
throw new Error('Session expired — account needs to log in first');
|
|
1558
|
-
}
|
|
1559
|
-
|
|
1560
|
-
// Fill current password
|
|
1561
|
-
const currentSelectors = ['input[aria-label="Current password"]', 'input[name="current_password"]', 'input[autocomplete="current-password"]'];
|
|
1562
|
-
for (const sel of currentSelectors) {
|
|
1563
|
-
const el = page.locator(sel).first();
|
|
1564
|
-
if (await el.isVisible({ timeout: 3000 }).catch(() => false)) {
|
|
1565
|
-
await safeFill(page, el, currentPassword);
|
|
1566
|
-
break;
|
|
1567
|
-
}
|
|
1568
|
-
}
|
|
1569
|
-
|
|
1570
|
-
// Fill new password
|
|
1571
|
-
const newSelectors = ['input[aria-label="New password"]', 'input[name="new_password"]', 'input[autocomplete="new-password"]'];
|
|
1572
|
-
for (const sel of newSelectors) {
|
|
1573
|
-
const el = page.locator(sel).first();
|
|
1574
|
-
if (await el.isVisible({ timeout: 3000 }).catch(() => false)) {
|
|
1575
|
-
await safeFill(page, el, newPassword);
|
|
1576
|
-
break;
|
|
1577
|
-
}
|
|
1578
|
-
}
|
|
1579
|
-
|
|
1580
|
-
// Confirm
|
|
1581
|
-
const confirmSelectors = ['input[aria-label="Confirm password"]', 'input[name="password_confirmation"]'];
|
|
1582
|
-
for (const sel of confirmSelectors) {
|
|
1583
|
-
const el = page.locator(sel).first();
|
|
1584
|
-
if (await el.isVisible({ timeout: 3000 }).catch(() => false)) {
|
|
1585
|
-
await safeFill(page, el, newPassword);
|
|
1586
|
-
break;
|
|
1587
|
-
}
|
|
1588
|
-
}
|
|
1589
|
-
|
|
1590
|
-
// Submit
|
|
1591
|
-
const submitSelectors = ['button:has-text("Save")', 'button:has-text("Change password")', '[role="button"]:has-text("Save")'];
|
|
1592
|
-
for (const sel of submitSelectors) {
|
|
1593
|
-
const el = page.locator(sel).first();
|
|
1594
|
-
if (await el.isVisible({ timeout: 3000 }).catch(() => false)) {
|
|
1595
|
-
await humanClick(page, el);
|
|
1596
|
-
break;
|
|
1597
|
-
}
|
|
1598
|
-
}
|
|
1599
|
-
|
|
1600
|
-
await sleep(3000);
|
|
1601
|
-
|
|
1602
|
-
// Check for failure
|
|
1603
|
-
const bodyText = await getBodyText(page);
|
|
1604
|
-
if (bodyText.includes('incorrect password') || bodyText.includes('wrong password')) {
|
|
1605
|
-
return { success: false, error: 'Current password is incorrect' };
|
|
1606
|
-
}
|
|
1607
|
-
|
|
1608
|
-
return { success: true, message: 'Password changed successfully' };
|
|
1609
|
-
}
|
|
1610
|
-
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Session actions — login, check login state, check account status.
|
|
5
|
+
* Ported from src/login.js + backend/routes/browser.js.
|
|
6
|
+
* Includes DBC captcha solving for login challenges.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
const { sleep, humanDelay, randDelay, safeFill, safeClick, humanClick, getBodyText, detectStage, waitForLoggedIn, generateTOTP, injectCookies, SELECTORS, humanHover, idleMouseJitter, humanScroll, logNormalDelay, highlightElement } = require('./helpers');
|
|
10
|
+
const dbc = require('./dbc');
|
|
11
|
+
|
|
12
|
+
// Simple log — writes to agent log via console (captured by agent's log system)
|
|
13
|
+
function log(msg) { console.log(`[session-action] ${msg}`); }
|
|
14
|
+
|
|
15
|
+
// ── Captcha detection ────────────────────────────────────────────────────────
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Detect if there's a captcha/challenge on the page.
|
|
19
|
+
* Returns { hasCaptcha, type, imageSelector } or null.
|
|
20
|
+
*/
|
|
21
|
+
async function detectCaptcha(page) {
|
|
22
|
+
try {
|
|
23
|
+
const bodyText = await getBodyText(page);
|
|
24
|
+
|
|
25
|
+
// Twitter/X challenge patterns
|
|
26
|
+
if (/verify you are human|unusual activity|login challenge|confirm you are a person/i.test(bodyText)) {
|
|
27
|
+
// Look for Arkose Labs / Funcaptcha iframe
|
|
28
|
+
const arkoseFrame = page.frameLocator('iframe[src*="arkose"], iframe[src*="funcaptcha"], iframe[title*="captcha"]');
|
|
29
|
+
if (await arkoseFrame.locator('body').isVisible({ timeout: 2000 }).catch(() => false)) {
|
|
30
|
+
return { hasCaptcha: true, type: 'arkose', imageSelector: null };
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
// Look for image captcha (img tag with captcha)
|
|
34
|
+
const captchaImg = page.locator('img[src*="captcha"], img[alt*="captcha"], #captcha, .captcha img').first();
|
|
35
|
+
if (await captchaImg.isVisible({ timeout: 2000 }).catch(() => false)) {
|
|
36
|
+
return { hasCaptcha: true, type: 'image', imageSelector: 'img[src*="captcha"], img[alt*="captcha"], #captcha img, .captcha img' };
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// Generic captcha container
|
|
40
|
+
const captchaContainer = page.locator('[data-testid="captcha"], [aria-label*="captcha"], canvas').first();
|
|
41
|
+
if (await captchaContainer.isVisible({ timeout: 2000 }).catch(() => false)) {
|
|
42
|
+
return { hasCaptcha: true, type: 'image', imageSelector: '[data-testid="captcha"], [aria-label*="captcha"], canvas' };
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// Challenge present but no recognizable captcha element
|
|
46
|
+
return { hasCaptcha: true, type: 'unknown', imageSelector: null };
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
return null;
|
|
50
|
+
} catch {
|
|
51
|
+
return null;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Attempt to solve an image captcha using DBC.
|
|
57
|
+
* Captures the captcha image, sends to DBC, enters the answer.
|
|
58
|
+
*/
|
|
59
|
+
async function solveCaptchaWithDBC(page, captchaInfo) {
|
|
60
|
+
if (!dbc.isEnabled()) {
|
|
61
|
+
console.log('[captcha] DBC not configured — cannot solve captcha automatically');
|
|
62
|
+
return false;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
if (captchaInfo.type === 'arkose') {
|
|
66
|
+
// Arkose Labs / Funcaptcha — DBC supports this via token-based solving
|
|
67
|
+
// but it requires a different API flow. For now, log and return false.
|
|
68
|
+
console.log('[captcha] Arkose/FunCaptcha detected — DBC image solver cannot handle this type');
|
|
69
|
+
return false;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
if (captchaInfo.type !== 'image') {
|
|
73
|
+
console.log(`[captcha] Unknown captcha type: ${captchaInfo.type}`);
|
|
74
|
+
return false;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
try {
|
|
78
|
+
// Capture the captcha image as screenshot
|
|
79
|
+
const imgLocator = page.locator(captchaInfo.imageSelector).first();
|
|
80
|
+
await imgLocator.waitFor({ state: 'visible', timeout: 5000 });
|
|
81
|
+
|
|
82
|
+
// Take a screenshot of the captcha element
|
|
83
|
+
const imageBuffer = await imgLocator.screenshot();
|
|
84
|
+
console.log(`[captcha] Captured captcha image (${imageBuffer.length} bytes)`);
|
|
85
|
+
|
|
86
|
+
// Send to DBC for solving
|
|
87
|
+
const result = await dbc.solveImageCaptcha(imageBuffer, { timeoutMs: 90000 });
|
|
88
|
+
console.log(`[captcha] DBC returned: "${result.text}"`);
|
|
89
|
+
|
|
90
|
+
// Find the input field for the captcha answer
|
|
91
|
+
const captchaInput = page.locator('input[name="captcha"], input[type="text"][placeholder*="captcha"], input[aria-label*="captcha"], input[name="text"]').first();
|
|
92
|
+
if (await captchaInput.isVisible({ timeout: 5000 }).catch(() => false)) {
|
|
93
|
+
await safeFill(page, captchaInput, result.text);
|
|
94
|
+
await humanDelay(300, 600);
|
|
95
|
+
|
|
96
|
+
// Look for a submit/verify button
|
|
97
|
+
const submitBtn = page.locator('button:has-text("Verify"), button:has-text("Submit"), button:has-text("Continue"), button:has-text("Next"), [role="button"]:has-text("Verify")').first();
|
|
98
|
+
if (await submitBtn.isVisible({ timeout: 3000 }).catch(() => false)) {
|
|
99
|
+
await humanClick(page, submitBtn);
|
|
100
|
+
} else {
|
|
101
|
+
await page.keyboard.press('Enter');
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
await randDelay(3000, 5000);
|
|
105
|
+
return true;
|
|
106
|
+
} else {
|
|
107
|
+
console.log('[captcha] No captcha input field found');
|
|
108
|
+
return false;
|
|
109
|
+
}
|
|
110
|
+
} catch (err) {
|
|
111
|
+
console.log(`[captcha] DBC solve failed: ${err.message}`);
|
|
112
|
+
return false;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
// ── Auto-login ───────────────────────────────────────────────────────────────
|
|
117
|
+
async function autoLogin(page, payload) {
|
|
118
|
+
const { username, password, totpSecret, cookies, dbcUsername, dbcPassword } = payload;
|
|
119
|
+
|
|
120
|
+
// Configure DBC if credentials provided
|
|
121
|
+
if (dbcUsername && dbcPassword) {
|
|
122
|
+
dbc.configure(dbcUsername, dbcPassword);
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
// Navigate to login — try clicking Sign in on the current page first
|
|
126
|
+
// (navigating directly to x.com/i/flow/login can crash Firefox with some proxies)
|
|
127
|
+
try {
|
|
128
|
+
// Make sure we're on x.com
|
|
129
|
+
const currentUrl = page.url();
|
|
130
|
+
if (!currentUrl.includes('x.com')) {
|
|
131
|
+
await page.goto('https://x.com', { waitUntil: 'domcontentloaded', timeout: 60000 });
|
|
132
|
+
}
|
|
133
|
+
await randDelay(2000, 4000);
|
|
134
|
+
|
|
135
|
+
// Check if we're already on the login page
|
|
136
|
+
const url = page.url();
|
|
137
|
+
if (url.includes('/login') || url.includes('/i/flow')) {
|
|
138
|
+
// Already on login page — wait for it to load
|
|
139
|
+
await randDelay(2000, 4000);
|
|
140
|
+
} else {
|
|
141
|
+
// Click the Sign in button using JavaScript (more reliable than locator)
|
|
142
|
+
await page.evaluate(() => {
|
|
143
|
+
const signInEl = document.querySelector('a[href="/login"], a[href="/i/flow/login"], [data-testid="loginButton"]');
|
|
144
|
+
if (signInEl) signInEl.click();
|
|
145
|
+
});
|
|
146
|
+
await randDelay(3000, 6000);
|
|
147
|
+
}
|
|
148
|
+
} catch (e) {
|
|
149
|
+
// Fallback: try direct navigation
|
|
150
|
+
try {
|
|
151
|
+
await page.goto('https://x.com/i/flow/login', { waitUntil: 'commit', timeout: 60000 });
|
|
152
|
+
await randDelay(3000, 6000);
|
|
153
|
+
} catch (e2) {
|
|
154
|
+
throw new Error(`Failed to navigate to login page: ${e2.message}`);
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
// Check if the page is still alive
|
|
159
|
+
try {
|
|
160
|
+
await page.evaluate(() => document.title);
|
|
161
|
+
} catch {
|
|
162
|
+
throw new Error('Browser closed after navigating to login page');
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
// Step 1: Enter username
|
|
166
|
+
const usernameInput = page.locator(SELECTORS.usernameInput).first();
|
|
167
|
+
await usernameInput.waitFor({ state: 'visible', timeout: 30000 });
|
|
168
|
+
await safeFill(page, usernameInput, username);
|
|
169
|
+
await humanDelay(300, 600);
|
|
170
|
+
|
|
171
|
+
// Click Next
|
|
172
|
+
const nextBtn = page.locator('button:has-text("Next"), [role="button"]:has-text("Next")').first();
|
|
173
|
+
if (await nextBtn.isVisible({ timeout: 3000 }).catch(() => false)) {
|
|
174
|
+
await humanClick(page, nextBtn);
|
|
175
|
+
} else {
|
|
176
|
+
await page.keyboard.press('Enter');
|
|
177
|
+
}
|
|
178
|
+
await randDelay(2000, 4000);
|
|
179
|
+
|
|
180
|
+
// Step 2: Enter password
|
|
181
|
+
const passwordInput = page.locator(SELECTORS.passwordInput).first();
|
|
182
|
+
await passwordInput.waitFor({ state: 'visible', timeout: 15000 });
|
|
183
|
+
await safeFill(page, passwordInput, password);
|
|
184
|
+
await humanDelay(300, 600);
|
|
185
|
+
|
|
186
|
+
// Click Log in
|
|
187
|
+
const loginBtn = page.locator('[data-testid="LoginForm_Login_Button"], button:has-text("Log in")').first();
|
|
188
|
+
if (await loginBtn.isVisible({ timeout: 3000 }).catch(() => false)) {
|
|
189
|
+
await humanClick(page, loginBtn);
|
|
190
|
+
} else {
|
|
191
|
+
await page.keyboard.press('Enter');
|
|
192
|
+
}
|
|
193
|
+
await randDelay(3000, 5000);
|
|
194
|
+
|
|
195
|
+
// Step 3: Check for captcha/challenge
|
|
196
|
+
const captchaInfo = await detectCaptcha(page);
|
|
197
|
+
if (captchaInfo) {
|
|
198
|
+
console.log(`[login] Captcha detected: ${captchaInfo.type}`);
|
|
199
|
+
const solved = await solveCaptchaWithDBC(page, captchaInfo);
|
|
200
|
+
if (!solved) {
|
|
201
|
+
return { success: false, state: 'captcha', message: 'Captcha detected but could not be solved automatically. Manual intervention required.' };
|
|
202
|
+
}
|
|
203
|
+
await randDelay(2000, 4000);
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
// Step 4: Check for 2FA
|
|
207
|
+
const stage = await detectStage(page);
|
|
208
|
+
if (stage === 'unknown') {
|
|
209
|
+
// Might need 2FA
|
|
210
|
+
const twoFactorInput = page.locator('input[name="text"], input[type="text"]').first();
|
|
211
|
+
if (await twoFactorInput.isVisible({ timeout: 5000 }).catch(() => false)) {
|
|
212
|
+
if (totpSecret) {
|
|
213
|
+
const code = generateTOTP(totpSecret);
|
|
214
|
+
await safeFill(page, twoFactorInput, code);
|
|
215
|
+
await page.keyboard.press('Enter');
|
|
216
|
+
await randDelay(3000, 5000);
|
|
217
|
+
} else {
|
|
218
|
+
throw new Error('2FA required but no TOTP secret provided');
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
// Step 5: Check for captcha again (after 2FA)
|
|
224
|
+
const captchaInfo2 = await detectCaptcha(page);
|
|
225
|
+
if (captchaInfo2) {
|
|
226
|
+
console.log(`[login] Post-2FA captcha detected: ${captchaInfo2.type}`);
|
|
227
|
+
const solved = await solveCaptchaWithDBC(page, captchaInfo2);
|
|
228
|
+
if (!solved) {
|
|
229
|
+
return { success: false, state: 'captcha', message: 'Captcha after 2FA could not be solved automatically.' };
|
|
230
|
+
}
|
|
231
|
+
await randDelay(2000, 4000);
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
// Wait for login to complete
|
|
235
|
+
const loggedIn = await waitForLoggedIn(page, { timeoutMs: 25000 });
|
|
236
|
+
if (loggedIn) {
|
|
237
|
+
return { success: true, state: 'home_logged_in', message: 'Login successful' };
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
const finalStage = await detectStage(page);
|
|
241
|
+
if (finalStage === 'login_username_step' || finalStage === 'login_password_step') {
|
|
242
|
+
return { success: false, state: finalStage, message: 'Login failed — check credentials' };
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
return { success: false, state: finalStage || 'unknown', message: 'Login may require manual intervention' };
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
// ── Check login state ────────────────────────────────────────────────────────
|
|
249
|
+
async function checkLoginState(page, payload) {
|
|
250
|
+
const stage = await detectStage(page);
|
|
251
|
+
const loggedIn = stage === 'home_logged_in';
|
|
252
|
+
return {
|
|
253
|
+
success: true,
|
|
254
|
+
loggedIn,
|
|
255
|
+
state: loggedIn ? 'logged_in' : stage === 'unknown' ? 'unknown' : 'login_required',
|
|
256
|
+
url: page.url(),
|
|
257
|
+
};
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
// ── Check account status (active/suspended/inactive) ─────────────────────────
|
|
261
|
+
async function checkStatus(page, payload) {
|
|
262
|
+
const { username } = payload;
|
|
263
|
+
const cleanUsername = String(username).replace(/^@/, '');
|
|
264
|
+
|
|
265
|
+
// Navigate to home
|
|
266
|
+
await page.goto('https://x.com/home', { waitUntil: 'domcontentloaded', timeout: 30000 }).catch(() => {});
|
|
267
|
+
await sleep(3000);
|
|
268
|
+
|
|
269
|
+
const homeUrl = page.url();
|
|
270
|
+
if (homeUrl.includes('/login') || homeUrl.includes('/i/flow')) {
|
|
271
|
+
return { success: true, status: 'inactive', reason: 'login_required', message: 'Account requires login' };
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
// Check for suspension banner on home
|
|
275
|
+
const homeBody = await getBodyText(page);
|
|
276
|
+
if (homeBody.includes('account suspended') || homeBody.includes('your account is suspended')) {
|
|
277
|
+
return { success: true, status: 'suspended', reason: 'home_suspension_banner', message: 'Account is suspended' };
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
// Navigate to profile
|
|
281
|
+
await page.goto(`https://x.com/${cleanUsername}`, { waitUntil: 'domcontentloaded', timeout: 30000 }).catch(() => {});
|
|
282
|
+
await sleep(3000);
|
|
283
|
+
|
|
284
|
+
const profileUrl = page.url();
|
|
285
|
+
if (profileUrl.includes('/login') || profileUrl.includes('/i/flow')) {
|
|
286
|
+
return { success: true, status: 'inactive', reason: 'login_required', message: 'Account requires login' };
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
const profileBody = await getBodyText(page);
|
|
290
|
+
if (profileBody.includes('account suspended') || profileBody.includes('your account is suspended')) {
|
|
291
|
+
return { success: true, status: 'suspended', reason: 'profile_suspension_detected', message: 'Account is suspended' };
|
|
292
|
+
}
|
|
293
|
+
if (profileBody.includes("this account doesn't exist") || profileBody.includes("account doesn't exist")) {
|
|
294
|
+
return { success: true, status: 'suspended', reason: 'account_not_found', message: 'Account does not exist' };
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
// Check if profile loaded
|
|
298
|
+
const profileLoaded = await page.$('[data-testid="primaryColumn"], [data-testid="UserName"]');
|
|
299
|
+
if (profileLoaded) {
|
|
300
|
+
return { success: true, status: 'active', reason: 'profile_accessible', message: 'Account is active' };
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
return { success: true, status: 'unknown', reason: 'unable_to_determine', message: 'Unable to determine status' };
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
// ── Get profile info ────────────────────────────────────────────────────────
|
|
307
|
+
async function getProfileInfo(page, payload) {
|
|
308
|
+
const { username } = payload;
|
|
309
|
+
const cleanUsername = String(username).replace(/^@/, '');
|
|
310
|
+
|
|
311
|
+
// Navigate to the profile page — use a fresh page to avoid closing the main one
|
|
312
|
+
// Try up to 3 times in case the page crashes through the proxy
|
|
313
|
+
let data = null;
|
|
314
|
+
for (let attempt = 0; attempt < 3 && !data; attempt++) {
|
|
315
|
+
try {
|
|
316
|
+
await page.goto(`https://x.com/${cleanUsername}`, { waitUntil: 'domcontentloaded', timeout: 45000 });
|
|
317
|
+
await page.waitForLoadState('networkidle', { timeout: 10000 }).catch(() => {});
|
|
318
|
+
await page.waitForSelector('[data-testid="UserName"], [data-testid="UserProfileHeader_Items"]', { timeout: 15000 }).catch(() => {});
|
|
319
|
+
await sleep(2500);
|
|
320
|
+
|
|
321
|
+
// Check if page is still alive before evaluate
|
|
322
|
+
try {
|
|
323
|
+
await page.evaluate(() => document.title);
|
|
324
|
+
} catch (e) {
|
|
325
|
+
log(`[getProfileInfo] Page closed on attempt ${attempt + 1}: ${e.message}`);
|
|
326
|
+
// Navigate back to home to recover the page
|
|
327
|
+
await page.goto('https://x.com/home', { waitUntil: 'domcontentloaded', timeout: 30000 }).catch(() => {});
|
|
328
|
+
continue;
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
data = await page.evaluate(() => {
|
|
332
|
+
let name = '', username = '', bio = '', avatarUrl = '', headerUrl = '';
|
|
333
|
+
const nameEl = document.querySelector('[data-testid="UserName"]');
|
|
334
|
+
if (nameEl) {
|
|
335
|
+
const spans = nameEl.querySelectorAll('span');
|
|
336
|
+
for (const sp of spans) {
|
|
337
|
+
const t = (sp.innerText || sp.textContent || '').trim();
|
|
338
|
+
if (!t || t === '·') continue;
|
|
339
|
+
if (!name && !t.startsWith('@')) name = t;
|
|
340
|
+
if (!username && t.startsWith('@')) username = t.replace(/^@/, '');
|
|
341
|
+
if (name && username) break;
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
const bioEl = document.querySelector('[data-testid="UserDescription"]');
|
|
345
|
+
bio = bioEl ? (bioEl.innerText || bioEl.textContent || '').trim() : '';
|
|
346
|
+
for (const img of document.querySelectorAll('img')) {
|
|
347
|
+
const src = img.src || '';
|
|
348
|
+
if (!avatarUrl && /pbs\.twimg\.com\/profile_images\//i.test(src)) {
|
|
349
|
+
avatarUrl = src.replace(/_(normal|mini|bigger|200x200|400x400|orig)(\.[a-z]+)$/i, '_400x400$2');
|
|
350
|
+
}
|
|
351
|
+
if (!headerUrl && /pbs\.twimg\.com\/profile_banners\//i.test(src)) headerUrl = src;
|
|
352
|
+
if (avatarUrl && headerUrl) break;
|
|
353
|
+
}
|
|
354
|
+
return { name, username, bio, avatarUrl, headerUrl };
|
|
355
|
+
});
|
|
356
|
+
} catch (e) {
|
|
357
|
+
log(`[getProfileInfo] Attempt ${attempt + 1} failed: ${e.message}`);
|
|
358
|
+
// Try to recover by going home
|
|
359
|
+
await page.goto('https://x.com/home', { waitUntil: 'domcontentloaded', timeout: 30000 }).catch(() => {});
|
|
360
|
+
await sleep(2000);
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
if (!data) {
|
|
365
|
+
// All attempts failed — return empty data (the frontend will use existing DB values)
|
|
366
|
+
log(`[getProfileInfo] All attempts failed for @${cleanUsername}, returning empty`);
|
|
367
|
+
return { name: '', username: cleanUsername, bio: '', avatarUrl: '', headerUrl: '' };
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
if (!data.username) data.username = cleanUsername;
|
|
371
|
+
return data;
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
// ── Helper: image URL or base64 → temp file ─────────────────────────────────
|
|
375
|
+
async function imageToTempFile(imageUrl, imageBase64) {
|
|
376
|
+
const fs = require('fs');
|
|
377
|
+
const path = require('path');
|
|
378
|
+
const os = require('os');
|
|
379
|
+
const https = require('https');
|
|
380
|
+
const http = require('http');
|
|
381
|
+
|
|
382
|
+
const extFromMime = (mime) => {
|
|
383
|
+
const m = String(mime || '').toLowerCase();
|
|
384
|
+
if (m.includes('png')) return 'png';
|
|
385
|
+
if (m.includes('webp')) return 'webp';
|
|
386
|
+
if (m.includes('jpeg') || m.includes('jpg')) return 'jpg';
|
|
387
|
+
return null;
|
|
388
|
+
};
|
|
389
|
+
|
|
390
|
+
if (imageBase64) {
|
|
391
|
+
const mimeMatch = imageBase64.match(/^data:(image\/[\w.+-]+);base64,/i);
|
|
392
|
+
const ext = extFromMime(mimeMatch?.[1]);
|
|
393
|
+
if (!ext) throw new Error(`Unsupported profile image type: ${mimeMatch?.[1] || 'unknown'}`);
|
|
394
|
+
const tempFile = path.join(os.tmpdir(), `tw-img-${Date.now()}.${ext}`);
|
|
395
|
+
const base64Data = imageBase64.replace(/^data:image\/[\w.+-]+;base64,/i, '');
|
|
396
|
+
fs.writeFileSync(tempFile, Buffer.from(base64Data, 'base64'));
|
|
397
|
+
return tempFile;
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
if (!imageUrl) throw new Error('No image provided');
|
|
401
|
+
|
|
402
|
+
let tempFile = null;
|
|
403
|
+
await new Promise((resolve, reject) => {
|
|
404
|
+
const protocol = imageUrl.startsWith('https') ? https : http;
|
|
405
|
+
protocol.get(imageUrl, (response) => {
|
|
406
|
+
if (response.statusCode !== 200) {
|
|
407
|
+
reject(new Error(`HTTP ${response.statusCode}`));
|
|
408
|
+
return;
|
|
409
|
+
}
|
|
410
|
+
let ext = extFromMime(response.headers['content-type']);
|
|
411
|
+
try {
|
|
412
|
+
const urlExt = path.extname(new URL(imageUrl).pathname).replace('.', '').toLowerCase();
|
|
413
|
+
if (/^(png|jpe?g|webp)$/.test(urlExt)) ext = urlExt === 'jpeg' ? 'jpg' : urlExt;
|
|
414
|
+
} catch {}
|
|
415
|
+
if (!ext) {
|
|
416
|
+
reject(new Error(`Unsupported profile image content type: ${response.headers['content-type'] || 'unknown'}`));
|
|
417
|
+
return;
|
|
418
|
+
}
|
|
419
|
+
tempFile = path.join(os.tmpdir(), `tw-img-${Date.now()}.${ext}`);
|
|
420
|
+
const file = fs.createWriteStream(tempFile);
|
|
421
|
+
response.pipe(file);
|
|
422
|
+
file.on('finish', () => { file.close(); resolve(); });
|
|
423
|
+
}).on('error', (err) => {
|
|
424
|
+
if (tempFile) try { fs.unlinkSync(tempFile); } catch {}
|
|
425
|
+
reject(err);
|
|
426
|
+
});
|
|
427
|
+
});
|
|
428
|
+
return tempFile;
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
// ── Helper: click banner/avatar trigger, upload file, apply crop ─────────────
|
|
432
|
+
async function uploadProfileImage(page, tempFile, kind) {
|
|
433
|
+
const label = kind === 'header' ? 'header banner' : 'profile avatar';
|
|
434
|
+
log(`[updateProfile] Uploading ${label}...`);
|
|
435
|
+
|
|
436
|
+
// Scroll to top so both upload buttons are in viewport
|
|
437
|
+
await page.evaluate(() => window.scrollTo(0, 0)).catch(() => {});
|
|
438
|
+
await sleep(400);
|
|
439
|
+
|
|
440
|
+
// ── PRIMARY: click the camera/add-photo button on the avatar or header area ──
|
|
441
|
+
// On X's profile editor, the avatar and header each have a camera button that
|
|
442
|
+
// opens a file chooser. We click the correct one based on kind, then set the
|
|
443
|
+
// file via the filechooser event — this is the most reliable method.
|
|
444
|
+
try {
|
|
445
|
+
const trigger = await findUploadTrigger(page, kind);
|
|
446
|
+
if (trigger) {
|
|
447
|
+
log(`[updateProfile] ${label}: found trigger at y=${Math.round(trigger.y)}, hint="${trigger.hint}"`);
|
|
448
|
+
const jx = trigger.x + (Math.random() * 4 - 2);
|
|
449
|
+
const jy = trigger.y + (Math.random() * 4 - 2);
|
|
450
|
+
await page.mouse.move(jx, jy, { steps: 8 });
|
|
451
|
+
await randDelay(80, 160);
|
|
452
|
+
const chooserPromise = page.waitForEvent('filechooser', { timeout: 5000 }).catch(() => null);
|
|
453
|
+
await page.mouse.click(jx, jy);
|
|
454
|
+
const chooser = await chooserPromise;
|
|
455
|
+
if (chooser) {
|
|
456
|
+
await chooser.setFiles(tempFile);
|
|
457
|
+
log(`[updateProfile] ${label}: file set via filechooser`);
|
|
458
|
+
// Wait longer for X to process the image and open the cropper (was 1.5s, now 3s)
|
|
459
|
+
await sleep(3000);
|
|
460
|
+
const applied = await confirmMediaEdit(page, kind);
|
|
461
|
+
if (applied) {
|
|
462
|
+
log(`[updateProfile] ${label}: uploaded and confirmed`);
|
|
463
|
+
// Wait for the cropper to fully close and image to be staged
|
|
464
|
+
await sleep(2000);
|
|
465
|
+
return true;
|
|
466
|
+
}
|
|
467
|
+
// Apply not found — maybe no cropper shown
|
|
468
|
+
log(`[updateProfile] ${label}: Apply not shown — assuming upload succeeded`);
|
|
469
|
+
await sleep(1000);
|
|
470
|
+
return true;
|
|
471
|
+
}
|
|
472
|
+
log(`[updateProfile] ${label}: click produced no filechooser — trying input method`);
|
|
473
|
+
} else {
|
|
474
|
+
log(`[updateProfile] ${label}: no trigger button found — trying input method`);
|
|
475
|
+
}
|
|
476
|
+
} catch (e) {
|
|
477
|
+
log(`[updateProfile] ${label}: trigger click failed: ${e.message} — trying input method`);
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
// ── FALLBACK: set file directly on the correct hidden input ──────────────
|
|
481
|
+
try {
|
|
482
|
+
const inputs = page.locator('input[type="file"], [data-testid="fileInput"]');
|
|
483
|
+
const count = await inputs.count().catch(() => 0);
|
|
484
|
+
if (count > 0) {
|
|
485
|
+
// Try to resolve the correct input index
|
|
486
|
+
const inputIndex = await resolveFileInputIndex(page, kind);
|
|
487
|
+
if (inputIndex >= 0 && count > inputIndex) {
|
|
488
|
+
await inputs.nth(inputIndex).setInputFiles(tempFile);
|
|
489
|
+
log(`[updateProfile] ${label}: file set on resolved input[${inputIndex}]`);
|
|
490
|
+
await sleep(3000);
|
|
491
|
+
const applied = await clickApplyButtonSimple(page, kind);
|
|
492
|
+
if (applied) {
|
|
493
|
+
log(`[updateProfile] ${label}: Apply clicked — uploaded`);
|
|
494
|
+
await sleep(2000);
|
|
495
|
+
return true;
|
|
496
|
+
}
|
|
497
|
+
log(`[updateProfile] ${label}: Apply not shown — assuming upload succeeded`);
|
|
498
|
+
await sleep(1000);
|
|
499
|
+
return true;
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
// If we can't resolve which input, try each one (for single-input pages)
|
|
503
|
+
if (count === 1) {
|
|
504
|
+
await inputs.nth(0).setInputFiles(tempFile);
|
|
505
|
+
log(`[updateProfile] ${label}: file set on only input[0]`);
|
|
506
|
+
await sleep(3000);
|
|
507
|
+
const applied = await clickApplyButtonSimple(page, kind);
|
|
508
|
+
if (applied) {
|
|
509
|
+
log(`[updateProfile] ${label}: Apply clicked — uploaded`);
|
|
510
|
+
await sleep(2000);
|
|
511
|
+
return true;
|
|
512
|
+
}
|
|
513
|
+
log(`[updateProfile] ${label}: Apply not shown — assuming upload succeeded`);
|
|
514
|
+
await sleep(1000);
|
|
515
|
+
return true;
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
log(`[updateProfile] ${label}: could not resolve a safe file input from ${count} input(s)`);
|
|
519
|
+
|
|
520
|
+
// Last resort: for avatar, try the LAST input (lowest on page = avatar)
|
|
521
|
+
// For header, try the FIRST input (topmost = header)
|
|
522
|
+
if (count >= 2) {
|
|
523
|
+
const fallbackIndex = kind === 'header' ? 0 : count - 1;
|
|
524
|
+
log(`[updateProfile] ${label}: trying fallback input[${fallbackIndex}]`);
|
|
525
|
+
await inputs.nth(fallbackIndex).setInputFiles(tempFile);
|
|
526
|
+
log(`[updateProfile] ${label}: file set on fallback input[${fallbackIndex}]`);
|
|
527
|
+
await sleep(3000);
|
|
528
|
+
const applied = await clickApplyButtonSimple(page, kind);
|
|
529
|
+
if (applied) {
|
|
530
|
+
log(`[updateProfile] ${label}: Apply clicked — uploaded (fallback)`);
|
|
531
|
+
await sleep(2000);
|
|
532
|
+
return true;
|
|
533
|
+
}
|
|
534
|
+
log(`[updateProfile] ${label}: Apply not shown — assuming upload succeeded (fallback)`);
|
|
535
|
+
await sleep(1000);
|
|
536
|
+
return true;
|
|
537
|
+
}
|
|
538
|
+
}
|
|
539
|
+
} catch (e) {
|
|
540
|
+
log(`[updateProfile] ${label}: input upload failed: ${e.message}`);
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
log(`[updateProfile] All upload paths exhausted for ${label}`);
|
|
544
|
+
return false;
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
// ── Helper: find the upload trigger button for avatar or header ──────────────
|
|
548
|
+
// On X's profile editor, the avatar has a camera button and the header has an
|
|
549
|
+
// "Add photo" button. We find them by aria-label, data-testid, or position.
|
|
550
|
+
async function findUploadTrigger(page, kind) {
|
|
551
|
+
const trigger = await page.evaluate((imageKind) => {
|
|
552
|
+
// Header-specific: must contain header/banner/cover keywords
|
|
553
|
+
const HEADER_RE = /header|banner|cover|غلاف|خلفية|add banner|add header/i;
|
|
554
|
+
// Avatar-specific: must contain avatar/profile photo keywords (NOT just "add photo")
|
|
555
|
+
const AVATAR_RE = /avatar|profile.?photo|profile.?picture|صورة.?شخصية|صورة.?ملف|add.*photo|camera|كاميرا/i;
|
|
556
|
+
// Generic media-related (for fallback)
|
|
557
|
+
const MEDIA_RE = /photo|image|avatar|header|banner|cover|edit|media|upload|add|غلاف|صورة|تحرير|رفع|كاميرا|camera|svg|icon/i;
|
|
558
|
+
const BACK_RE = /^back$|^رجوع$|^السابق$/i;
|
|
559
|
+
// Only skip clearly unrelated elements (don't skip profileheader — it's the container)
|
|
560
|
+
const SKIP_RE = /tweet-user-avatar|profilebackground|verified|follow|share|save|back|رجوع/i;
|
|
561
|
+
|
|
562
|
+
const seen = new Set();
|
|
563
|
+
const candidates = [];
|
|
564
|
+
|
|
565
|
+
// Look for buttons, role=button, and also divs with click handlers near avatar/header
|
|
566
|
+
// Also look for SVG-containing buttons (camera icons have no text)
|
|
567
|
+
const SELS = [
|
|
568
|
+
'button[aria-label]', '[role="button"][aria-label]',
|
|
569
|
+
'button', '[role="button"]',
|
|
570
|
+
'[data-testid*="banner" i]', '[data-testid*="avatar" i]',
|
|
571
|
+
'[data-testid*="header" i]', '[data-testid*="photo" i]',
|
|
572
|
+
'[data-testid*="edit" i]', '[data-testid*="camera" i]',
|
|
573
|
+
'[data-testid*="upload" i]', '[data-testid*="image" i]',
|
|
574
|
+
// Camera icon buttons — often have no text, just SVG
|
|
575
|
+
'button:has(svg)', '[role="button"]:has(svg)',
|
|
576
|
+
];
|
|
577
|
+
for (const sel of SELS) {
|
|
578
|
+
document.querySelectorAll(sel).forEach((el) => {
|
|
579
|
+
if (seen.has(el)) return; seen.add(el);
|
|
580
|
+
const rect = el.getBoundingClientRect();
|
|
581
|
+
if (rect.width < 8 || rect.height < 8) return;
|
|
582
|
+
if (rect.bottom < 0 || rect.top > window.innerHeight) return;
|
|
583
|
+
const cs = window.getComputedStyle(el);
|
|
584
|
+
if (cs.visibility === 'hidden' || cs.display === 'none' || cs.opacity === '0') return;
|
|
585
|
+
const hint = `${el.getAttribute('aria-label') || ''} ${el.getAttribute('data-testid') || ''} ${el.innerText || ''} ${el.title || ''}`.trim();
|
|
586
|
+
if (BACK_RE.test(hint.trim())) return;
|
|
587
|
+
if (SKIP_RE.test(hint)) return;
|
|
588
|
+
// For SVG-only buttons (camera icons), check if they're positioned over the avatar/header area
|
|
589
|
+
const hasSvg = el.querySelector('svg') !== null;
|
|
590
|
+
if (!MEDIA_RE.test(hint) && !hasSvg) return;
|
|
591
|
+
// If it has an SVG but no text, it might be a camera button — include it
|
|
592
|
+
if (hasSvg && !hint) {
|
|
593
|
+
candidates.push({
|
|
594
|
+
x: rect.left + rect.width / 2,
|
|
595
|
+
y: rect.top + rect.height / 2,
|
|
596
|
+
isHeader: false, // will be determined by position
|
|
597
|
+
isAvatar: false, // will be determined by position
|
|
598
|
+
hint: 'svg-icon-button',
|
|
599
|
+
hasSvg: true,
|
|
600
|
+
rect: { top: rect.top, left: rect.left, width: rect.width, height: rect.height },
|
|
601
|
+
});
|
|
602
|
+
return;
|
|
603
|
+
}
|
|
604
|
+
candidates.push({
|
|
605
|
+
x: rect.left + rect.width / 2,
|
|
606
|
+
y: rect.top + rect.height / 2,
|
|
607
|
+
isHeader: HEADER_RE.test(hint),
|
|
608
|
+
isAvatar: AVATAR_RE.test(hint),
|
|
609
|
+
hint,
|
|
610
|
+
hasSvg,
|
|
611
|
+
rect: { top: rect.top, left: rect.left, width: rect.width, height: rect.height },
|
|
612
|
+
});
|
|
613
|
+
});
|
|
614
|
+
}
|
|
615
|
+
|
|
616
|
+
if (!candidates.length) return null;
|
|
617
|
+
|
|
618
|
+
// Prefer explicit semantic match
|
|
619
|
+
const headerCands = candidates.filter(c => c.isHeader);
|
|
620
|
+
const avatarCands = candidates.filter(c => c.isAvatar);
|
|
621
|
+
if (imageKind === 'header' && headerCands.length) {
|
|
622
|
+
headerCands.sort((a, b) => a.y - b.y);
|
|
623
|
+
return headerCands[0];
|
|
624
|
+
}
|
|
625
|
+
if (imageKind === 'avatar' && avatarCands.length) {
|
|
626
|
+
avatarCands.sort((a, b) => b.y - a.y);
|
|
627
|
+
return avatarCands[0];
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
// Position fallback: header button is ALWAYS above the avatar button
|
|
631
|
+
// On X profile editor: header is at top (~y=100-200), avatar is below (~y=200-350)
|
|
632
|
+
candidates.sort((a, b) => a.y - b.y);
|
|
633
|
+
if (imageKind === 'header') return candidates[0];
|
|
634
|
+
|
|
635
|
+
// For avatar: pick the lowest candidate that's not the header
|
|
636
|
+
// Or if there are SVG-only buttons, pick the one closest to the avatar position
|
|
637
|
+
const svgButtons = candidates.filter(c => c.hasSvg && !c.isHeader);
|
|
638
|
+
if (svgButtons.length > 0 && imageKind === 'avatar') {
|
|
639
|
+
// Avatar camera button is typically the lowest SVG button
|
|
640
|
+
svgButtons.sort((a, b) => b.y - a.y);
|
|
641
|
+
return svgButtons[0];
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
return candidates[candidates.length - 1];
|
|
645
|
+
}, kind).catch(() => null);
|
|
646
|
+
|
|
647
|
+
return trigger;
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
// ── Helper: pick the correct hidden file input index (banner vs avatar) ─────
|
|
651
|
+
// First tries semantic hints in ancestor elements (English + Arabic).
|
|
652
|
+
// Falls back to Y-position of the closest visible ancestor container:
|
|
653
|
+
// top-most container = banner/header, lower container = avatar.
|
|
654
|
+
async function resolveFileInputIndex(page, kind) {
|
|
655
|
+
const index = await page.evaluate((imageKind) => {
|
|
656
|
+
const inputs = Array.from(document.querySelectorAll('input[type="file"]'));
|
|
657
|
+
if (inputs.length === 0) return -1;
|
|
658
|
+
if (inputs.length === 1) return 0; // Only one input — use it
|
|
659
|
+
|
|
660
|
+
const HEADER_RE = /banner|header|cover|غلاف|خلفية/i;
|
|
661
|
+
const AVATAR_RE = /avatar|profile.?photo|profile.?picture|صورة.?شخصية|صورة.?ملف/i;
|
|
662
|
+
const wanted = imageKind === 'header' ? HEADER_RE : AVATAR_RE;
|
|
663
|
+
|
|
664
|
+
// Semantic pass: walk up to 25 ancestors looking for matching hint
|
|
665
|
+
for (let i = 0; i < inputs.length; i++) {
|
|
666
|
+
let el = inputs[i];
|
|
667
|
+
for (let depth = 0; depth < 25 && el; depth++) {
|
|
668
|
+
const hint = `${el.getAttribute('aria-label') || ''} ${el.getAttribute('data-testid') || ''} ${el.innerText || ''}`;
|
|
669
|
+
if (wanted.test(hint)) return i;
|
|
670
|
+
el = el.parentElement;
|
|
671
|
+
}
|
|
672
|
+
}
|
|
673
|
+
|
|
674
|
+
// Position fallback: find each input's nearest visible ancestor container.
|
|
675
|
+
// On X settings/profile the banner container is above the avatar container.
|
|
676
|
+
const getRect = (el) => {
|
|
677
|
+
let cur = el.parentElement;
|
|
678
|
+
while (cur && cur !== document.body) {
|
|
679
|
+
const r = cur.getBoundingClientRect();
|
|
680
|
+
if (r.width > 10 && r.height > 10) return r;
|
|
681
|
+
cur = cur.parentElement;
|
|
682
|
+
}
|
|
683
|
+
return null;
|
|
684
|
+
};
|
|
685
|
+
|
|
686
|
+
const ranked = inputs
|
|
687
|
+
.map((inp, i) => ({ i, y: (getRect(inp) || { top: 99999 }).top }))
|
|
688
|
+
.sort((a, b) => a.y - b.y);
|
|
689
|
+
|
|
690
|
+
// topmost container = banner/header input, lowest = avatar input
|
|
691
|
+
// For avatar: return the LAST (lowest) input
|
|
692
|
+
// For header: return the FIRST (topmost) input
|
|
693
|
+
if (imageKind === 'header') return ranked[0].i;
|
|
694
|
+
return ranked[ranked.length - 1].i;
|
|
695
|
+
}, kind).catch(() => -1);
|
|
696
|
+
|
|
697
|
+
log(`[updateProfile] resolveFileInputIndex => ${index} for ${kind}`);
|
|
698
|
+
return index;
|
|
699
|
+
}
|
|
700
|
+
|
|
701
|
+
// ── Helper: click Apply on the Edit-media cropper (simple, multi-selector) ──
|
|
702
|
+
// Used by the recorded input-index upload method. Tries the Apply button with
|
|
703
|
+
// multiple selectors (data-testid, role+text, button-text — matches the
|
|
704
|
+
// recorded real-user flow) plus Arabic "تطبيق" variants.
|
|
705
|
+
async function clickApplyButtonSimple(page, kind) {
|
|
706
|
+
const applySelectors = [
|
|
707
|
+
'[data-testid="applyButton"]',
|
|
708
|
+
'div[role="button"]:has-text("Apply")',
|
|
709
|
+
'button:has-text("Apply")',
|
|
710
|
+
'[role="button"]:has-text("تطبيق")',
|
|
711
|
+
'button:has-text("تطبيق")',
|
|
712
|
+
];
|
|
713
|
+
|
|
714
|
+
// Wait briefly for the cropper/Apply button to appear
|
|
715
|
+
for (let i = 0; i < 10; i++) {
|
|
716
|
+
for (const selector of applySelectors) {
|
|
717
|
+
const btn = page.locator(selector).last();
|
|
718
|
+
if (await btn.isVisible({ timeout: 400 }).catch(() => false)) {
|
|
719
|
+
const enabled = await btn.isEnabled({ timeout: 1000 }).catch(() => true);
|
|
720
|
+
if (!enabled) { await sleep(400); continue; }
|
|
721
|
+
try {
|
|
722
|
+
await btn.click({ timeout: 5000 });
|
|
723
|
+
log(`[updateProfile] ${kind}: Apply clicked (selector: ${selector})`);
|
|
724
|
+
await sleep(1500);
|
|
725
|
+
return true;
|
|
726
|
+
} catch (e) {
|
|
727
|
+
log(`[updateProfile] ${kind}: Apply click failed: ${e.message}`);
|
|
728
|
+
}
|
|
729
|
+
}
|
|
730
|
+
}
|
|
731
|
+
await sleep(400);
|
|
732
|
+
}
|
|
733
|
+
return false;
|
|
734
|
+
}
|
|
735
|
+
|
|
736
|
+
// ── Helper: wait for cropper preview image to finish loading ────────────────
|
|
737
|
+
async function waitForCropperReady(page, kind, timeoutMs = 30000) {
|
|
738
|
+
log(`[updateProfile] ${kind}: waiting for cropper to be ready...`);
|
|
739
|
+
const applyBtn = page.getByRole('button', { name: /^Apply$/i });
|
|
740
|
+
const deadline = Date.now() + timeoutMs;
|
|
741
|
+
|
|
742
|
+
while (Date.now() < deadline) {
|
|
743
|
+
if (!(await isEditMediaOpen(page))) return false;
|
|
744
|
+
|
|
745
|
+
// Best signal: Apply button visible AND enabled means X finished loading the image
|
|
746
|
+
const applyVisible = await applyBtn.isVisible({ timeout: 300 }).catch(() => false);
|
|
747
|
+
if (applyVisible) {
|
|
748
|
+
const applyEnabled = await applyBtn.isEnabled().catch(() => false);
|
|
749
|
+
if (applyEnabled) {
|
|
750
|
+
log(`[updateProfile] ${kind}: Apply button enabled — cropper ready`);
|
|
751
|
+
await sleep(1500);
|
|
752
|
+
return true;
|
|
753
|
+
}
|
|
754
|
+
}
|
|
755
|
+
|
|
756
|
+
// Fallback: visible blob/canvas preview inside cropper
|
|
757
|
+
const hasPreview = await page.evaluate(() => {
|
|
758
|
+
for (const el of document.querySelectorAll('img, canvas')) {
|
|
759
|
+
const rect = el.getBoundingClientRect();
|
|
760
|
+
if (rect.width < 80 || rect.height < 80) continue;
|
|
761
|
+
if (el.tagName === 'CANVAS') return true;
|
|
762
|
+
if (el.tagName === 'IMG') {
|
|
763
|
+
const src = el.src || '';
|
|
764
|
+
if ((src.startsWith('blob:') || src.startsWith('data:')) && el.complete && el.naturalWidth > 0) {
|
|
765
|
+
return true;
|
|
766
|
+
}
|
|
767
|
+
}
|
|
768
|
+
}
|
|
769
|
+
return false;
|
|
770
|
+
}).catch(() => false);
|
|
771
|
+
|
|
772
|
+
if (hasPreview) {
|
|
773
|
+
log(`[updateProfile] ${kind}: cropper preview visible — waiting for Apply to enable`);
|
|
774
|
+
}
|
|
775
|
+
await sleep(500);
|
|
776
|
+
}
|
|
777
|
+
|
|
778
|
+
log(`[updateProfile] ${kind}: cropper ready wait timed out`);
|
|
779
|
+
return false;
|
|
780
|
+
}
|
|
781
|
+
|
|
782
|
+
async function clickApplyButton(page, kind) {
|
|
783
|
+
const applyBtn = page.getByRole('button', { name: /^Apply$/i });
|
|
784
|
+
if (!(await applyBtn.isVisible({ timeout: 2000 }).catch(() => false))) return false;
|
|
785
|
+
|
|
786
|
+
// Wait up to 10s for Apply to become enabled
|
|
787
|
+
for (let i = 0; i < 20; i++) {
|
|
788
|
+
if (await applyBtn.isEnabled().catch(() => false)) break;
|
|
789
|
+
await sleep(500);
|
|
790
|
+
}
|
|
791
|
+
|
|
792
|
+
try {
|
|
793
|
+
const box = await applyBtn.boundingBox();
|
|
794
|
+
if (box) {
|
|
795
|
+
const cx = box.x + box.width / 2 + (Math.random() * 4 - 2);
|
|
796
|
+
const cy = box.y + box.height / 2 + (Math.random() * 4 - 2);
|
|
797
|
+
await page.mouse.move(cx, cy, { steps: 4 });
|
|
798
|
+
await randDelay(100, 200);
|
|
799
|
+
await page.mouse.click(cx, cy);
|
|
800
|
+
log(`[updateProfile] ${kind} Apply clicked via mouse`);
|
|
801
|
+
return true;
|
|
802
|
+
}
|
|
803
|
+
await applyBtn.click({ force: true, timeout: 5000 });
|
|
804
|
+
log(`[updateProfile] ${kind} Apply clicked via getByRole`);
|
|
805
|
+
return true;
|
|
806
|
+
} catch (e) {
|
|
807
|
+
log(`[updateProfile] ${kind} Apply click failed: ${e.message}`);
|
|
808
|
+
}
|
|
809
|
+
|
|
810
|
+
// JS fallback
|
|
811
|
+
return page.evaluate(() => {
|
|
812
|
+
const applyBtns = [];
|
|
813
|
+
document.querySelectorAll('[role="button"], button').forEach((el) => {
|
|
814
|
+
const ariaLabel = (el.getAttribute('aria-label') || '').trim().toLowerCase();
|
|
815
|
+
const text = (el.innerText || '').trim();
|
|
816
|
+
if (ariaLabel === 'back' || ariaLabel === 'رجوع') return;
|
|
817
|
+
if (text !== 'Apply' && text !== 'تطبيق') return;
|
|
818
|
+
const rect = el.getBoundingClientRect();
|
|
819
|
+
if (rect.width < 8 || rect.height < 8) return;
|
|
820
|
+
applyBtns.push({ el, right: rect.right });
|
|
821
|
+
});
|
|
822
|
+
if (!applyBtns.length) return false;
|
|
823
|
+
applyBtns.sort((a, b) => b.right - a.right);
|
|
824
|
+
applyBtns[0].el.click();
|
|
825
|
+
return true;
|
|
826
|
+
}).catch(() => false);
|
|
827
|
+
}
|
|
828
|
+
|
|
829
|
+
// ── Helper: confirm "Edit media" cropper (click Apply — NOT Back) ───────────
|
|
830
|
+
// X opens an "Edit media" sheet after file selection. Top-left = Back arrow,
|
|
831
|
+
// top-right = Apply (black filled button). We must wait for the image preview,
|
|
832
|
+
// click Apply, then wait for the sheet to close before touching Save.
|
|
833
|
+
async function isEditMediaOpen(page) {
|
|
834
|
+
return page.getByText('Edit media', { exact: true }).first()
|
|
835
|
+
.isVisible({ timeout: 800 }).catch(() => false);
|
|
836
|
+
}
|
|
837
|
+
|
|
838
|
+
async function confirmMediaEdit(page, kind) {
|
|
839
|
+
// Wait for the cropper sheet to appear (up to 8s)
|
|
840
|
+
let modalOpen = false;
|
|
841
|
+
for (let i = 0; i < 16; i++) {
|
|
842
|
+
if (await isEditMediaOpen(page)) { modalOpen = true; break; }
|
|
843
|
+
await sleep(500);
|
|
844
|
+
}
|
|
845
|
+
|
|
846
|
+
if (!modalOpen) {
|
|
847
|
+
log(`[updateProfile] ${kind}: no Edit media modal — nothing to confirm`);
|
|
848
|
+
return true;
|
|
849
|
+
}
|
|
850
|
+
|
|
851
|
+
log(`[updateProfile] ${kind}: Edit media modal detected`);
|
|
852
|
+
|
|
853
|
+
// Critical: wait for Apply to become enabled before clicking
|
|
854
|
+
await waitForCropperReady(page, kind);
|
|
855
|
+
|
|
856
|
+
for (let attempt = 1; attempt <= 5; attempt++) {
|
|
857
|
+
if (!(await isEditMediaOpen(page))) {
|
|
858
|
+
log(`[updateProfile] ${kind}: cropper already closed`);
|
|
859
|
+
await sleep(1500);
|
|
860
|
+
return true;
|
|
861
|
+
}
|
|
862
|
+
|
|
863
|
+
log(`[updateProfile] ${kind}: Apply attempt ${attempt}`);
|
|
864
|
+
await clickApplyButton(page, kind);
|
|
865
|
+
await sleep(1200);
|
|
866
|
+
|
|
867
|
+
if (!(await isEditMediaOpen(page))) {
|
|
868
|
+
log(`[updateProfile] ${kind}: cropper closed after Apply (attempt ${attempt})`);
|
|
869
|
+
await sleep(2000);
|
|
870
|
+
return true;
|
|
871
|
+
}
|
|
872
|
+
await sleep(800);
|
|
873
|
+
}
|
|
874
|
+
|
|
875
|
+
log(`[updateProfile] ${kind} Edit media still open after 5 Apply attempts`);
|
|
876
|
+
return false;
|
|
877
|
+
}
|
|
878
|
+
|
|
879
|
+
// ── Helper: wait until the profile Save button is enabled ─────────────────
|
|
880
|
+
async function waitForSaveButtonReady(page, label, timeoutMs = 15000) {
|
|
881
|
+
const saveBtn = page.locator('[data-testid="Profile_Save_Button"]').first();
|
|
882
|
+
const deadline = Date.now() + timeoutMs;
|
|
883
|
+
while (Date.now() < deadline) {
|
|
884
|
+
const visible = await saveBtn.isVisible({ timeout: 500 }).catch(() => false);
|
|
885
|
+
if (!visible) { await sleep(400); continue; }
|
|
886
|
+
const enabled = await saveBtn.isEnabled().catch(() => false);
|
|
887
|
+
if (enabled) {
|
|
888
|
+
log(`[updateProfile] Save button ready (${label})`);
|
|
889
|
+
return saveBtn;
|
|
890
|
+
}
|
|
891
|
+
await sleep(400);
|
|
892
|
+
}
|
|
893
|
+
log(`[updateProfile] Save button not ready within ${timeoutMs}ms (${label})`);
|
|
894
|
+
return null;
|
|
895
|
+
}
|
|
896
|
+
|
|
897
|
+
// ── Helper: click Save and wait for X to finish persisting ──────────────────
|
|
898
|
+
async function waitForSaveComplete(page, label, timeoutMs = 25000) {
|
|
899
|
+
const saveBtn = page.locator('[data-testid="Profile_Save_Button"]').first();
|
|
900
|
+
const deadline = Date.now() + timeoutMs;
|
|
901
|
+
while (Date.now() < deadline) {
|
|
902
|
+
const url = page.url();
|
|
903
|
+
if (url.includes('/home') || url === 'https://x.com/' || url === 'https://x.com') {
|
|
904
|
+
log(`[updateProfile] Save complete — redirected to home (${label})`);
|
|
905
|
+
await sleep(2500);
|
|
906
|
+
return true;
|
|
907
|
+
}
|
|
908
|
+
|
|
909
|
+
const bodyText = await getBodyText(page).catch(() => '');
|
|
910
|
+
if (/profile.*updated|changes saved|saved successfully/i.test(bodyText)) {
|
|
911
|
+
log(`[updateProfile] Save complete — success message (${label})`);
|
|
912
|
+
await sleep(2000);
|
|
913
|
+
return true;
|
|
914
|
+
}
|
|
915
|
+
|
|
916
|
+
// Still on settings: Save button disabled = no pending changes = saved
|
|
917
|
+
if (url.includes('/settings/profile')) {
|
|
918
|
+
const saveVisible = await saveBtn.isVisible({ timeout: 300 }).catch(() => false);
|
|
919
|
+
if (saveVisible) {
|
|
920
|
+
const enabled = await saveBtn.isEnabled().catch(() => true);
|
|
921
|
+
if (!enabled) {
|
|
922
|
+
log(`[updateProfile] Save complete — Save button disabled (${label})`);
|
|
923
|
+
await sleep(2000);
|
|
924
|
+
return true;
|
|
925
|
+
}
|
|
926
|
+
}
|
|
927
|
+
}
|
|
928
|
+
|
|
929
|
+
await sleep(500);
|
|
930
|
+
}
|
|
931
|
+
log(`[updateProfile] Save did not confirm within ${timeoutMs}ms (${label}), URL: ${page.url()}`);
|
|
932
|
+
return false;
|
|
933
|
+
}
|
|
934
|
+
|
|
935
|
+
// ── Update profile by clicks only ───────────────────────────────────────────
|
|
936
|
+
// No page.goto(). Browser must already be on X and logged in.
|
|
937
|
+
|
|
938
|
+
async function updateProfile(page, payload = {}) {
|
|
939
|
+
const {
|
|
940
|
+
name,
|
|
941
|
+
bio,
|
|
942
|
+
location,
|
|
943
|
+
avatarUrl,
|
|
944
|
+
avatarBase64,
|
|
945
|
+
headerUrl,
|
|
946
|
+
headerBase64,
|
|
947
|
+
} = payload;
|
|
948
|
+
|
|
949
|
+
const fs = require('fs');
|
|
950
|
+
const path = require('path');
|
|
951
|
+
const os = require('os');
|
|
952
|
+
|
|
953
|
+
const hasOwn = (obj, key) => Object.prototype.hasOwnProperty.call(obj, key);
|
|
954
|
+
|
|
955
|
+
const wants = {
|
|
956
|
+
header: !!(headerBase64 || headerUrl),
|
|
957
|
+
avatar: !!(avatarBase64 || avatarUrl),
|
|
958
|
+
name: typeof name === 'string' && name.trim().length > 0,
|
|
959
|
+
bio: hasOwn(payload, 'bio') && typeof bio === 'string',
|
|
960
|
+
location: hasOwn(payload, 'location') && typeof location === 'string',
|
|
961
|
+
};
|
|
962
|
+
|
|
963
|
+
const requestedFields = Object.keys(wants).filter((key) => wants[key]);
|
|
964
|
+
const stagedFields = new Set();
|
|
965
|
+
const partialFailures = [];
|
|
966
|
+
|
|
967
|
+
const logMsg = (msg) => {
|
|
968
|
+
if (typeof log === 'function') log(msg);
|
|
969
|
+
else console.log(msg);
|
|
970
|
+
};
|
|
971
|
+
|
|
972
|
+
const wait = async (ms) => {
|
|
973
|
+
if (typeof sleep === 'function') return sleep(ms);
|
|
974
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
975
|
+
};
|
|
976
|
+
|
|
977
|
+
const locatorFrom = (spec) => {
|
|
978
|
+
if (typeof spec === 'function') return spec(page);
|
|
979
|
+
return page.locator(spec);
|
|
980
|
+
};
|
|
981
|
+
|
|
982
|
+
async function isVisible(locator, timeout = 3000) {
|
|
983
|
+
try {
|
|
984
|
+
await locator.first().waitFor({ state: 'visible', timeout });
|
|
985
|
+
return true;
|
|
986
|
+
} catch {
|
|
987
|
+
return false;
|
|
988
|
+
}
|
|
989
|
+
}
|
|
990
|
+
|
|
991
|
+
async function firstVisible(specs, label, timeout = 8000) {
|
|
992
|
+
for (const spec of specs) {
|
|
993
|
+
try {
|
|
994
|
+
const locator = locatorFrom(spec).first();
|
|
995
|
+
await locator.waitFor({ state: 'visible', timeout });
|
|
996
|
+
return locator;
|
|
997
|
+
} catch {}
|
|
998
|
+
}
|
|
999
|
+
|
|
1000
|
+
throw new Error(`Could not find visible element: ${label}`);
|
|
1001
|
+
}
|
|
1002
|
+
|
|
1003
|
+
async function clickFirst(specs, label, timeout = 8000) {
|
|
1004
|
+
const locator = await firstVisible(specs, label, timeout);
|
|
1005
|
+
|
|
1006
|
+
try {
|
|
1007
|
+
if (typeof humanHover === 'function') {
|
|
1008
|
+
await humanHover(page, locator).catch(() => {});
|
|
1009
|
+
}
|
|
1010
|
+
|
|
1011
|
+
if (typeof highlightElement === 'function') {
|
|
1012
|
+
await highlightElement(page, locator, '#00ff00', label).catch(() => {});
|
|
1013
|
+
}
|
|
1014
|
+
|
|
1015
|
+
await locator.click({ timeout });
|
|
1016
|
+
logMsg(`[updateProfile] Clicked: ${label}`);
|
|
1017
|
+
return locator;
|
|
1018
|
+
} catch (e) {
|
|
1019
|
+
throw new Error(`Could not click ${label}: ${e.message}`);
|
|
1020
|
+
}
|
|
1021
|
+
}
|
|
1022
|
+
|
|
1023
|
+
async function fillFirst(specs, value, label) {
|
|
1024
|
+
const locator = await firstVisible(specs, label, 8000);
|
|
1025
|
+
|
|
1026
|
+
try {
|
|
1027
|
+
if (typeof humanHover === 'function') {
|
|
1028
|
+
await humanHover(page, locator).catch(() => {});
|
|
1029
|
+
}
|
|
1030
|
+
|
|
1031
|
+
if (typeof highlightElement === 'function') {
|
|
1032
|
+
await highlightElement(page, locator, '#00ff00', label).catch(() => {});
|
|
1033
|
+
}
|
|
1034
|
+
|
|
1035
|
+
await locator.click({ timeout: 8000 });
|
|
1036
|
+
await page.keyboard.press('Control+A').catch(() => {});
|
|
1037
|
+
await page.keyboard.press('Backspace').catch(() => {});
|
|
1038
|
+
|
|
1039
|
+
if (typeof safeFill === 'function') {
|
|
1040
|
+
await safeFill(page, locator, value);
|
|
1041
|
+
} else {
|
|
1042
|
+
await locator.fill(value, { timeout: 8000 });
|
|
1043
|
+
}
|
|
1044
|
+
|
|
1045
|
+
await wait(500);
|
|
1046
|
+
logMsg(`[updateProfile] Filled ${label}: ${value}`);
|
|
1047
|
+
return true;
|
|
1048
|
+
} catch (e) {
|
|
1049
|
+
throw new Error(`Could not fill ${label}: ${e.message}`);
|
|
1050
|
+
}
|
|
1051
|
+
}
|
|
1052
|
+
|
|
1053
|
+
function markFail(field, reason) {
|
|
1054
|
+
partialFailures.push({ field, reason });
|
|
1055
|
+
logMsg(`[updateProfile] PARTIAL FAILURE — ${field}: ${reason}`);
|
|
1056
|
+
}
|
|
1057
|
+
|
|
1058
|
+
async function assertLoggedInByClicksUI() {
|
|
1059
|
+
const url = page.url();
|
|
1060
|
+
|
|
1061
|
+
if (
|
|
1062
|
+
url.includes('/login') ||
|
|
1063
|
+
url.includes('/i/flow/login') ||
|
|
1064
|
+
url.includes('/account/access')
|
|
1065
|
+
) {
|
|
1066
|
+
throw new Error('Session expired — account needs manual login first');
|
|
1067
|
+
}
|
|
1068
|
+
|
|
1069
|
+
const sidebarReady = await isVisible(
|
|
1070
|
+
page.locator(
|
|
1071
|
+
'[data-testid="AppTabBar_Profile_Link"], [data-testid="AppTabBar_Home_Link"]'
|
|
1072
|
+
),
|
|
1073
|
+
12000
|
|
1074
|
+
);
|
|
1075
|
+
|
|
1076
|
+
if (!sidebarReady) {
|
|
1077
|
+
throw new Error(
|
|
1078
|
+
'X sidebar not found. Open X manually and login first. This function does not paste URLs.'
|
|
1079
|
+
);
|
|
1080
|
+
}
|
|
1081
|
+
}
|
|
1082
|
+
|
|
1083
|
+
async function openProfileEditorByClicks() {
|
|
1084
|
+
await page.bringToFront().catch(() => {});
|
|
1085
|
+
await assertLoggedInByClicksUI();
|
|
1086
|
+
|
|
1087
|
+
const editorAlreadyOpen = await isVisible(
|
|
1088
|
+
page.locator('input[name="displayName"], input[aria-label^="Name"]').first(),
|
|
1089
|
+
1500
|
|
1090
|
+
);
|
|
1091
|
+
|
|
1092
|
+
if (editorAlreadyOpen) {
|
|
1093
|
+
logMsg('[updateProfile] Profile editor already open');
|
|
1094
|
+
return;
|
|
1095
|
+
}
|
|
1096
|
+
|
|
1097
|
+
const editVisible = await isVisible(
|
|
1098
|
+
page.locator('[data-testid="editProfileButton"], div[role="button"]:has-text("Edit profile")'),
|
|
1099
|
+
1500
|
|
1100
|
+
);
|
|
1101
|
+
|
|
1102
|
+
if (!editVisible) {
|
|
1103
|
+
await clickFirst(
|
|
1104
|
+
[
|
|
1105
|
+
'[data-testid="AppTabBar_Profile_Link"]',
|
|
1106
|
+
(p) => p.getByRole('link', { name: /^Profile$/i }),
|
|
1107
|
+
'a[aria-label="Profile"]',
|
|
1108
|
+
'text=Profile',
|
|
1109
|
+
],
|
|
1110
|
+
'Profile'
|
|
1111
|
+
);
|
|
1112
|
+
|
|
1113
|
+
await wait(2500);
|
|
1114
|
+
}
|
|
1115
|
+
|
|
1116
|
+
await clickFirst(
|
|
1117
|
+
[
|
|
1118
|
+
'[data-testid="editProfileButton"]',
|
|
1119
|
+
(p) => p.getByRole('button', { name: /^Edit profile$/i }),
|
|
1120
|
+
'div[role="button"]:has-text("Edit profile")',
|
|
1121
|
+
'button:has-text("Edit profile")',
|
|
1122
|
+
'text=Edit profile',
|
|
1123
|
+
],
|
|
1124
|
+
'Edit profile'
|
|
1125
|
+
);
|
|
1126
|
+
|
|
1127
|
+
await firstVisible(
|
|
1128
|
+
[
|
|
1129
|
+
'input[name="displayName"]',
|
|
1130
|
+
'input[aria-label^="Name"]',
|
|
1131
|
+
],
|
|
1132
|
+
'profile name input',
|
|
1133
|
+
12000
|
|
1134
|
+
);
|
|
1135
|
+
|
|
1136
|
+
logMsg('[updateProfile] Profile editor opened by clicks');
|
|
1137
|
+
}
|
|
1138
|
+
|
|
1139
|
+
async function imageToTempFileLocal(url, base64, label) {
|
|
1140
|
+
if (typeof imageToTempFile === 'function') {
|
|
1141
|
+
return imageToTempFile(url, base64);
|
|
1142
|
+
}
|
|
1143
|
+
|
|
1144
|
+
// Detect actual image format from base64 data URI prefix
|
|
1145
|
+
let ext = 'jpg';
|
|
1146
|
+
if (base64 && base64.includes(',')) {
|
|
1147
|
+
const prefix = base64.split(',').shift().toLowerCase();
|
|
1148
|
+
if (prefix.includes('png')) ext = 'png';
|
|
1149
|
+
else if (prefix.includes('webp')) ext = 'webp';
|
|
1150
|
+
else if (prefix.includes('jpeg') || prefix.includes('jpg')) ext = 'jpg';
|
|
1151
|
+
}
|
|
1152
|
+
|
|
1153
|
+
const tmpFile = path.join(os.tmpdir(), `x-${label}-${Date.now()}.${ext}`);
|
|
1154
|
+
|
|
1155
|
+
if (base64) {
|
|
1156
|
+
const cleanBase64 = base64.includes(',')
|
|
1157
|
+
? base64.split(',').pop()
|
|
1158
|
+
: base64;
|
|
1159
|
+
|
|
1160
|
+
fs.writeFileSync(tmpFile, Buffer.from(cleanBase64, 'base64'));
|
|
1161
|
+
logMsg(`[updateProfile] ${label}: temp file created: ${tmpFile} (${ext}, ${(Buffer.from(cleanBase64, 'base64').length / 1024).toFixed(1)} KB)`);
|
|
1162
|
+
return tmpFile;
|
|
1163
|
+
}
|
|
1164
|
+
|
|
1165
|
+
if (url) {
|
|
1166
|
+
if (typeof fetch !== 'function') {
|
|
1167
|
+
throw new Error('fetch is not available. Use avatarBase64/headerBase64 instead of URL.');
|
|
1168
|
+
}
|
|
1169
|
+
|
|
1170
|
+
const res = await fetch(url);
|
|
1171
|
+
if (!res.ok) throw new Error(`Image download failed: ${res.status}`);
|
|
1172
|
+
|
|
1173
|
+
const buffer = Buffer.from(await res.arrayBuffer());
|
|
1174
|
+
fs.writeFileSync(tmpFile, buffer);
|
|
1175
|
+
return tmpFile;
|
|
1176
|
+
}
|
|
1177
|
+
|
|
1178
|
+
throw new Error(`No image source provided for ${label}`);
|
|
1179
|
+
}
|
|
1180
|
+
|
|
1181
|
+
async function stageImage(field, url, base64) {
|
|
1182
|
+
let tmpFile = null;
|
|
1183
|
+
|
|
1184
|
+
try {
|
|
1185
|
+
tmpFile = await imageToTempFileLocal(url, base64, field);
|
|
1186
|
+
logMsg(`[updateProfile] ${field} temp file: ${tmpFile} (${url ? 'url' : 'base64'} source)`);
|
|
1187
|
+
|
|
1188
|
+
if (typeof humanScroll === 'function') {
|
|
1189
|
+
await humanScroll(page, 40 + Math.random() * 80).catch(() => {});
|
|
1190
|
+
}
|
|
1191
|
+
|
|
1192
|
+
await wait(700);
|
|
1193
|
+
|
|
1194
|
+
if (typeof uploadProfileImage !== 'function') {
|
|
1195
|
+
throw new Error('uploadProfileImage helper is missing');
|
|
1196
|
+
}
|
|
1197
|
+
|
|
1198
|
+
const uploaded = await uploadProfileImage(page, tmpFile, field);
|
|
1199
|
+
|
|
1200
|
+
if (!uploaded) {
|
|
1201
|
+
markFail(field, 'upload trigger or file input not found');
|
|
1202
|
+
return false;
|
|
1203
|
+
}
|
|
1204
|
+
|
|
1205
|
+
stagedFields.add(field);
|
|
1206
|
+
logMsg(`[updateProfile] ${field} staged successfully`);
|
|
1207
|
+
return true;
|
|
1208
|
+
} catch (e) {
|
|
1209
|
+
markFail(field, e.message);
|
|
1210
|
+
return false;
|
|
1211
|
+
} finally {
|
|
1212
|
+
if (tmpFile) {
|
|
1213
|
+
try {
|
|
1214
|
+
fs.unlinkSync(tmpFile);
|
|
1215
|
+
} catch {}
|
|
1216
|
+
}
|
|
1217
|
+
}
|
|
1218
|
+
}
|
|
1219
|
+
|
|
1220
|
+
async function clickSaveOnce() {
|
|
1221
|
+
// STEP 1: Make sure no "Edit media" cropper is open — close it first by clicking Apply
|
|
1222
|
+
if (typeof isEditMediaOpen === 'function') {
|
|
1223
|
+
let mediaOpen = await isEditMediaOpen(page).catch(() => false);
|
|
1224
|
+
let attempts = 0;
|
|
1225
|
+
while (mediaOpen && attempts < 3) {
|
|
1226
|
+
logMsg(`[updateProfile] Edit media modal still open — clicking Apply (attempt ${attempts + 1})`);
|
|
1227
|
+
if (typeof confirmMediaEdit === 'function') {
|
|
1228
|
+
const closed = await confirmMediaEdit(page, 'All');
|
|
1229
|
+
if (!closed) {
|
|
1230
|
+
logMsg('[updateProfile] ⚠️ Could not close Edit media modal');
|
|
1231
|
+
break;
|
|
1232
|
+
}
|
|
1233
|
+
}
|
|
1234
|
+
await wait(1500);
|
|
1235
|
+
mediaOpen = await isEditMediaOpen(page).catch(() => false);
|
|
1236
|
+
attempts += 1;
|
|
1237
|
+
}
|
|
1238
|
+
if (mediaOpen) {
|
|
1239
|
+
logMsg('[updateProfile] ⚠️ Edit media modal still open after all attempts — pressing Escape');
|
|
1240
|
+
await page.keyboard.press('Escape').catch(() => {});
|
|
1241
|
+
await wait(1000);
|
|
1242
|
+
}
|
|
1243
|
+
}
|
|
1244
|
+
|
|
1245
|
+
// STEP 2: Wait for any pending image processing (cropper, upload, etc.)
|
|
1246
|
+
// X needs a moment to fully process the image after Apply before Save is enabled
|
|
1247
|
+
logMsg('[updateProfile] Waiting for image to finish processing...');
|
|
1248
|
+
await wait(3000);
|
|
1249
|
+
|
|
1250
|
+
// STEP 3: Wait for the profile Save button to become enabled
|
|
1251
|
+
let saveBtn = null;
|
|
1252
|
+
logMsg('[updateProfile] Waiting for Save button to be ready...');
|
|
1253
|
+
if (typeof waitForSaveButtonReady === 'function') {
|
|
1254
|
+
saveBtn = await waitForSaveButtonReady(page, 'All', 20000);
|
|
1255
|
+
}
|
|
1256
|
+
|
|
1257
|
+
if (!saveBtn) {
|
|
1258
|
+
// Retry once more — maybe the image is still processing
|
|
1259
|
+
logMsg('[updateProfile] Save button not ready, waiting longer and retrying...');
|
|
1260
|
+
await wait(3000);
|
|
1261
|
+
if (typeof waitForSaveButtonReady === 'function') {
|
|
1262
|
+
saveBtn = await waitForSaveButtonReady(page, 'All', 15000);
|
|
1263
|
+
}
|
|
1264
|
+
}
|
|
1265
|
+
|
|
1266
|
+
if (!saveBtn) {
|
|
1267
|
+
// Final fallback — just find any visible Save button
|
|
1268
|
+
saveBtn = await firstVisible(
|
|
1269
|
+
[
|
|
1270
|
+
'[data-testid="Profile_Save_Button"]',
|
|
1271
|
+
(p) => p.getByRole('button', { name: /^Save$/i }),
|
|
1272
|
+
'div[role="button"]:has-text("Save")',
|
|
1273
|
+
'button:has-text("Save")',
|
|
1274
|
+
'text=Save',
|
|
1275
|
+
],
|
|
1276
|
+
'Save button',
|
|
1277
|
+
10000
|
|
1278
|
+
);
|
|
1279
|
+
}
|
|
1280
|
+
|
|
1281
|
+
if (typeof highlightElement === 'function') {
|
|
1282
|
+
await highlightElement(page, saveBtn, 'red', 'SAVE').catch(() => {});
|
|
1283
|
+
}
|
|
1284
|
+
|
|
1285
|
+
if (typeof randDelay === 'function') {
|
|
1286
|
+
await randDelay(500, 1000).catch(() => {});
|
|
1287
|
+
} else {
|
|
1288
|
+
await wait(800);
|
|
1289
|
+
}
|
|
1290
|
+
|
|
1291
|
+
// STEP 4: Click Save
|
|
1292
|
+
await saveBtn.click({ timeout: 10000 });
|
|
1293
|
+
logMsg('[updateProfile] ✅ Save clicked');
|
|
1294
|
+
|
|
1295
|
+
// STEP 5: Wait for save to complete
|
|
1296
|
+
if (typeof waitForSaveComplete === 'function') {
|
|
1297
|
+
return waitForSaveComplete(page, 'All');
|
|
1298
|
+
}
|
|
1299
|
+
|
|
1300
|
+
await wait(6000);
|
|
1301
|
+
return true;
|
|
1302
|
+
}
|
|
1303
|
+
|
|
1304
|
+
async function getBodyTextSafe() {
|
|
1305
|
+
if (typeof getBodyText === 'function') {
|
|
1306
|
+
return getBodyText(page);
|
|
1307
|
+
}
|
|
1308
|
+
|
|
1309
|
+
return page.locator('body').innerText({ timeout: 5000 }).catch(() => '');
|
|
1310
|
+
}
|
|
1311
|
+
|
|
1312
|
+
async function reopenEditorForVerify() {
|
|
1313
|
+
const nameInputVisible = await isVisible(
|
|
1314
|
+
page.locator('input[name="displayName"], input[aria-label^="Name"]').first(),
|
|
1315
|
+
1000
|
|
1316
|
+
);
|
|
1317
|
+
|
|
1318
|
+
if (nameInputVisible) return true;
|
|
1319
|
+
|
|
1320
|
+
await clickFirst(
|
|
1321
|
+
[
|
|
1322
|
+
'[data-testid="editProfileButton"]',
|
|
1323
|
+
(p) => p.getByRole('button', { name: /^Edit profile$/i }),
|
|
1324
|
+
'div[role="button"]:has-text("Edit profile")',
|
|
1325
|
+
'button:has-text("Edit profile")',
|
|
1326
|
+
'text=Edit profile',
|
|
1327
|
+
],
|
|
1328
|
+
'Edit profile for verification',
|
|
1329
|
+
10000
|
|
1330
|
+
);
|
|
1331
|
+
|
|
1332
|
+
await firstVisible(
|
|
1333
|
+
[
|
|
1334
|
+
'input[name="displayName"]',
|
|
1335
|
+
'input[aria-label^="Name"]',
|
|
1336
|
+
],
|
|
1337
|
+
'profile editor for verification',
|
|
1338
|
+
10000
|
|
1339
|
+
);
|
|
1340
|
+
|
|
1341
|
+
return true;
|
|
1342
|
+
}
|
|
1343
|
+
|
|
1344
|
+
async function verifyTextFields() {
|
|
1345
|
+
const needVerify = stagedFields.has('name') || stagedFields.has('bio') || stagedFields.has('location');
|
|
1346
|
+
if (!needVerify) return;
|
|
1347
|
+
|
|
1348
|
+
await reopenEditorForVerify();
|
|
1349
|
+
|
|
1350
|
+
if (stagedFields.has('name')) {
|
|
1351
|
+
const currentName = await page
|
|
1352
|
+
.locator('input[name="displayName"], input[aria-label^="Name"]')
|
|
1353
|
+
.first()
|
|
1354
|
+
.inputValue()
|
|
1355
|
+
.catch(() => '');
|
|
1356
|
+
|
|
1357
|
+
if (currentName.trim() !== name.trim()) {
|
|
1358
|
+
markFail('name', `did not persist. Expected "${name}", got "${currentName}"`);
|
|
1359
|
+
}
|
|
1360
|
+
}
|
|
1361
|
+
|
|
1362
|
+
if (stagedFields.has('bio')) {
|
|
1363
|
+
const currentBio = await page
|
|
1364
|
+
.locator('textarea[name="description"], textarea[aria-label^="Bio"]')
|
|
1365
|
+
.first()
|
|
1366
|
+
.inputValue()
|
|
1367
|
+
.catch(() => '');
|
|
1368
|
+
|
|
1369
|
+
if (currentBio.trim() !== bio.trim()) {
|
|
1370
|
+
markFail('bio', `did not persist. Expected "${bio}", got "${currentBio}"`);
|
|
1371
|
+
}
|
|
1372
|
+
}
|
|
1373
|
+
|
|
1374
|
+
if (stagedFields.has('location')) {
|
|
1375
|
+
const currentLocation = await page
|
|
1376
|
+
.locator('input[name="location"], input[aria-label^="Location"]')
|
|
1377
|
+
.first()
|
|
1378
|
+
.inputValue()
|
|
1379
|
+
.catch(() => '');
|
|
1380
|
+
|
|
1381
|
+
if (currentLocation.trim() !== location.trim()) {
|
|
1382
|
+
markFail('location', `did not persist. Expected "${location}", got "${currentLocation}"`);
|
|
1383
|
+
}
|
|
1384
|
+
}
|
|
1385
|
+
|
|
1386
|
+
await page.keyboard.press('Escape').catch(() => {});
|
|
1387
|
+
}
|
|
1388
|
+
|
|
1389
|
+
async function captureFailureContext(reason) {
|
|
1390
|
+
const ctx = { reason };
|
|
1391
|
+
|
|
1392
|
+
try {
|
|
1393
|
+
const shot = await page.screenshot({
|
|
1394
|
+
type: 'png',
|
|
1395
|
+
fullPage: false,
|
|
1396
|
+
timeout: 5000,
|
|
1397
|
+
});
|
|
1398
|
+
|
|
1399
|
+
ctx.screenshotBase64 = shot.toString('base64');
|
|
1400
|
+
} catch (e) {
|
|
1401
|
+
ctx.screenshotError = e.message;
|
|
1402
|
+
}
|
|
1403
|
+
|
|
1404
|
+
return ctx;
|
|
1405
|
+
}
|
|
1406
|
+
|
|
1407
|
+
// ── Start ────────────────────────────────────────────────────────────────
|
|
1408
|
+
|
|
1409
|
+
await openProfileEditorByClicks();
|
|
1410
|
+
|
|
1411
|
+
if (wants.avatar) {
|
|
1412
|
+
await stageImage('avatar', avatarUrl, avatarBase64);
|
|
1413
|
+
}
|
|
1414
|
+
|
|
1415
|
+
if (wants.header) {
|
|
1416
|
+
await stageImage('header', headerUrl, headerBase64);
|
|
1417
|
+
}
|
|
1418
|
+
|
|
1419
|
+
if (wants.name) {
|
|
1420
|
+
try {
|
|
1421
|
+
await fillFirst(
|
|
1422
|
+
[
|
|
1423
|
+
'input[name="displayName"]',
|
|
1424
|
+
'input[aria-label^="Name"]',
|
|
1425
|
+
],
|
|
1426
|
+
name,
|
|
1427
|
+
'Name'
|
|
1428
|
+
);
|
|
1429
|
+
|
|
1430
|
+
stagedFields.add('name');
|
|
1431
|
+
} catch (e) {
|
|
1432
|
+
markFail('name', e.message);
|
|
1433
|
+
}
|
|
1434
|
+
}
|
|
1435
|
+
|
|
1436
|
+
if (wants.bio) {
|
|
1437
|
+
try {
|
|
1438
|
+
await fillFirst(
|
|
1439
|
+
[
|
|
1440
|
+
'textarea[name="description"]',
|
|
1441
|
+
'textarea[aria-label^="Bio"]',
|
|
1442
|
+
],
|
|
1443
|
+
bio,
|
|
1444
|
+
'Bio'
|
|
1445
|
+
);
|
|
1446
|
+
|
|
1447
|
+
stagedFields.add('bio');
|
|
1448
|
+
} catch (e) {
|
|
1449
|
+
markFail('bio', e.message);
|
|
1450
|
+
}
|
|
1451
|
+
}
|
|
1452
|
+
|
|
1453
|
+
if (wants.location) {
|
|
1454
|
+
try {
|
|
1455
|
+
await fillFirst(
|
|
1456
|
+
[
|
|
1457
|
+
'input[name="location"]',
|
|
1458
|
+
'input[aria-label^="Location"]',
|
|
1459
|
+
],
|
|
1460
|
+
location,
|
|
1461
|
+
'Location'
|
|
1462
|
+
);
|
|
1463
|
+
|
|
1464
|
+
stagedFields.add('location');
|
|
1465
|
+
} catch (e) {
|
|
1466
|
+
markFail('location', e.message);
|
|
1467
|
+
}
|
|
1468
|
+
}
|
|
1469
|
+
|
|
1470
|
+
if (stagedFields.size === 0) {
|
|
1471
|
+
const ctx = await captureFailureContext('No requested changes were staged');
|
|
1472
|
+
throw Object.assign(
|
|
1473
|
+
new Error('Profile update failed — no requested changes were staged'),
|
|
1474
|
+
{ failureContext: ctx, partialFailures }
|
|
1475
|
+
);
|
|
1476
|
+
}
|
|
1477
|
+
|
|
1478
|
+
await wait(1200);
|
|
1479
|
+
|
|
1480
|
+
const saved = await clickSaveOnce();
|
|
1481
|
+
|
|
1482
|
+
if (!saved) {
|
|
1483
|
+
for (const field of stagedFields) {
|
|
1484
|
+
markFail(field, 'Save did not complete');
|
|
1485
|
+
}
|
|
1486
|
+
|
|
1487
|
+
const ctx = await captureFailureContext('Save did not complete');
|
|
1488
|
+
throw Object.assign(
|
|
1489
|
+
new Error('Profile update failed — Save did not complete'),
|
|
1490
|
+
{ failureContext: ctx, partialFailures }
|
|
1491
|
+
);
|
|
1492
|
+
}
|
|
1493
|
+
|
|
1494
|
+
await wait(4000);
|
|
1495
|
+
|
|
1496
|
+
const bodyText = (await getBodyTextSafe()).toLowerCase();
|
|
1497
|
+
|
|
1498
|
+
const errorPhrases = [
|
|
1499
|
+
'something went wrong',
|
|
1500
|
+
'please try again',
|
|
1501
|
+
'failed to update',
|
|
1502
|
+
"couldn't update",
|
|
1503
|
+
"name can't be blank",
|
|
1504
|
+
'bio is too long',
|
|
1505
|
+
'there was an error',
|
|
1506
|
+
'unable to save',
|
|
1507
|
+
'some media was not uploaded',
|
|
1508
|
+
'media was not uploaded',
|
|
1509
|
+
];
|
|
1510
|
+
|
|
1511
|
+
const hasError = errorPhrases.some((phrase) => bodyText.includes(phrase));
|
|
1512
|
+
|
|
1513
|
+
if (hasError) {
|
|
1514
|
+
const ctx = await captureFailureContext('X rejected the profile update');
|
|
1515
|
+
throw Object.assign(
|
|
1516
|
+
new Error('X rejected the profile update. Account may need manual check.'),
|
|
1517
|
+
{ failureContext: ctx, partialFailures }
|
|
1518
|
+
);
|
|
1519
|
+
}
|
|
1520
|
+
|
|
1521
|
+
await verifyTextFields();
|
|
1522
|
+
|
|
1523
|
+
const failedFields = new Set(partialFailures.map((f) => f.field));
|
|
1524
|
+
const allRequestedFailed =
|
|
1525
|
+
requestedFields.length > 0 &&
|
|
1526
|
+
requestedFields.every((field) => failedFields.has(field));
|
|
1527
|
+
|
|
1528
|
+
if (allRequestedFailed) {
|
|
1529
|
+
const ctx = await captureFailureContext('All requested fields failed');
|
|
1530
|
+
throw Object.assign(
|
|
1531
|
+
new Error('Profile update failed — all requested fields failed'),
|
|
1532
|
+
{ failureContext: ctx, partialFailures }
|
|
1533
|
+
);
|
|
1534
|
+
}
|
|
1535
|
+
|
|
1536
|
+
const result = {
|
|
1537
|
+
success: true,
|
|
1538
|
+
message: 'Profile updated by clicks and verified',
|
|
1539
|
+
};
|
|
1540
|
+
|
|
1541
|
+
if (partialFailures.length) {
|
|
1542
|
+
result.partialFailures = partialFailures;
|
|
1543
|
+
}
|
|
1544
|
+
|
|
1545
|
+
logMsg('[updateProfile] Profile update completed');
|
|
1546
|
+
return result;
|
|
1547
|
+
}
|
|
1548
|
+
|
|
1549
|
+
// ── Change password ──────────────────────────────────────────────────────────
|
|
1550
|
+
async function changePassword(page, payload) {
|
|
1551
|
+
const { currentPassword, newPassword } = payload;
|
|
1552
|
+
|
|
1553
|
+
await page.goto('https://x.com/settings/password', { waitUntil: 'domcontentloaded', timeout: 30000 }).catch(() => {});
|
|
1554
|
+
await sleep(2000);
|
|
1555
|
+
|
|
1556
|
+
if (page.url().includes('/login') || page.url().includes('/i/flow/login')) {
|
|
1557
|
+
throw new Error('Session expired — account needs to log in first');
|
|
1558
|
+
}
|
|
1559
|
+
|
|
1560
|
+
// Fill current password
|
|
1561
|
+
const currentSelectors = ['input[aria-label="Current password"]', 'input[name="current_password"]', 'input[autocomplete="current-password"]'];
|
|
1562
|
+
for (const sel of currentSelectors) {
|
|
1563
|
+
const el = page.locator(sel).first();
|
|
1564
|
+
if (await el.isVisible({ timeout: 3000 }).catch(() => false)) {
|
|
1565
|
+
await safeFill(page, el, currentPassword);
|
|
1566
|
+
break;
|
|
1567
|
+
}
|
|
1568
|
+
}
|
|
1569
|
+
|
|
1570
|
+
// Fill new password
|
|
1571
|
+
const newSelectors = ['input[aria-label="New password"]', 'input[name="new_password"]', 'input[autocomplete="new-password"]'];
|
|
1572
|
+
for (const sel of newSelectors) {
|
|
1573
|
+
const el = page.locator(sel).first();
|
|
1574
|
+
if (await el.isVisible({ timeout: 3000 }).catch(() => false)) {
|
|
1575
|
+
await safeFill(page, el, newPassword);
|
|
1576
|
+
break;
|
|
1577
|
+
}
|
|
1578
|
+
}
|
|
1579
|
+
|
|
1580
|
+
// Confirm
|
|
1581
|
+
const confirmSelectors = ['input[aria-label="Confirm password"]', 'input[name="password_confirmation"]'];
|
|
1582
|
+
for (const sel of confirmSelectors) {
|
|
1583
|
+
const el = page.locator(sel).first();
|
|
1584
|
+
if (await el.isVisible({ timeout: 3000 }).catch(() => false)) {
|
|
1585
|
+
await safeFill(page, el, newPassword);
|
|
1586
|
+
break;
|
|
1587
|
+
}
|
|
1588
|
+
}
|
|
1589
|
+
|
|
1590
|
+
// Submit
|
|
1591
|
+
const submitSelectors = ['button:has-text("Save")', 'button:has-text("Change password")', '[role="button"]:has-text("Save")'];
|
|
1592
|
+
for (const sel of submitSelectors) {
|
|
1593
|
+
const el = page.locator(sel).first();
|
|
1594
|
+
if (await el.isVisible({ timeout: 3000 }).catch(() => false)) {
|
|
1595
|
+
await humanClick(page, el);
|
|
1596
|
+
break;
|
|
1597
|
+
}
|
|
1598
|
+
}
|
|
1599
|
+
|
|
1600
|
+
await sleep(3000);
|
|
1601
|
+
|
|
1602
|
+
// Check for failure
|
|
1603
|
+
const bodyText = await getBodyText(page);
|
|
1604
|
+
if (bodyText.includes('incorrect password') || bodyText.includes('wrong password')) {
|
|
1605
|
+
return { success: false, error: 'Current password is incorrect' };
|
|
1606
|
+
}
|
|
1607
|
+
|
|
1608
|
+
return { success: true, message: 'Password changed successfully' };
|
|
1609
|
+
}
|
|
1610
|
+
|
|
1611
1611
|
module.exports = { autoLogin, checkLoginState, checkStatus, getProfileInfo, updateProfile, changePassword, detectCaptcha, solveCaptchaWithDBC };
|