mail-163.js 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  1. // content/mail-163.js — Content script for 163 Mail (steps 4, 7)
  2. // Injected on: mail.163.com
  3. //
  4. // Actual 163 Mail DOM structure:
  5. // <div class="rF0" sign="letter" id="...Dom" aria-label="你的 ChatGPT 代码为 479637 发件人 : OpenAI ...">
  6. // <div class="dP0" sign="start-from">
  7. // <span class="nui-user">OpenAI</span>
  8. // </div>
  9. // <div class="il0">
  10. // <span class="da0">你的 ChatGPT 代码为 479637</span>
  11. // </div>
  12. // </div>
  13. const MAIL163_PREFIX = '[MultiPage:mail-163]';
  14. const isTopFrame = window === window.top;
  15. console.log(MAIL163_PREFIX, 'Content script loaded on', location.href, 'frame:', isTopFrame ? 'top' : 'child');
  16. // ============================================================
  17. // Message Handler
  18. // ============================================================
  19. chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  20. if (message.type === 'POLL_EMAIL') {
  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;
  28. }
  29. });
  30. // ============================================================
  31. // Get all current mail IDs
  32. // ============================================================
  33. function getCurrentMailIds() {
  34. const ids = new Set();
  35. // 163 mail items have sign="letter" and id ending with "Dom"
  36. const items = findMailItems();
  37. for (const item of items) {
  38. const id = item.getAttribute('id') || '';
  39. if (id) ids.add(id);
  40. }
  41. return ids;
  42. }
  43. function findMailItems() {
  44. // Try current document first
  45. let items = document.querySelectorAll('div[sign="letter"]');
  46. if (items.length > 0) return items;
  47. // Try iframes (163 mail may use iframes)
  48. const iframes = document.querySelectorAll('iframe');
  49. for (const iframe of iframes) {
  50. try {
  51. const doc = iframe.contentDocument || iframe.contentWindow?.document;
  52. if (doc) {
  53. items = doc.querySelectorAll('div[sign="letter"]');
  54. if (items.length > 0) return items;
  55. }
  56. } catch { }
  57. }
  58. return [];
  59. }
  60. // ============================================================
  61. // Email Polling
  62. // ============================================================
  63. async function handlePollEmail(step, payload) {
  64. const { senderFilters, subjectFilters, maxAttempts, intervalMs } = payload;
  65. log(`Step ${step}: Starting email poll on 163 Mail (max ${maxAttempts} attempts)`);
  66. // Wait for mail list to load
  67. await sleep(3000);
  68. let items = findMailItems();
  69. if (items.length === 0) {
  70. log(`Step ${step}: Waiting for mail list to appear...`);
  71. await sleep(5000);
  72. items = findMailItems();
  73. }
  74. if (items.length === 0) {
  75. throw new Error('163 Mail list did not load. Make sure inbox is open.');
  76. }
  77. log(`Step ${step}: Mail list loaded, ${items.length} items found`);
  78. const existingMailIds = getCurrentMailIds();
  79. log(`Step ${step}: Snapshotted ${existingMailIds.size} existing emails`);
  80. const FALLBACK_AFTER = 3;
  81. for (let attempt = 1; attempt <= maxAttempts; attempt++) {
  82. log(`Polling 163 Mail... attempt ${attempt}/${maxAttempts}`);
  83. if (attempt > 1) {
  84. await refreshInbox();
  85. await sleep(1000);
  86. }
  87. const allItems = findMailItems();
  88. const useFallback = attempt > FALLBACK_AFTER;
  89. for (const item of allItems) {
  90. const id = item.getAttribute('id') || '';
  91. if (!useFallback && existingMailIds.has(id)) continue;
  92. // Get sender from .nui-user
  93. const senderEl = item.querySelector('.nui-user');
  94. const sender = senderEl ? senderEl.textContent.toLowerCase() : '';
  95. // Get subject from span.da0
  96. const subjectEl = item.querySelector('span.da0');
  97. const subject = subjectEl ? subjectEl.textContent : '';
  98. // Also check aria-label which contains full info
  99. const ariaLabel = (item.getAttribute('aria-label') || '').toLowerCase();
  100. const senderMatch = senderFilters.some(f => sender.includes(f.toLowerCase()) || ariaLabel.includes(f.toLowerCase()));
  101. const subjectMatch = subjectFilters.some(f => subject.toLowerCase().includes(f.toLowerCase()) || ariaLabel.includes(f.toLowerCase()));
  102. if (senderMatch || subjectMatch) {
  103. const code = extractVerificationCode(subject + ' ' + ariaLabel);
  104. if (code) {
  105. const source = useFallback && existingMailIds.has(id) ? 'fallback' : 'new';
  106. log(`Step ${step}: Code found: ${code} (${source}, subject: ${subject.slice(0, 40)})`, 'ok');
  107. return { ok: true, code, emailTimestamp: Date.now(), mailId: id };
  108. }
  109. }
  110. }
  111. if (attempt === FALLBACK_AFTER + 1) {
  112. log(`Step ${step}: No new emails after ${FALLBACK_AFTER} attempts, falling back to first match`, 'warn');
  113. }
  114. if (attempt < maxAttempts) {
  115. await sleep(intervalMs);
  116. }
  117. }
  118. throw new Error(
  119. `No matching email found on 163 Mail after ${(maxAttempts * intervalMs / 1000).toFixed(0)}s. ` +
  120. 'Check inbox manually.'
  121. );
  122. }
  123. // ============================================================
  124. // Inbox Refresh
  125. // ============================================================
  126. async function refreshInbox() {
  127. // 163 mail: click the "收信" button in toolbar
  128. function tryRefresh(doc) {
  129. const btn = doc.querySelector(
  130. 'a[title="收信"], [id*="refresh"], .nui-toolbar-item[title*="收"]'
  131. );
  132. if (btn) {
  133. btn.click();
  134. console.log(MAIL163_PREFIX, 'Clicked 收信 button');
  135. return true;
  136. }
  137. return false;
  138. }
  139. if (tryRefresh(document)) { await sleep(500); return; }
  140. // Try in iframes
  141. const iframes = document.querySelectorAll('iframe');
  142. for (const iframe of iframes) {
  143. try {
  144. const doc = iframe.contentDocument || iframe.contentWindow?.document;
  145. if (doc && tryRefresh(doc)) { await sleep(500); return; }
  146. } catch { }
  147. }
  148. console.log(MAIL163_PREFIX, 'Could not find refresh button');
  149. }
  150. // ============================================================
  151. // Verification Code Extraction
  152. // ============================================================
  153. function extractVerificationCode(text) {
  154. const matchCn = text.match(/(?:代码为|验证码[^0-9]*?)[\s::]*(\d{6})/);
  155. if (matchCn) return matchCn[1];
  156. const matchEn = text.match(/code[:\s]+is[:\s]+(\d{6})|code[:\s]+(\d{6})/i);
  157. if (matchEn) return matchEn[1] || matchEn[2];
  158. const match6 = text.match(/\b(\d{6})\b/);
  159. if (match6) return match6[1];
  160. return null;
  161. }