mail-163.js 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  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. // Strategy 1: Click the trash icon inside the mail item
  149. // Each mail item has: <b class="nui-ico nui-ico-delete" title="删除邮件" sign="trash">
  150. // These icons appear on hover, so we trigger mouseover first
  151. item.dispatchEvent(new MouseEvent('mouseover', { bubbles: true }));
  152. item.dispatchEvent(new MouseEvent('mouseenter', { bubbles: true }));
  153. await sleep(300);
  154. const trashIcon = item.querySelector('[sign="trash"], .nui-ico-delete, [title="删除邮件"]');
  155. if (trashIcon) {
  156. trashIcon.click();
  157. log(`Step ${step}: Clicked trash icon`, 'ok');
  158. await sleep(1500);
  159. // Check if item disappeared (confirm deletion)
  160. const stillExists = document.getElementById(item.id);
  161. if (!stillExists || stillExists.style.display === 'none') {
  162. log(`Step ${step}: Email deleted successfully`);
  163. } else {
  164. log(`Step ${step}: Email may not have been deleted, item still visible`, 'warn');
  165. }
  166. return;
  167. }
  168. // Strategy 2: Select checkbox then click toolbar delete button
  169. log(`Step ${step}: Trash icon not found, trying checkbox + toolbar delete...`);
  170. const checkbox = item.querySelector('[sign="checkbox"], .nui-chk');
  171. if (checkbox) {
  172. checkbox.click();
  173. await sleep(300);
  174. // Click toolbar delete button
  175. const toolbarBtns = document.querySelectorAll('.nui-btn .nui-btn-text');
  176. for (const btn of toolbarBtns) {
  177. if (btn.textContent.replace(/\s/g, '').includes('删除')) {
  178. btn.closest('.nui-btn').click();
  179. log(`Step ${step}: Clicked toolbar delete`, 'ok');
  180. await sleep(1500);
  181. return;
  182. }
  183. }
  184. }
  185. log(`Step ${step}: Could not delete email (no delete button found)`, 'warn');
  186. } catch (err) {
  187. log(`Step ${step}: Failed to delete email: ${err.message}`, 'warn');
  188. }
  189. }
  190. // ============================================================
  191. // Inbox Refresh
  192. // ============================================================
  193. async function refreshInbox() {
  194. // Try toolbar "刷 新" button
  195. const toolbarBtns = document.querySelectorAll('.nui-btn .nui-btn-text');
  196. for (const btn of toolbarBtns) {
  197. if (btn.textContent.replace(/\s/g, '') === '刷新') {
  198. btn.closest('.nui-btn').click();
  199. console.log(MAIL163_PREFIX, 'Clicked "刷新" button');
  200. await sleep(800);
  201. return;
  202. }
  203. }
  204. // Fallback: click sidebar "收 信"
  205. const shouXinBtns = document.querySelectorAll('.ra0');
  206. for (const btn of shouXinBtns) {
  207. if (btn.textContent.replace(/\s/g, '').includes('收信')) {
  208. btn.click();
  209. console.log(MAIL163_PREFIX, 'Clicked "收信" button');
  210. await sleep(800);
  211. return;
  212. }
  213. }
  214. console.log(MAIL163_PREFIX, 'Could not find refresh button');
  215. }
  216. // ============================================================
  217. // Verification Code Extraction
  218. // ============================================================
  219. function extractVerificationCode(text) {
  220. const matchCn = text.match(/(?:代码为|验证码[^0-9]*?)[\s::]*(\d{6})/);
  221. if (matchCn) return matchCn[1];
  222. const matchEn = text.match(/code[:\s]+is[:\s]+(\d{6})|code[:\s]+(\d{6})/i);
  223. if (matchEn) return matchEn[1] || matchEn[2];
  224. const match6 = text.match(/\b(\d{6})\b/);
  225. if (match6) return match6[1];
  226. return null;
  227. }
  228. } // end of isTopFrame else block