mail-163.js 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  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. // Only operate in the top frame — child iframes don't have the inbox
  17. if (!isTopFrame) {
  18. console.log(MAIL163_PREFIX, 'Skipping child frame');
  19. // Don't report ready or handle messages from child frames
  20. } else {
  21. // ============================================================
  22. // Message Handler (top frame only)
  23. // ============================================================
  24. chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  25. if (message.type === 'POLL_EMAIL') {
  26. handlePollEmail(message.step, message.payload).then(result => {
  27. sendResponse(result);
  28. }).catch(err => {
  29. reportError(message.step, err.message);
  30. sendResponse({ error: err.message });
  31. });
  32. return true;
  33. }
  34. });
  35. // ============================================================
  36. // Get all current mail IDs
  37. // ============================================================
  38. function getCurrentMailIds() {
  39. const ids = new Set();
  40. // 163 mail items have sign="letter" and id ending with "Dom"
  41. const items = findMailItems();
  42. for (const item of items) {
  43. const id = item.getAttribute('id') || '';
  44. if (id) ids.add(id);
  45. }
  46. return ids;
  47. }
  48. function findMailItems() {
  49. // Try current document first
  50. let items = document.querySelectorAll('div[sign="letter"]');
  51. if (items.length > 0) return items;
  52. // Try iframes (163 mail may use iframes)
  53. const iframes = document.querySelectorAll('iframe');
  54. for (const iframe of iframes) {
  55. try {
  56. const doc = iframe.contentDocument || iframe.contentWindow?.document;
  57. if (doc) {
  58. items = doc.querySelectorAll('div[sign="letter"]');
  59. if (items.length > 0) return items;
  60. }
  61. } catch { }
  62. }
  63. return [];
  64. }
  65. // ============================================================
  66. // Email Polling
  67. // ============================================================
  68. async function handlePollEmail(step, payload) {
  69. const { senderFilters, subjectFilters, maxAttempts, intervalMs } = payload;
  70. log(`Step ${step}: Starting email poll on 163 Mail (max ${maxAttempts} attempts)`);
  71. // Wait for sidebar to load, then click "收件箱"
  72. log(`Step ${step}: Waiting for 163 Mail sidebar to load...`);
  73. try {
  74. const inboxLink = await waitForElement('.nui-tree-item-text[title="收件箱"]', 5000);
  75. inboxLink.click();
  76. log(`Step ${step}: Clicked inbox in sidebar`);
  77. } catch {
  78. log(`Step ${step}: Could not find inbox link, trying to proceed anyway...`, 'warn');
  79. }
  80. // Wait for mail list — poll every 500ms, max 10s
  81. log(`Step ${step}: Waiting for mail list...`);
  82. let items = [];
  83. for (let i = 0; i < 20; i++) {
  84. items = findMailItems();
  85. if (items.length > 0) break;
  86. await sleep(500);
  87. }
  88. if (items.length === 0) {
  89. log(`Step ${step}: Mail list not found, trying refresh...`, 'warn');
  90. await refreshInbox();
  91. await sleep(2000);
  92. items = findMailItems();
  93. }
  94. if (items.length === 0) {
  95. throw new Error('163 Mail list did not load. Make sure inbox is open and has emails.');
  96. }
  97. log(`Step ${step}: Mail list loaded, ${items.length} items found`);
  98. const existingMailIds = getCurrentMailIds();
  99. log(`Step ${step}: Snapshotted ${existingMailIds.size} existing emails`);
  100. const FALLBACK_AFTER = 3;
  101. for (let attempt = 1; attempt <= maxAttempts; attempt++) {
  102. log(`Polling 163 Mail... attempt ${attempt}/${maxAttempts}`);
  103. if (attempt > 1) {
  104. await refreshInbox();
  105. await sleep(1000);
  106. }
  107. const allItems = findMailItems();
  108. const useFallback = attempt > FALLBACK_AFTER;
  109. for (const item of allItems) {
  110. const id = item.getAttribute('id') || '';
  111. if (!useFallback && existingMailIds.has(id)) continue;
  112. // Get sender from .nui-user
  113. const senderEl = item.querySelector('.nui-user');
  114. const sender = senderEl ? senderEl.textContent.toLowerCase() : '';
  115. // Get subject from span.da0
  116. const subjectEl = item.querySelector('span.da0');
  117. const subject = subjectEl ? subjectEl.textContent : '';
  118. // Also check aria-label which contains full info
  119. const ariaLabel = (item.getAttribute('aria-label') || '').toLowerCase();
  120. const senderMatch = senderFilters.some(f => sender.includes(f.toLowerCase()) || ariaLabel.includes(f.toLowerCase()));
  121. const subjectMatch = subjectFilters.some(f => subject.toLowerCase().includes(f.toLowerCase()) || ariaLabel.includes(f.toLowerCase()));
  122. if (senderMatch || subjectMatch) {
  123. const code = extractVerificationCode(subject + ' ' + ariaLabel);
  124. if (code) {
  125. const source = useFallback && existingMailIds.has(id) ? 'fallback' : 'new';
  126. log(`Step ${step}: Code found: ${code} (${source}, subject: ${subject.slice(0, 40)})`, 'ok');
  127. return { ok: true, code, emailTimestamp: Date.now(), mailId: id };
  128. }
  129. }
  130. }
  131. if (attempt === FALLBACK_AFTER + 1) {
  132. log(`Step ${step}: No new emails after ${FALLBACK_AFTER} attempts, falling back to first match`, 'warn');
  133. }
  134. if (attempt < maxAttempts) {
  135. await sleep(intervalMs);
  136. }
  137. }
  138. throw new Error(
  139. `No matching email found on 163 Mail after ${(maxAttempts * intervalMs / 1000).toFixed(0)}s. ` +
  140. 'Check inbox manually.'
  141. );
  142. }
  143. // ============================================================
  144. // Inbox Refresh
  145. // ============================================================
  146. async function refreshInbox() {
  147. // 163 mail: try the toolbar "刷 新" button first
  148. // Actual DOM: <div class="js-component-button nui-btn"><span class="nui-btn-text">刷 新</span></div>
  149. const toolbarBtns = document.querySelectorAll('.nui-btn .nui-btn-text');
  150. for (const btn of toolbarBtns) {
  151. if (btn.textContent.replace(/\s/g, '') === '刷新') {
  152. btn.closest('.nui-btn').click();
  153. console.log(MAIL163_PREFIX, 'Clicked toolbar "刷新" button');
  154. await sleep(800);
  155. return;
  156. }
  157. }
  158. // Fallback: click the left sidebar "收 信" button
  159. // Actual DOM: <li class="ra0 nb0"><span class="oz0">收 信</span></li>
  160. const shouXinBtns = document.querySelectorAll('.ra0');
  161. for (const btn of shouXinBtns) {
  162. if (btn.textContent.replace(/\s/g, '').includes('收信')) {
  163. btn.click();
  164. console.log(MAIL163_PREFIX, 'Clicked sidebar "收信" button');
  165. await sleep(800);
  166. return;
  167. }
  168. }
  169. console.log(MAIL163_PREFIX, 'Could not find refresh button');
  170. }
  171. // ============================================================
  172. // Verification Code Extraction
  173. // ============================================================
  174. function extractVerificationCode(text) {
  175. const matchCn = text.match(/(?:代码为|验证码[^0-9]*?)[\s::]*(\d{6})/);
  176. if (matchCn) return matchCn[1];
  177. const matchEn = text.match(/code[:\s]+is[:\s]+(\d{6})|code[:\s]+(\d{6})/i);
  178. if (matchEn) return matchEn[1] || matchEn[2];
  179. const match6 = text.match(/\b(\d{6})\b/);
  180. if (match6) return match6[1];
  181. return null;
  182. }
  183. } // end of isTopFrame else block