feat: add Auto Run mode for full automated flow
- Background: add step completion waiting (promise-based), autoRun/resumeAutoRun chains steps 1→2 (pause for email) → 3→4→5→6→7→8→9 automatically - Side Panel: add "Auto Run" button and "Continue Auto" bar for email pause point - signup-page.js: add step 8 handler to click "继续" on OAuth consent page - Fix all steps to reportComplete before form submit (prevents connection loss on navigation) - qq-mail.js: fallback after 3 attempts to first matching email - vps-panel.js: step 9 waits for "认证成功!" status badge
This commit is contained in:
+100
-186
@@ -1,64 +1,27 @@
|
||||
// content/qq-mail.js — Content script for QQ Mail (steps 4, 7)
|
||||
// Injected on: mail.qq.com, wx.mail.qq.com
|
||||
// NOTE: all_frames: true — this script runs in every frame on QQ Mail
|
||||
// NOTE: all_frames: true
|
||||
//
|
||||
// Strategy for avoiding stale codes:
|
||||
// 1. On poll start, snapshot all existing mail IDs as "old"
|
||||
// 2. On each poll cycle, refresh inbox and look for NEW items (not in snapshot)
|
||||
// 3. Only extract codes from NEW items that match sender/subject filters
|
||||
|
||||
const QQ_MAIL_PREFIX = '[MultiPage:qq-mail]';
|
||||
const isNewVersion = location.hostname === 'wx.mail.qq.com';
|
||||
const isTopFrame = window === window.top;
|
||||
|
||||
console.log(QQ_MAIL_PREFIX, 'Content script loaded on', location.href, 'frame:', isTopFrame ? 'top' : 'child');
|
||||
|
||||
// For old QQ Mail with iframes, only report ready from the top frame
|
||||
// to avoid duplicate registrations. The inbox frame will handle email ops.
|
||||
if (!isTopFrame && isNewVersion) {
|
||||
console.log(QQ_MAIL_PREFIX, 'Skipping non-top frame on new QQ Mail');
|
||||
// Don't do anything in child frames of new version
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Frame detection
|
||||
// ============================================================
|
||||
|
||||
function isInboxFrame() {
|
||||
if (isNewVersion) return isTopFrame;
|
||||
// Old version: check if this frame has email list elements
|
||||
return !!document.querySelector(
|
||||
'#mailList, .mail-list, [id*="mailList"], #frm_main, .toarea, .mailList'
|
||||
);
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Login State Check
|
||||
// ============================================================
|
||||
|
||||
function checkLoginState() {
|
||||
if (isNewVersion) {
|
||||
// wx.mail.qq.com: look for compose button or folder list
|
||||
return !!(
|
||||
document.querySelector('[class*="folder"], [class*="compose"], [class*="sidebar"]') ||
|
||||
document.querySelector('nav, [role="navigation"]') ||
|
||||
document.querySelector('[class*="mail-list"], [class*="mailList"]')
|
||||
);
|
||||
} else {
|
||||
// mail.qq.com: look for known logged-in elements
|
||||
return !!(
|
||||
document.querySelector('#folder_1, .folder_inbox, #composebtn, #mainFrameContainer')
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Message Handler
|
||||
// ============================================================
|
||||
|
||||
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
|
||||
if (message.type === 'POLL_EMAIL') {
|
||||
// For old QQ Mail, only handle in the inbox frame
|
||||
if (!isNewVersion && !isInboxFrame()) {
|
||||
if (!isTopFrame) {
|
||||
sendResponse({ ok: false, reason: 'wrong-frame' });
|
||||
return;
|
||||
}
|
||||
|
||||
handlePollEmail(message.step, message.payload).then(result => {
|
||||
sendResponse(result);
|
||||
}).catch(err => {
|
||||
@@ -67,60 +30,93 @@ chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
|
||||
});
|
||||
return true; // async response
|
||||
}
|
||||
|
||||
if (message.type === 'CHECK_LOGIN') {
|
||||
if (!isTopFrame) {
|
||||
sendResponse({ loggedIn: false });
|
||||
return;
|
||||
}
|
||||
sendResponse({ loggedIn: checkLoginState() });
|
||||
return;
|
||||
}
|
||||
});
|
||||
|
||||
// ============================================================
|
||||
// Get all current mail IDs from the list
|
||||
// ============================================================
|
||||
|
||||
function getCurrentMailIds() {
|
||||
const ids = new Set();
|
||||
document.querySelectorAll('.mail-list-page-item[data-mailid]').forEach(item => {
|
||||
ids.add(item.getAttribute('data-mailid'));
|
||||
});
|
||||
return ids;
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Email Polling
|
||||
// ============================================================
|
||||
|
||||
async function handlePollEmail(step, payload) {
|
||||
const { filterAfterTimestamp, senderFilters, subjectFilters, maxAttempts, intervalMs } = payload;
|
||||
|
||||
// Check login state first
|
||||
if (isTopFrame && !checkLoginState()) {
|
||||
throw new Error('QQ Mail not logged in. Please log in to QQ Mail and retry.');
|
||||
}
|
||||
const { senderFilters, subjectFilters, maxAttempts, intervalMs } = payload;
|
||||
|
||||
log(`Step ${step}: Starting email poll (max ${maxAttempts} attempts, every ${intervalMs / 1000}s)`);
|
||||
|
||||
// Wait for mail list to load
|
||||
try {
|
||||
await waitForElement('.mail-list-page-item', 10000);
|
||||
log(`Step ${step}: Mail list loaded`);
|
||||
} catch {
|
||||
throw new Error('Mail list did not load. Make sure QQ Mail inbox is open.');
|
||||
}
|
||||
|
||||
// Step 1: Snapshot existing mail IDs BEFORE we start waiting for new email
|
||||
const existingMailIds = getCurrentMailIds();
|
||||
log(`Step ${step}: Snapshotted ${existingMailIds.size} existing emails as "old"`);
|
||||
|
||||
// Fallback after just 3 attempts (~10s). In practice, the email is usually
|
||||
// already in the list but has the same mailid (page was already open).
|
||||
const FALLBACK_AFTER = 3;
|
||||
|
||||
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
|
||||
log(`Polling QQ Mail... attempt ${attempt}/${maxAttempts}`);
|
||||
|
||||
// Try to refresh inbox
|
||||
await refreshInbox();
|
||||
await sleep(800); // Wait for refresh to take effect
|
||||
// Refresh inbox (skip on first attempt, list is fresh)
|
||||
if (attempt > 1) {
|
||||
await refreshInbox();
|
||||
await sleep(800);
|
||||
}
|
||||
|
||||
// Search for matching email
|
||||
const result = await findMatchingEmail(senderFilters, subjectFilters);
|
||||
const allItems = document.querySelectorAll('.mail-list-page-item[data-mailid]');
|
||||
const useFallback = attempt > FALLBACK_AFTER;
|
||||
|
||||
if (result) {
|
||||
log(`Step ${step}: Found matching email! Extracting code...`);
|
||||
const code = extractVerificationCode(result.content);
|
||||
if (code) {
|
||||
log(`Step ${step}: Verification code found: ${code}`, 'ok');
|
||||
return { ok: true, code, emailTimestamp: Date.now() };
|
||||
} else {
|
||||
log(`Step ${step}: Email found but no 6-digit code in content. Preview: ${result.content.slice(0, 100)}`, 'warn');
|
||||
// Phase 1 (attempt 1~3): only look at NEW emails (not in snapshot)
|
||||
// Phase 2 (attempt 4+): fallback to first matching email in list
|
||||
for (const item of allItems) {
|
||||
const mailId = item.getAttribute('data-mailid');
|
||||
|
||||
if (!useFallback && existingMailIds.has(mailId)) continue;
|
||||
|
||||
const sender = (item.querySelector('.cmp-account-nick')?.textContent || '').toLowerCase();
|
||||
const subject = (item.querySelector('.mail-subject')?.textContent || '').toLowerCase();
|
||||
const digest = item.querySelector('.mail-digest')?.textContent || '';
|
||||
|
||||
const senderMatch = senderFilters.some(f => sender.includes(f.toLowerCase()));
|
||||
const subjectMatch = subjectFilters.some(f => subject.includes(f.toLowerCase()));
|
||||
|
||||
if (senderMatch || subjectMatch) {
|
||||
const code = extractVerificationCode(subject + ' ' + digest);
|
||||
if (code) {
|
||||
const source = useFallback && existingMailIds.has(mailId) ? 'fallback-first-match' : 'new';
|
||||
log(`Step ${step}: Code found: ${code} (${source}, subject: ${subject.slice(0, 40)})`, 'ok');
|
||||
return { ok: true, code, emailTimestamp: Date.now(), mailId };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (attempt === FALLBACK_AFTER + 1) {
|
||||
log(`Step ${step}: No new emails after ${FALLBACK_AFTER} attempts, falling back to first matching email`, 'warn');
|
||||
}
|
||||
|
||||
if (attempt < maxAttempts) {
|
||||
await sleep(intervalMs);
|
||||
}
|
||||
}
|
||||
|
||||
throw new Error(
|
||||
`No matching email found after ${(maxAttempts * intervalMs / 1000).toFixed(0)}s. ` +
|
||||
'Check QQ Mail manually. Email may be in spam folder.'
|
||||
`No new matching email found after ${(maxAttempts * intervalMs / 1000).toFixed(0)}s. ` +
|
||||
'Check QQ Mail manually. Email may be delayed or in spam folder.'
|
||||
);
|
||||
}
|
||||
|
||||
@@ -129,114 +125,33 @@ async function handlePollEmail(step, payload) {
|
||||
// ============================================================
|
||||
|
||||
async function refreshInbox() {
|
||||
if (isNewVersion) {
|
||||
// wx.mail.qq.com: try multiple refresh selectors
|
||||
const refreshBtn = document.querySelector(
|
||||
'[class*="refresh"], [title*="刷新"], button[aria-label*="refresh"], ' +
|
||||
'[data-action="refresh"], .toolbar-refresh'
|
||||
);
|
||||
if (refreshBtn) {
|
||||
simulateClick(refreshBtn);
|
||||
console.log(QQ_MAIL_PREFIX, 'Clicked refresh button (new version)');
|
||||
} else {
|
||||
// Fallback: click on "Inbox" folder to force reload
|
||||
const inboxLink = document.querySelector(
|
||||
'[class*="inbox"], [title*="收件箱"], a[href*="inbox"]'
|
||||
);
|
||||
if (inboxLink) {
|
||||
simulateClick(inboxLink);
|
||||
console.log(QQ_MAIL_PREFIX, 'Clicked inbox link to refresh');
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// mail.qq.com: old version
|
||||
const refreshBtn = document.querySelector(
|
||||
'#refresh, .refresh_btn, [id*="refresh"], a[title*="刷新"]'
|
||||
);
|
||||
if (refreshBtn) {
|
||||
simulateClick(refreshBtn);
|
||||
console.log(QQ_MAIL_PREFIX, 'Clicked refresh button (old version)');
|
||||
}
|
||||
}
|
||||
}
|
||||
// Try multiple strategies to refresh the mail list
|
||||
|
||||
// ============================================================
|
||||
// Find Matching Email
|
||||
// ============================================================
|
||||
|
||||
async function findMatchingEmail(senderFilters, subjectFilters) {
|
||||
let emailItems;
|
||||
|
||||
if (isNewVersion) {
|
||||
// wx.mail.qq.com: email list items
|
||||
emailItems = document.querySelectorAll(
|
||||
'[class*="mail-item"], [class*="list-item"], [class*="mail_item"], ' +
|
||||
'tr[class*="mail"], div[class*="letter"], [class*="thread"]'
|
||||
);
|
||||
} else {
|
||||
// mail.qq.com: email list inside table
|
||||
emailItems = document.querySelectorAll(
|
||||
'.toarea tr, #mailList tr, .mail_list tr, [id*="mail_"] tr'
|
||||
);
|
||||
// Strategy 1: Click any visible refresh button
|
||||
const refreshBtn = document.querySelector('[class*="refresh"], [title*="刷新"]');
|
||||
if (refreshBtn) {
|
||||
simulateClick(refreshBtn);
|
||||
console.log(QQ_MAIL_PREFIX, 'Clicked refresh button');
|
||||
await sleep(500);
|
||||
return;
|
||||
}
|
||||
|
||||
console.log(QQ_MAIL_PREFIX, `Found ${emailItems.length} email items to scan`);
|
||||
|
||||
for (const item of emailItems) {
|
||||
const text = (item.textContent || '').toLowerCase();
|
||||
|
||||
const senderMatch = senderFilters.some(f => text.includes(f.toLowerCase()));
|
||||
const subjectMatch = subjectFilters.some(f => text.includes(f.toLowerCase()));
|
||||
|
||||
if (senderMatch || subjectMatch) {
|
||||
console.log(QQ_MAIL_PREFIX, 'Found matching email item:', text.slice(0, 100));
|
||||
|
||||
// Try to get content from the visible text first
|
||||
let content = item.textContent || '';
|
||||
|
||||
// Check if we can already extract a code from the preview
|
||||
if (extractVerificationCode(content)) {
|
||||
return { content };
|
||||
}
|
||||
|
||||
// Need to click into the email for full body
|
||||
log('Clicking email to read full content...');
|
||||
simulateClick(item);
|
||||
await sleep(1500);
|
||||
|
||||
// Read email body
|
||||
const bodyEl = document.querySelector(
|
||||
'[class*="mail-body"], [class*="mail_body"], [class*="letter-body"], ' +
|
||||
'.body_content, #contentDiv, [class*="read-content"], [class*="mail-detail"]'
|
||||
);
|
||||
|
||||
if (bodyEl) {
|
||||
content = bodyEl.textContent || bodyEl.innerText || '';
|
||||
console.log(QQ_MAIL_PREFIX, 'Email body content:', content.slice(0, 200));
|
||||
}
|
||||
|
||||
// Go back to inbox after reading
|
||||
await goBackToInbox();
|
||||
|
||||
return { content };
|
||||
}
|
||||
// Strategy 2: Click inbox in sidebar to reload list
|
||||
const sidebarInbox = document.querySelector('a[href*="inbox"], [class*="folder-item"][class*="inbox"], [title="收件箱"]');
|
||||
if (sidebarInbox) {
|
||||
simulateClick(sidebarInbox);
|
||||
console.log(QQ_MAIL_PREFIX, 'Clicked sidebar inbox');
|
||||
await sleep(500);
|
||||
return;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
async function goBackToInbox() {
|
||||
if (isNewVersion) {
|
||||
// Click back or inbox link
|
||||
const backBtn = document.querySelector(
|
||||
'[class*="back"], [aria-label*="back"], [title*="返回"], [class*="return"]'
|
||||
);
|
||||
if (backBtn) {
|
||||
simulateClick(backBtn);
|
||||
await sleep(500);
|
||||
}
|
||||
// Strategy 3: Click the folder name in toolbar
|
||||
const folderName = document.querySelector('.toolbar-folder-name');
|
||||
if (folderName) {
|
||||
simulateClick(folderName);
|
||||
console.log(QQ_MAIL_PREFIX, 'Clicked toolbar folder name');
|
||||
await sleep(500);
|
||||
}
|
||||
// Old version typically uses frames, no need to go back
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
@@ -244,18 +159,17 @@ async function goBackToInbox() {
|
||||
// ============================================================
|
||||
|
||||
function extractVerificationCode(text) {
|
||||
// Try various patterns for 6-digit verification codes
|
||||
// Pattern 1: standalone 6 digits
|
||||
// Pattern 1: Chinese format "代码为 370794" or "验证码...370794"
|
||||
const matchCn = text.match(/(?:代码为|验证码[^0-9]*?)[\s::]*(\d{6})/);
|
||||
if (matchCn) return matchCn[1];
|
||||
|
||||
// Pattern 2: English format "code is 370794" or "code: 370794"
|
||||
const matchEn = text.match(/code[:\s]+is[:\s]+(\d{6})|code[:\s]+(\d{6})/i);
|
||||
if (matchEn) return matchEn[1] || matchEn[2];
|
||||
|
||||
// Pattern 3: standalone 6-digit number (first occurrence)
|
||||
const match6 = text.match(/\b(\d{6})\b/);
|
||||
if (match6) return match6[1];
|
||||
|
||||
// Pattern 2: code/verification followed by digits
|
||||
const matchLabeled = text.match(/(?:code|验证码|verification|verify)[:\s]*(\d{4,8})/i);
|
||||
if (matchLabeled) return matchLabeled[1];
|
||||
|
||||
// Pattern 3: digits followed by "code" label (Chinese: 是您的验证码)
|
||||
const matchReverse = text.match(/(\d{4,8})\s*(?:是|为|is)?\s*(?:您的)?(?:验证码|code)/i);
|
||||
if (matchReverse) return matchReverse[1];
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user