qq-mail.js 6.3 KB

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