mail-163.js 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  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. // First, click on "收件箱" in left sidebar to ensure we're in inbox view
  67. await sleep(2000);
  68. const inboxLink = document.querySelector('.nui-tree-item-text[title="收件箱"]');
  69. if (inboxLink) {
  70. inboxLink.click();
  71. log(`Step ${step}: Clicked inbox in sidebar`);
  72. await sleep(2000);
  73. }
  74. // Wait for mail list to load
  75. let items = findMailItems();
  76. if (items.length === 0) {
  77. log(`Step ${step}: Waiting for mail list to appear...`);
  78. await sleep(5000);
  79. items = findMailItems();
  80. }
  81. if (items.length === 0) {
  82. throw new Error('163 Mail list did not load. Make sure inbox is open.');
  83. }
  84. log(`Step ${step}: Mail list loaded, ${items.length} items found`);
  85. const existingMailIds = getCurrentMailIds();
  86. log(`Step ${step}: Snapshotted ${existingMailIds.size} existing emails`);
  87. const FALLBACK_AFTER = 3;
  88. for (let attempt = 1; attempt <= maxAttempts; attempt++) {
  89. log(`Polling 163 Mail... attempt ${attempt}/${maxAttempts}`);
  90. if (attempt > 1) {
  91. await refreshInbox();
  92. await sleep(1000);
  93. }
  94. const allItems = findMailItems();
  95. const useFallback = attempt > FALLBACK_AFTER;
  96. for (const item of allItems) {
  97. const id = item.getAttribute('id') || '';
  98. if (!useFallback && existingMailIds.has(id)) continue;
  99. // Get sender from .nui-user
  100. const senderEl = item.querySelector('.nui-user');
  101. const sender = senderEl ? senderEl.textContent.toLowerCase() : '';
  102. // Get subject from span.da0
  103. const subjectEl = item.querySelector('span.da0');
  104. const subject = subjectEl ? subjectEl.textContent : '';
  105. // Also check aria-label which contains full info
  106. const ariaLabel = (item.getAttribute('aria-label') || '').toLowerCase();
  107. const senderMatch = senderFilters.some(f => sender.includes(f.toLowerCase()) || ariaLabel.includes(f.toLowerCase()));
  108. const subjectMatch = subjectFilters.some(f => subject.toLowerCase().includes(f.toLowerCase()) || ariaLabel.includes(f.toLowerCase()));
  109. if (senderMatch || subjectMatch) {
  110. const code = extractVerificationCode(subject + ' ' + ariaLabel);
  111. if (code) {
  112. const source = useFallback && existingMailIds.has(id) ? 'fallback' : 'new';
  113. log(`Step ${step}: Code found: ${code} (${source}, subject: ${subject.slice(0, 40)})`, 'ok');
  114. return { ok: true, code, emailTimestamp: Date.now(), mailId: id };
  115. }
  116. }
  117. }
  118. if (attempt === FALLBACK_AFTER + 1) {
  119. log(`Step ${step}: No new emails after ${FALLBACK_AFTER} attempts, falling back to first match`, 'warn');
  120. }
  121. if (attempt < maxAttempts) {
  122. await sleep(intervalMs);
  123. }
  124. }
  125. throw new Error(
  126. `No matching email found on 163 Mail after ${(maxAttempts * intervalMs / 1000).toFixed(0)}s. ` +
  127. 'Check inbox manually.'
  128. );
  129. }
  130. // ============================================================
  131. // Inbox Refresh
  132. // ============================================================
  133. async function refreshInbox() {
  134. // 163 mail: try the toolbar "刷 新" button first
  135. // Actual DOM: <div class="js-component-button nui-btn"><span class="nui-btn-text">刷 新</span></div>
  136. const toolbarBtns = document.querySelectorAll('.nui-btn .nui-btn-text');
  137. for (const btn of toolbarBtns) {
  138. if (btn.textContent.replace(/\s/g, '') === '刷新') {
  139. btn.closest('.nui-btn').click();
  140. console.log(MAIL163_PREFIX, 'Clicked toolbar "刷新" button');
  141. await sleep(800);
  142. return;
  143. }
  144. }
  145. // Fallback: click the left sidebar "收 信" button
  146. // Actual DOM: <li class="ra0 nb0"><span class="oz0">收 信</span></li>
  147. const shouXinBtns = document.querySelectorAll('.ra0');
  148. for (const btn of shouXinBtns) {
  149. if (btn.textContent.replace(/\s/g, '').includes('收信')) {
  150. btn.click();
  151. console.log(MAIL163_PREFIX, 'Clicked sidebar "收信" button');
  152. await sleep(800);
  153. return;
  154. }
  155. }
  156. console.log(MAIL163_PREFIX, 'Could not find refresh button');
  157. }
  158. // ============================================================
  159. // Verification Code Extraction
  160. // ============================================================
  161. function extractVerificationCode(text) {
  162. const matchCn = text.match(/(?:代码为|验证码[^0-9]*?)[\s::]*(\d{6})/);
  163. if (matchCn) return matchCn[1];
  164. const matchEn = text.match(/code[:\s]+is[:\s]+(\d{6})|code[:\s]+(\d{6})/i);
  165. if (matchEn) return matchEn[1] || matchEn[2];
  166. const match6 = text.match(/\b(\d{6})\b/);
  167. if (match6) return match6[1];
  168. return null;
  169. }