mail-163.js 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  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. resetStopState();
  37. handlePollEmail(message.step, message.payload).then(result => {
  38. sendResponse(result);
  39. }).catch(err => {
  40. if (isStopError(err)) {
  41. log(`Step ${message.step}: Stopped by user.`, 'warn');
  42. sendResponse({ stopped: true, error: err.message });
  43. return;
  44. }
  45. reportError(message.step, err.message);
  46. sendResponse({ error: err.message });
  47. });
  48. return true;
  49. }
  50. });
  51. // ============================================================
  52. // Find mail items
  53. // ============================================================
  54. function findMailItems() {
  55. return document.querySelectorAll('div[sign="letter"]');
  56. }
  57. function getCurrentMailIds() {
  58. const ids = new Set();
  59. findMailItems().forEach(item => {
  60. const id = item.getAttribute('id') || '';
  61. if (id) ids.add(id);
  62. });
  63. return ids;
  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. // Click inbox in sidebar to ensure we're in inbox view
  72. log(`Step ${step}: Waiting for sidebar...`);
  73. try {
  74. const inboxLink = await waitForElement('.nui-tree-item-text[title="收件箱"]', 5000);
  75. inboxLink.click();
  76. log(`Step ${step}: Clicked inbox`);
  77. } catch {
  78. log(`Step ${step}: Inbox link not found, proceeding...`, 'warn');
  79. }
  80. // Wait for mail list to appear
  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. await refreshInbox();
  90. await sleep(2000);
  91. items = findMailItems();
  92. }
  93. if (items.length === 0) {
  94. throw new Error('163 Mail list did not load. Make sure inbox is open.');
  95. }
  96. log(`Step ${step}: Mail list loaded, ${items.length} items`);
  97. // Snapshot existing mail IDs
  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. const senderEl = item.querySelector('.nui-user');
  113. const sender = senderEl ? senderEl.textContent.toLowerCase() : '';
  114. const subjectEl = item.querySelector('span.da0');
  115. const subject = subjectEl ? subjectEl.textContent : '';
  116. const ariaLabel = (item.getAttribute('aria-label') || '').toLowerCase();
  117. const senderMatch = senderFilters.some(f => sender.includes(f.toLowerCase()) || ariaLabel.includes(f.toLowerCase()));
  118. const subjectMatch = subjectFilters.some(f => subject.toLowerCase().includes(f.toLowerCase()) || ariaLabel.includes(f.toLowerCase()));
  119. if (senderMatch || subjectMatch) {
  120. const code = extractVerificationCode(subject + ' ' + ariaLabel);
  121. if (code && !seenCodes.has(code)) {
  122. seenCodes.add(code);
  123. persistSeenCodes();
  124. const source = useFallback && existingMailIds.has(id) ? 'fallback' : 'new';
  125. log(`Step ${step}: Code found: ${code} (${source}, subject: ${subject.slice(0, 40)})`, 'ok');
  126. // Delete this email via right-click menu, WAIT for it to finish before returning
  127. await deleteEmail(item, step);
  128. // Extra wait to ensure deletion is processed
  129. await sleep(1000);
  130. return { ok: true, code, emailTimestamp: Date.now(), mailId: id };
  131. } else if (code && seenCodes.has(code)) {
  132. log(`Step ${step}: Skipping already-seen code: ${code}`, 'info');
  133. }
  134. }
  135. }
  136. if (attempt === FALLBACK_AFTER + 1) {
  137. log(`Step ${step}: No new emails after ${FALLBACK_AFTER} attempts, falling back to first match`, 'warn');
  138. }
  139. if (attempt < maxAttempts) {
  140. await sleep(intervalMs);
  141. }
  142. }
  143. throw new Error(
  144. `No new matching email found on 163 Mail after ${(maxAttempts * intervalMs / 1000).toFixed(0)}s. ` +
  145. 'Check inbox manually.'
  146. );
  147. }
  148. // ============================================================
  149. // Delete Email via Right-Click Menu
  150. // ============================================================
  151. async function deleteEmail(item, step) {
  152. try {
  153. log(`Step ${step}: Deleting email...`);
  154. // Strategy 1: Click the trash icon inside the mail item
  155. // Each mail item has: <b class="nui-ico nui-ico-delete" title="删除邮件" sign="trash">
  156. // These icons appear on hover, so we trigger mouseover first
  157. item.dispatchEvent(new MouseEvent('mouseover', { bubbles: true }));
  158. item.dispatchEvent(new MouseEvent('mouseenter', { bubbles: true }));
  159. await sleep(300);
  160. const trashIcon = item.querySelector('[sign="trash"], .nui-ico-delete, [title="删除邮件"]');
  161. if (trashIcon) {
  162. trashIcon.click();
  163. log(`Step ${step}: Clicked trash icon`, 'ok');
  164. await sleep(1500);
  165. // Check if item disappeared (confirm deletion)
  166. const stillExists = document.getElementById(item.id);
  167. if (!stillExists || stillExists.style.display === 'none') {
  168. log(`Step ${step}: Email deleted successfully`);
  169. } else {
  170. log(`Step ${step}: Email may not have been deleted, item still visible`, 'warn');
  171. }
  172. return;
  173. }
  174. // Strategy 2: Select checkbox then click toolbar delete button
  175. log(`Step ${step}: Trash icon not found, trying checkbox + toolbar delete...`);
  176. const checkbox = item.querySelector('[sign="checkbox"], .nui-chk');
  177. if (checkbox) {
  178. checkbox.click();
  179. await sleep(300);
  180. // Click toolbar delete button
  181. const toolbarBtns = document.querySelectorAll('.nui-btn .nui-btn-text');
  182. for (const btn of toolbarBtns) {
  183. if (btn.textContent.replace(/\s/g, '').includes('删除')) {
  184. btn.closest('.nui-btn').click();
  185. log(`Step ${step}: Clicked toolbar delete`, 'ok');
  186. await sleep(1500);
  187. return;
  188. }
  189. }
  190. }
  191. log(`Step ${step}: Could not delete email (no delete button found)`, 'warn');
  192. } catch (err) {
  193. log(`Step ${step}: Failed to delete email: ${err.message}`, 'warn');
  194. }
  195. }
  196. // ============================================================
  197. // Inbox Refresh
  198. // ============================================================
  199. async function refreshInbox() {
  200. // Try toolbar "刷 新" button
  201. const toolbarBtns = document.querySelectorAll('.nui-btn .nui-btn-text');
  202. for (const btn of toolbarBtns) {
  203. if (btn.textContent.replace(/\s/g, '') === '刷新') {
  204. btn.closest('.nui-btn').click();
  205. console.log(MAIL163_PREFIX, 'Clicked "刷新" button');
  206. await sleep(800);
  207. return;
  208. }
  209. }
  210. // Fallback: click sidebar "收 信"
  211. const shouXinBtns = document.querySelectorAll('.ra0');
  212. for (const btn of shouXinBtns) {
  213. if (btn.textContent.replace(/\s/g, '').includes('收信')) {
  214. btn.click();
  215. console.log(MAIL163_PREFIX, 'Clicked "收信" button');
  216. await sleep(800);
  217. return;
  218. }
  219. }
  220. console.log(MAIL163_PREFIX, 'Could not find refresh button');
  221. }
  222. // ============================================================
  223. // Verification Code Extraction
  224. // ============================================================
  225. function extractVerificationCode(text) {
  226. const matchCn = text.match(/(?:代码为|验证码[^0-9]*?)[\s::]*(\d{6})/);
  227. if (matchCn) return matchCn[1];
  228. const matchEn = text.match(/code[:\s]+is[:\s]+(\d{6})|code[:\s]+(\d{6})/i);
  229. if (matchEn) return matchEn[1] || matchEn[2];
  230. const match6 = text.match(/\b(\d{6})\b/);
  231. if (match6) return match6[1];
  232. return null;
  233. }
  234. } // end of isTopFrame else block