mail-163.js 9.8 KB

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