qq-mail.js 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  1. // content/qq-mail.js — Content script for QQ Mail (steps 4, 7)
  2. // Injected on: mail.qq.com, wx.mail.qq.com
  3. // NOTE: all_frames: true
  4. //
  5. // Strategy for avoiding stale codes:
  6. // 1. On poll start, snapshot all existing mail IDs as "old"
  7. // 2. On each poll cycle, refresh inbox and look for NEW items (not in snapshot)
  8. // 3. Only extract codes from NEW items that match sender/subject filters
  9. const QQ_MAIL_PREFIX = '[MultiPage:qq-mail]';
  10. const isTopFrame = window === window.top;
  11. console.log(QQ_MAIL_PREFIX, 'Content script loaded on', location.href, 'frame:', isTopFrame ? 'top' : 'child');
  12. // ============================================================
  13. // Message Handler
  14. // ============================================================
  15. chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  16. if (message.type === 'POLL_EMAIL') {
  17. if (!isTopFrame) {
  18. sendResponse({ ok: false, reason: 'wrong-frame' });
  19. return;
  20. }
  21. resetStopState();
  22. handlePollEmail(message.step, message.payload).then(result => {
  23. sendResponse(result);
  24. }).catch(err => {
  25. if (isStopError(err)) {
  26. log(`步骤 ${message.step}:已被用户停止。`, 'warn');
  27. sendResponse({ stopped: true, error: err.message });
  28. return;
  29. }
  30. log(`步骤 ${message.step}:邮箱轮询失败:${err.message}`, 'warn');
  31. sendResponse({ error: err.message });
  32. });
  33. return true; // async response
  34. }
  35. });
  36. // ============================================================
  37. // Get all current mail IDs from the list
  38. // ============================================================
  39. function getCurrentMailIds() {
  40. const ids = new Set();
  41. document.querySelectorAll('.mail-list-page-item[data-mailid]').forEach(item => {
  42. ids.add(item.getAttribute('data-mailid'));
  43. });
  44. return ids;
  45. }
  46. // ============================================================
  47. // Email Polling
  48. // ============================================================
  49. async function handlePollEmail(step, payload) {
  50. const { senderFilters, subjectFilters, maxAttempts, intervalMs, excludeCodes = [] } = payload;
  51. const excludedCodeSet = new Set(excludeCodes.filter(Boolean));
  52. log(`步骤 ${step}:开始轮询邮箱(最多 ${maxAttempts} 次,每 ${intervalMs / 1000} 秒一次)`);
  53. // Wait for mail list to load
  54. try {
  55. await waitForElement('.mail-list-page-item', 10000);
  56. log(`步骤 ${step}:邮件列表已加载`);
  57. } catch {
  58. throw new Error('邮件列表未加载完成,请确认 QQ 邮箱已打开收件箱。');
  59. }
  60. // Step 1: Snapshot existing mail IDs BEFORE we start waiting for new email
  61. const existingMailIds = getCurrentMailIds();
  62. log(`步骤 ${step}:已将当前 ${existingMailIds.size} 封邮件标记为旧邮件快照`);
  63. // Fallback after just 3 attempts (~10s). In practice, the email is usually
  64. // already in the list but has the same mailid (page was already open).
  65. const FALLBACK_AFTER = 3;
  66. for (let attempt = 1; attempt <= maxAttempts; attempt++) {
  67. log(`步骤 ${step}:正在轮询 QQ 邮箱,第 ${attempt}/${maxAttempts} 次`);
  68. // Refresh inbox (skip on first attempt, list is fresh)
  69. if (attempt > 1) {
  70. await refreshInbox();
  71. await sleep(800);
  72. }
  73. const allItems = document.querySelectorAll('.mail-list-page-item[data-mailid]');
  74. const useFallback = attempt > FALLBACK_AFTER;
  75. // Phase 1 (attempt 1~3): only look at NEW emails (not in snapshot)
  76. // Phase 2 (attempt 4+): fallback to first matching email in list
  77. for (const item of allItems) {
  78. const mailId = item.getAttribute('data-mailid');
  79. if (!useFallback && existingMailIds.has(mailId)) continue;
  80. const sender = (item.querySelector('.cmp-account-nick')?.textContent || '').toLowerCase();
  81. const subject = (item.querySelector('.mail-subject')?.textContent || '').toLowerCase();
  82. const digest = item.querySelector('.mail-digest')?.textContent || '';
  83. const senderMatch = senderFilters.some(f => sender.includes(f.toLowerCase()));
  84. const subjectMatch = subjectFilters.some(f => subject.includes(f.toLowerCase()));
  85. if (senderMatch || subjectMatch) {
  86. const code = extractVerificationCode(subject + ' ' + digest);
  87. if (code) {
  88. if (excludedCodeSet.has(code)) {
  89. log(`步骤 ${step}:跳过排除的验证码:${code}`, 'info');
  90. continue;
  91. }
  92. const source = useFallback && existingMailIds.has(mailId) ? '回退首封匹配邮件' : '新邮件';
  93. log(`步骤 ${step}:已找到验证码:${code}(来源:${source},主题:${subject.slice(0, 40)})`, 'ok');
  94. return { ok: true, code, emailTimestamp: Date.now(), mailId };
  95. }
  96. }
  97. }
  98. if (attempt === FALLBACK_AFTER + 1) {
  99. log(`步骤 ${step}:连续 ${FALLBACK_AFTER} 次未发现新邮件,开始回退到首封匹配邮件`, 'warn');
  100. }
  101. if (attempt < maxAttempts) {
  102. await sleep(intervalMs);
  103. }
  104. }
  105. throw new Error(
  106. `${(maxAttempts * intervalMs / 1000).toFixed(0)} 秒后仍未找到新的匹配邮件。` +
  107. '请手动检查 QQ 邮箱,邮件可能延迟到达或进入垃圾箱。'
  108. );
  109. }
  110. // ============================================================
  111. // Inbox Refresh
  112. // ============================================================
  113. async function refreshInbox() {
  114. // Try multiple strategies to refresh the mail list
  115. // Strategy 1: Click any visible refresh button
  116. const refreshBtn = document.querySelector('[class*="refresh"], [title*="刷新"]');
  117. if (refreshBtn) {
  118. simulateClick(refreshBtn);
  119. console.log(QQ_MAIL_PREFIX, 'Clicked refresh button');
  120. await sleep(500);
  121. return;
  122. }
  123. // Strategy 2: Click inbox in sidebar to reload list
  124. const sidebarInbox = document.querySelector('a[href*="inbox"], [class*="folder-item"][class*="inbox"], [title="收件箱"]');
  125. if (sidebarInbox) {
  126. simulateClick(sidebarInbox);
  127. console.log(QQ_MAIL_PREFIX, 'Clicked sidebar inbox');
  128. await sleep(500);
  129. return;
  130. }
  131. // Strategy 3: Click the folder name in toolbar
  132. const folderName = document.querySelector('.toolbar-folder-name');
  133. if (folderName) {
  134. simulateClick(folderName);
  135. console.log(QQ_MAIL_PREFIX, 'Clicked toolbar folder name');
  136. await sleep(500);
  137. }
  138. }
  139. // ============================================================
  140. // Verification Code Extraction
  141. // ============================================================
  142. function extractVerificationCode(text) {
  143. // Pattern 1: Chinese format "代码为 370794" or "验证码...370794"
  144. const matchCn = text.match(/(?:代码为|验证码[^0-9]*?)[\s::]*(\d{6})/);
  145. if (matchCn) return matchCn[1];
  146. // Pattern 2: English format "code is 370794" or "code: 370794"
  147. const matchEn = text.match(/code[:\s]+is[:\s]+(\d{6})|code[:\s]+(\d{6})/i);
  148. if (matchEn) return matchEn[1] || matchEn[2];
  149. // Pattern 3: standalone 6-digit number (first occurrence)
  150. const match6 = text.match(/\b(\d{6})\b/);
  151. if (match6) return match6[1];
  152. return null;
  153. }