qq-mail.js 6.5 KB

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