mail-163.js 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  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 — persisted in chrome.storage.session to survive script re-injection
  17. let seenCodes = new Set();
  18. // Load previously seen codes on startup
  19. (async () => {
  20. try {
  21. const data = await chrome.storage.session.get('seenCodes');
  22. if (data.seenCodes && Array.isArray(data.seenCodes)) {
  23. seenCodes = new Set(data.seenCodes);
  24. console.log(MAIL163_PREFIX, `Loaded ${seenCodes.size} previously seen codes`);
  25. }
  26. } catch {}
  27. })();
  28. async function persistSeenCodes() {
  29. await chrome.storage.session.set({ seenCodes: [...seenCodes] });
  30. }
  31. // ============================================================
  32. // Message Handler (top frame only)
  33. // ============================================================
  34. chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  35. if (message.type === 'POLL_EMAIL') {
  36. handlePollEmail(message.step, message.payload).then(result => {
  37. sendResponse(result);
  38. }).catch(err => {
  39. reportError(message.step, err.message);
  40. sendResponse({ error: err.message });
  41. });
  42. return true;
  43. }
  44. });
  45. // ============================================================
  46. // Find mail items
  47. // ============================================================
  48. function findMailItems() {
  49. return document.querySelectorAll('div[sign="letter"]');
  50. }
  51. function getCurrentMailIds() {
  52. const ids = new Set();
  53. findMailItems().forEach(item => {
  54. const id = item.getAttribute('id') || '';
  55. if (id) ids.add(id);
  56. });
  57. return ids;
  58. }
  59. // ============================================================
  60. // Email Polling
  61. // ============================================================
  62. async function handlePollEmail(step, payload) {
  63. const { senderFilters, subjectFilters, maxAttempts, intervalMs } = payload;
  64. log(`Step ${step}: Starting email poll on 163 Mail (max ${maxAttempts} attempts)`);
  65. // Click inbox in sidebar to ensure we're in inbox view
  66. log(`Step ${step}: Waiting for sidebar...`);
  67. try {
  68. const inboxLink = await waitForElement('.nui-tree-item-text[title="收件箱"]', 5000);
  69. inboxLink.click();
  70. log(`Step ${step}: Clicked inbox`);
  71. } catch {
  72. log(`Step ${step}: Inbox link not found, proceeding...`, 'warn');
  73. }
  74. // Wait for mail list to appear
  75. log(`Step ${step}: Waiting for mail list...`);
  76. let items = [];
  77. for (let i = 0; i < 20; i++) {
  78. items = findMailItems();
  79. if (items.length > 0) break;
  80. await sleep(500);
  81. }
  82. if (items.length === 0) {
  83. await refreshInbox();
  84. await sleep(2000);
  85. items = findMailItems();
  86. }
  87. if (items.length === 0) {
  88. throw new Error('163 Mail list did not load. Make sure inbox is open.');
  89. }
  90. log(`Step ${step}: Mail list loaded, ${items.length} items`);
  91. // Snapshot existing mail IDs
  92. const existingMailIds = getCurrentMailIds();
  93. log(`Step ${step}: Snapshotted ${existingMailIds.size} existing emails`);
  94. const FALLBACK_AFTER = 3;
  95. for (let attempt = 1; attempt <= maxAttempts; attempt++) {
  96. log(`Polling 163 Mail... attempt ${attempt}/${maxAttempts}`);
  97. if (attempt > 1) {
  98. await refreshInbox();
  99. await sleep(1000);
  100. }
  101. const allItems = findMailItems();
  102. const useFallback = attempt > FALLBACK_AFTER;
  103. for (const item of allItems) {
  104. const id = item.getAttribute('id') || '';
  105. if (!useFallback && existingMailIds.has(id)) continue;
  106. const senderEl = item.querySelector('.nui-user');
  107. const sender = senderEl ? senderEl.textContent.toLowerCase() : '';
  108. const subjectEl = item.querySelector('span.da0');
  109. const subject = subjectEl ? subjectEl.textContent : '';
  110. const ariaLabel = (item.getAttribute('aria-label') || '').toLowerCase();
  111. const senderMatch = senderFilters.some(f => sender.includes(f.toLowerCase()) || ariaLabel.includes(f.toLowerCase()));
  112. const subjectMatch = subjectFilters.some(f => subject.toLowerCase().includes(f.toLowerCase()) || ariaLabel.includes(f.toLowerCase()));
  113. if (senderMatch || subjectMatch) {
  114. const code = extractVerificationCode(subject + ' ' + ariaLabel);
  115. if (code && !seenCodes.has(code)) {
  116. seenCodes.add(code);
  117. persistSeenCodes();
  118. const source = useFallback && existingMailIds.has(id) ? 'fallback' : 'new';
  119. log(`Step ${step}: Code found: ${code} (${source}, subject: ${subject.slice(0, 40)})`, 'ok');
  120. // Delete this email via right-click menu, WAIT for it to finish before returning
  121. await deleteEmail(item, step);
  122. // Extra wait to ensure deletion is processed
  123. await sleep(1000);
  124. return { ok: true, code, emailTimestamp: Date.now(), mailId: id };
  125. } else if (code && seenCodes.has(code)) {
  126. log(`Step ${step}: Skipping already-seen code: ${code}`, 'info');
  127. }
  128. }
  129. }
  130. if (attempt === FALLBACK_AFTER + 1) {
  131. log(`Step ${step}: No new emails after ${FALLBACK_AFTER} attempts, falling back to first match`, 'warn');
  132. }
  133. if (attempt < maxAttempts) {
  134. await sleep(intervalMs);
  135. }
  136. }
  137. throw new Error(
  138. `No new matching email found on 163 Mail after ${(maxAttempts * intervalMs / 1000).toFixed(0)}s. ` +
  139. 'Check inbox manually.'
  140. );
  141. }
  142. // ============================================================
  143. // Delete Email via Right-Click Menu
  144. // ============================================================
  145. async function deleteEmail(item, step) {
  146. try {
  147. log(`Step ${step}: Deleting email...`);
  148. // Right-click on the mail item to trigger context menu
  149. const rect = item.getBoundingClientRect();
  150. item.dispatchEvent(new MouseEvent('contextmenu', {
  151. bubbles: true, cancelable: true, button: 2,
  152. clientX: rect.left + rect.width / 2,
  153. clientY: rect.top + rect.height / 2,
  154. }));
  155. // Wait for context menu to appear
  156. let deleteMenuItem = null;
  157. for (let i = 0; i < 10; i++) {
  158. await sleep(300);
  159. const menuItems = document.querySelectorAll('.nui-menu-item .nui-menu-item-text');
  160. for (const mi of menuItems) {
  161. if (mi.textContent.trim() === '删除邮件') {
  162. deleteMenuItem = mi.closest('.nui-menu-item');
  163. break;
  164. }
  165. }
  166. if (deleteMenuItem) break;
  167. }
  168. if (deleteMenuItem) {
  169. deleteMenuItem.click();
  170. log(`Step ${step}: Clicked "删除邮件"`, 'ok');
  171. // Wait for the delete to process and item to disappear
  172. await sleep(1000);
  173. log(`Step ${step}: Email deleted successfully`);
  174. } else {
  175. log(`Step ${step}: Context menu "删除邮件" not found`, 'warn');
  176. }
  177. } catch (err) {
  178. log(`Step ${step}: Failed to delete email: ${err.message}`, 'warn');
  179. }
  180. }
  181. // ============================================================
  182. // Inbox Refresh
  183. // ============================================================
  184. async function refreshInbox() {
  185. // Try toolbar "刷 新" button
  186. const toolbarBtns = document.querySelectorAll('.nui-btn .nui-btn-text');
  187. for (const btn of toolbarBtns) {
  188. if (btn.textContent.replace(/\s/g, '') === '刷新') {
  189. btn.closest('.nui-btn').click();
  190. console.log(MAIL163_PREFIX, 'Clicked "刷新" button');
  191. await sleep(800);
  192. return;
  193. }
  194. }
  195. // Fallback: click sidebar "收 信"
  196. const shouXinBtns = document.querySelectorAll('.ra0');
  197. for (const btn of shouXinBtns) {
  198. if (btn.textContent.replace(/\s/g, '').includes('收信')) {
  199. btn.click();
  200. console.log(MAIL163_PREFIX, 'Clicked "收信" button');
  201. await sleep(800);
  202. return;
  203. }
  204. }
  205. console.log(MAIL163_PREFIX, 'Could not find refresh button');
  206. }
  207. // ============================================================
  208. // Verification Code Extraction
  209. // ============================================================
  210. function extractVerificationCode(text) {
  211. const matchCn = text.match(/(?:代码为|验证码[^0-9]*?)[\s::]*(\d{6})/);
  212. if (matchCn) return matchCn[1];
  213. const matchEn = text.match(/code[:\s]+is[:\s]+(\d{6})|code[:\s]+(\d{6})/i);
  214. if (matchEn) return matchEn[1] || matchEn[2];
  215. const match6 = text.match(/\b(\d{6})\b/);
  216. if (match6) return match6[1];
  217. return null;
  218. }
  219. } // end of isTopFrame else block