mail-163.js 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  1. // content/mail-163.js — Content script for 163 Mail (steps 4, 7)
  2. // Injected on: mail.163.com
  3. //
  4. // DOM structure:
  5. // Mail item: div[sign="letter"] with aria-label="你的 ChatGPT 代码为 479637 发件人 : OpenAI ..."
  6. // Sender: .nui-user (e.g., "OpenAI")
  7. // Subject: span.da0 (e.g., "你的 ChatGPT 代码为 479637")
  8. // Right-click menu: .nui-menu → .nui-menu-item with text "删除邮件"
  9. const MAIL163_PREFIX = '[MultiPage:mail-163]';
  10. const isTopFrame = window === window.top;
  11. console.log(MAIL163_PREFIX, 'Content script loaded on', location.href, 'frame:', isTopFrame ? 'top' : 'child');
  12. // Only operate in the top frame
  13. if (!isTopFrame) {
  14. console.log(MAIL163_PREFIX, 'Skipping child frame');
  15. } else {
  16. // Track codes we've already seen across polls to avoid duplicates
  17. const seenCodes = new Set();
  18. // ============================================================
  19. // Message Handler (top frame only)
  20. // ============================================================
  21. chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  22. if (message.type === 'POLL_EMAIL') {
  23. handlePollEmail(message.step, message.payload).then(result => {
  24. sendResponse(result);
  25. }).catch(err => {
  26. reportError(message.step, err.message);
  27. sendResponse({ error: err.message });
  28. });
  29. return true;
  30. }
  31. });
  32. // ============================================================
  33. // Find mail items
  34. // ============================================================
  35. function findMailItems() {
  36. return document.querySelectorAll('div[sign="letter"]');
  37. }
  38. function getCurrentMailIds() {
  39. const ids = new Set();
  40. findMailItems().forEach(item => {
  41. const id = item.getAttribute('id') || '';
  42. if (id) ids.add(id);
  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 on 163 Mail (max ${maxAttempts} attempts)`);
  52. // Click inbox in sidebar to ensure we're in inbox view
  53. log(`Step ${step}: Waiting for sidebar...`);
  54. try {
  55. const inboxLink = await waitForElement('.nui-tree-item-text[title="收件箱"]', 5000);
  56. inboxLink.click();
  57. log(`Step ${step}: Clicked inbox`);
  58. } catch {
  59. log(`Step ${step}: Inbox link not found, proceeding...`, 'warn');
  60. }
  61. // Wait for mail list to appear
  62. log(`Step ${step}: Waiting for mail list...`);
  63. let items = [];
  64. for (let i = 0; i < 20; i++) {
  65. items = findMailItems();
  66. if (items.length > 0) break;
  67. await sleep(500);
  68. }
  69. if (items.length === 0) {
  70. await refreshInbox();
  71. await sleep(2000);
  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`);
  78. // Snapshot existing mail IDs
  79. const existingMailIds = getCurrentMailIds();
  80. log(`Step ${step}: Snapshotted ${existingMailIds.size} existing emails`);
  81. const FALLBACK_AFTER = 3;
  82. for (let attempt = 1; attempt <= maxAttempts; attempt++) {
  83. log(`Polling 163 Mail... attempt ${attempt}/${maxAttempts}`);
  84. if (attempt > 1) {
  85. await refreshInbox();
  86. await sleep(1000);
  87. }
  88. const allItems = findMailItems();
  89. const useFallback = attempt > FALLBACK_AFTER;
  90. for (const item of allItems) {
  91. const id = item.getAttribute('id') || '';
  92. if (!useFallback && existingMailIds.has(id)) continue;
  93. const senderEl = item.querySelector('.nui-user');
  94. const sender = senderEl ? senderEl.textContent.toLowerCase() : '';
  95. const subjectEl = item.querySelector('span.da0');
  96. const subject = subjectEl ? subjectEl.textContent : '';
  97. const ariaLabel = (item.getAttribute('aria-label') || '').toLowerCase();
  98. const senderMatch = senderFilters.some(f => sender.includes(f.toLowerCase()) || ariaLabel.includes(f.toLowerCase()));
  99. const subjectMatch = subjectFilters.some(f => subject.toLowerCase().includes(f.toLowerCase()) || ariaLabel.includes(f.toLowerCase()));
  100. if (senderMatch || subjectMatch) {
  101. const code = extractVerificationCode(subject + ' ' + ariaLabel);
  102. if (code && !seenCodes.has(code)) {
  103. seenCodes.add(code);
  104. const source = useFallback && existingMailIds.has(id) ? 'fallback' : 'new';
  105. log(`Step ${step}: Code found: ${code} (${source}, subject: ${subject.slice(0, 40)})`, 'ok');
  106. // Delete this email via right-click menu
  107. await deleteEmail(item, step);
  108. return { ok: true, code, emailTimestamp: Date.now(), mailId: id };
  109. } else if (code && seenCodes.has(code)) {
  110. log(`Step ${step}: Skipping already-seen code: ${code}`, 'info');
  111. }
  112. }
  113. }
  114. if (attempt === FALLBACK_AFTER + 1) {
  115. log(`Step ${step}: No new emails after ${FALLBACK_AFTER} attempts, falling back to first match`, 'warn');
  116. }
  117. if (attempt < maxAttempts) {
  118. await sleep(intervalMs);
  119. }
  120. }
  121. throw new Error(
  122. `No new matching email found on 163 Mail after ${(maxAttempts * intervalMs / 1000).toFixed(0)}s. ` +
  123. 'Check inbox manually.'
  124. );
  125. }
  126. // ============================================================
  127. // Delete Email via Right-Click Menu
  128. // ============================================================
  129. async function deleteEmail(item, step) {
  130. try {
  131. log(`Step ${step}: Deleting email...`);
  132. // Right-click on the mail item to trigger context menu
  133. item.dispatchEvent(new MouseEvent('contextmenu', {
  134. bubbles: true, cancelable: true, button: 2,
  135. clientX: item.getBoundingClientRect().x + 100,
  136. clientY: item.getBoundingClientRect().y + 10,
  137. }));
  138. await sleep(500);
  139. // Find the context menu and click "删除邮件"
  140. const menuItems = document.querySelectorAll('.nui-menu-item .nui-menu-item-text');
  141. for (const menuItem of menuItems) {
  142. if (menuItem.textContent.trim() === '删除邮件') {
  143. menuItem.closest('.nui-menu-item').click();
  144. log(`Step ${step}: Email deleted`, 'ok');
  145. await sleep(500);
  146. return;
  147. }
  148. }
  149. log(`Step ${step}: Could not find "删除邮件" in context menu`, 'warn');
  150. } catch (err) {
  151. log(`Step ${step}: Failed to delete email: ${err.message}`, 'warn');
  152. }
  153. }
  154. // ============================================================
  155. // Inbox Refresh
  156. // ============================================================
  157. async function refreshInbox() {
  158. // Try toolbar "刷 新" button
  159. const toolbarBtns = document.querySelectorAll('.nui-btn .nui-btn-text');
  160. for (const btn of toolbarBtns) {
  161. if (btn.textContent.replace(/\s/g, '') === '刷新') {
  162. btn.closest('.nui-btn').click();
  163. console.log(MAIL163_PREFIX, 'Clicked "刷新" button');
  164. await sleep(800);
  165. return;
  166. }
  167. }
  168. // Fallback: click sidebar "收 信"
  169. const shouXinBtns = document.querySelectorAll('.ra0');
  170. for (const btn of shouXinBtns) {
  171. if (btn.textContent.replace(/\s/g, '').includes('收信')) {
  172. btn.click();
  173. console.log(MAIL163_PREFIX, 'Clicked "收信" button');
  174. await sleep(800);
  175. return;
  176. }
  177. }
  178. console.log(MAIL163_PREFIX, 'Could not find refresh button');
  179. }
  180. // ============================================================
  181. // Verification Code Extraction
  182. // ============================================================
  183. function extractVerificationCode(text) {
  184. const matchCn = text.match(/(?:代码为|验证码[^0-9]*?)[\s::]*(\d{6})/);
  185. if (matchCn) return matchCn[1];
  186. const matchEn = text.match(/code[:\s]+is[:\s]+(\d{6})|code[:\s]+(\d{6})/i);
  187. if (matchEn) return matchEn[1] || matchEn[2];
  188. const match6 = text.match(/\b(\d{6})\b/);
  189. if (match6) return match6[1];
  190. return null;
  191. }
  192. } // end of isTopFrame else block