qq-mail.js 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  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(`Step ${message.step}: Stopped by user.`, 'warn');
  27. sendResponse({ stopped: true, error: err.message });
  28. return;
  29. }
  30. reportError(message.step, err.message);
  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, usedMailIds, usedCodes } = payload;
  51. // Build sets of already-used mail IDs and codes to skip during fallback
  52. const usedMailIdSet = new Set(usedMailIds || []);
  53. const usedCodeSet = new Set(usedCodes || []);
  54. log(`Step ${step}: Starting email poll (max ${maxAttempts} attempts, every ${intervalMs / 1000}s)`);
  55. // Wait for mail list to load
  56. try {
  57. await waitForElement('.mail-list-page-item', 10000);
  58. log(`Step ${step}: Mail list loaded`);
  59. } catch {
  60. throw new Error('Mail list did not load. Make sure QQ Mail inbox is open.');
  61. }
  62. // Step 1: Snapshot existing mail IDs BEFORE we start waiting for new email
  63. const existingMailIds = getCurrentMailIds();
  64. log(`Step ${step}: Snapshotted ${existingMailIds.size} existing emails as "old"`);
  65. // Fallback after just 3 attempts (~10s). In practice, the email is usually
  66. // already in the list but has the same mailid (page was already open).
  67. const FALLBACK_AFTER = 3;
  68. for (let attempt = 1; attempt <= maxAttempts; attempt++) {
  69. log(`Polling QQ Mail... attempt ${attempt}/${maxAttempts}`);
  70. // Refresh inbox (skip on first attempt, list is fresh)
  71. if (attempt > 1) {
  72. await refreshInbox();
  73. await sleep(800);
  74. }
  75. const allItems = document.querySelectorAll('.mail-list-page-item[data-mailid]');
  76. const useFallback = attempt > FALLBACK_AFTER;
  77. // Phase 1 (attempt 1~3): only look at NEW emails (not in snapshot)
  78. // Phase 2 (attempt 4+): fallback to first matching email in list (but skip used ones)
  79. for (const item of allItems) {
  80. const mailId = item.getAttribute('data-mailid');
  81. if (!useFallback && existingMailIds.has(mailId)) continue;
  82. // Skip mail IDs that have already been used in previous runs
  83. if (usedMailIdSet.has(mailId)) continue;
  84. const sender = (item.querySelector('.cmp-account-nick')?.textContent || '').toLowerCase();
  85. const subject = (item.querySelector('.mail-subject')?.textContent || '').toLowerCase();
  86. const digest = item.querySelector('.mail-digest')?.textContent || '';
  87. const senderMatch = senderFilters.some(f => sender.includes(f.toLowerCase()));
  88. const subjectMatch = subjectFilters.some(f => subject.includes(f.toLowerCase()));
  89. if (senderMatch || subjectMatch) {
  90. const code = extractVerificationCode(subject + ' ' + digest);
  91. if (code) {
  92. // Skip codes that have already been used
  93. if (usedCodeSet.has(code)) {
  94. log(`Step ${step}: Skipping already-used code ${code} (mailId: ${mailId})`);
  95. continue;
  96. }
  97. const source = useFallback && existingMailIds.has(mailId) ? 'fallback-first-match' : 'new';
  98. log(`Step ${step}: Code found: ${code} (${source}, subject: ${subject.slice(0, 40)})`, 'ok');
  99. return { ok: true, code, emailTimestamp: Date.now(), mailId };
  100. }
  101. }
  102. }
  103. if (attempt === FALLBACK_AFTER + 1) {
  104. log(`Step ${step}: No new emails after ${FALLBACK_AFTER} attempts, falling back to first matching email`, 'warn');
  105. }
  106. if (attempt < maxAttempts) {
  107. await sleep(intervalMs);
  108. }
  109. }
  110. throw new Error(
  111. `No new matching email found after ${(maxAttempts * intervalMs / 1000).toFixed(0)}s. ` +
  112. 'Check QQ Mail manually. Email may be delayed or in spam folder.'
  113. );
  114. }
  115. // ============================================================
  116. // Inbox Refresh
  117. // ============================================================
  118. async function refreshInbox() {
  119. // Try multiple strategies to refresh the mail list
  120. // Strategy 1: Click any visible refresh button
  121. const refreshBtn = document.querySelector('[class*="refresh"], [title*="刷新"]');
  122. if (refreshBtn) {
  123. simulateClick(refreshBtn);
  124. console.log(QQ_MAIL_PREFIX, 'Clicked refresh button');
  125. await sleep(500);
  126. return;
  127. }
  128. // Strategy 2: Click inbox in sidebar to reload list
  129. const sidebarInbox = document.querySelector('a[href*="inbox"], [class*="folder-item"][class*="inbox"], [title="收件箱"]');
  130. if (sidebarInbox) {
  131. simulateClick(sidebarInbox);
  132. console.log(QQ_MAIL_PREFIX, 'Clicked sidebar inbox');
  133. await sleep(500);
  134. return;
  135. }
  136. // Strategy 3: Click the folder name in toolbar
  137. const folderName = document.querySelector('.toolbar-folder-name');
  138. if (folderName) {
  139. simulateClick(folderName);
  140. console.log(QQ_MAIL_PREFIX, 'Clicked toolbar folder name');
  141. await sleep(500);
  142. }
  143. }
  144. // ============================================================
  145. // Verification Code Extraction
  146. // ============================================================
  147. function extractVerificationCode(text) {
  148. // Pattern 1: Chinese format "代码为 370794" or "验证码...370794"
  149. const matchCn = text.match(/(?:代码为|验证码[^0-9]*?)[\s::]*(\d{6})/);
  150. if (matchCn) return matchCn[1];
  151. // Pattern 2: English format "code is 370794" or "code: 370794"
  152. const matchEn = text.match(/code[:\s]+is[:\s]+(\d{6})|code[:\s]+(\d{6})/i);
  153. if (matchEn) return matchEn[1] || matchEn[2];
  154. // Pattern 3: standalone 6-digit number (first occurrence)
  155. const match6 = text.match(/\b(\d{6})\b/);
  156. if (match6) return match6[1];
  157. return null;
  158. }