mail-163.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  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. // Delete actions: hover trash icon on the row, or checkbox + toolbar delete button
  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(`步骤 ${message.step}:已被用户停止。`, 'warn');
  49. sendResponse({ stopped: true, error: err.message });
  50. return;
  51. }
  52. log(`步骤 ${message.step}:邮箱轮询失败:${err.message}`, 'warn');
  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. function normalizeMinuteTimestamp(timestamp) {
  73. if (!Number.isFinite(timestamp) || timestamp <= 0) return 0;
  74. const date = new Date(timestamp);
  75. date.setSeconds(0, 0);
  76. return date.getTime();
  77. }
  78. function parseMail163Timestamp(rawText) {
  79. const text = (rawText || '').replace(/\s+/g, ' ').trim();
  80. if (!text) return null;
  81. let match = text.match(/(\d{4})年(\d{1,2})月(\d{1,2})日\s+(\d{1,2}):(\d{2})/);
  82. if (match) {
  83. const [, year, month, day, hour, minute] = match;
  84. return new Date(
  85. Number(year),
  86. Number(month) - 1,
  87. Number(day),
  88. Number(hour),
  89. Number(minute),
  90. 0,
  91. 0
  92. ).getTime();
  93. }
  94. match = text.match(/\b(\d{1,2}):(\d{2})\b/);
  95. if (match) {
  96. const [, hour, minute] = match;
  97. const now = new Date();
  98. return new Date(
  99. now.getFullYear(),
  100. now.getMonth(),
  101. now.getDate(),
  102. Number(hour),
  103. Number(minute),
  104. 0,
  105. 0
  106. ).getTime();
  107. }
  108. return null;
  109. }
  110. function getMailTimestamp(item) {
  111. const candidates = [];
  112. const timeCell = item.querySelector('.e00[title], [title*="年"][title*=":"]');
  113. if (timeCell?.getAttribute('title')) candidates.push(timeCell.getAttribute('title'));
  114. if (timeCell?.textContent) candidates.push(timeCell.textContent);
  115. const titledNodes = item.querySelectorAll('[title]');
  116. titledNodes.forEach((node) => {
  117. const title = node.getAttribute('title');
  118. if (title) candidates.push(title);
  119. });
  120. for (const candidate of candidates) {
  121. const parsed = parseMail163Timestamp(candidate);
  122. if (parsed) return parsed;
  123. }
  124. return null;
  125. }
  126. function scheduleEmailCleanup(item, step) {
  127. setTimeout(() => {
  128. Promise.resolve(deleteEmail(item, step)).catch(() => {
  129. // Cleanup is best effort only and must never affect the main verification flow.
  130. });
  131. }, 0);
  132. }
  133. // ============================================================
  134. // Email Polling
  135. // ============================================================
  136. async function handlePollEmail(step, payload) {
  137. const { senderFilters, subjectFilters, maxAttempts, intervalMs, excludeCodes = [], filterAfterTimestamp = 0 } = payload;
  138. const excludedCodeSet = new Set(excludeCodes.filter(Boolean));
  139. const filterAfterMinute = normalizeMinuteTimestamp(Number(filterAfterTimestamp) || 0);
  140. log(`步骤 ${step}:开始轮询 163 邮箱(最多 ${maxAttempts} 次)`);
  141. if (filterAfterMinute) {
  142. log(`步骤 ${step}:仅尝试 ${new Date(filterAfterMinute).toLocaleString('zh-CN', { hour12: false })} 及之后时间的邮件。`);
  143. }
  144. // Click inbox in sidebar to ensure we're in inbox view
  145. log(`步骤 ${step}:正在等待侧边栏加载...`);
  146. try {
  147. const inboxLink = await waitForElement('.nui-tree-item-text[title="收件箱"]', 5000);
  148. inboxLink.click();
  149. log(`步骤 ${step}:已点击收件箱`);
  150. } catch {
  151. log(`步骤 ${step}:未找到收件箱入口,继续尝试后续流程...`, 'warn');
  152. }
  153. // Wait for mail list to appear
  154. log(`步骤 ${step}:正在等待邮件列表加载...`);
  155. let items = [];
  156. for (let i = 0; i < 20; i++) {
  157. items = findMailItems();
  158. if (items.length > 0) break;
  159. await sleep(500);
  160. }
  161. if (items.length === 0) {
  162. await refreshInbox();
  163. await sleep(2000);
  164. items = findMailItems();
  165. }
  166. if (items.length === 0) {
  167. throw new Error('163 邮箱列表未加载完成,请确认当前已打开收件箱。');
  168. }
  169. log(`步骤 ${step}:邮件列表已加载,共 ${items.length} 封邮件`);
  170. // Snapshot existing mail IDs
  171. const existingMailIds = getCurrentMailIds();
  172. log(`步骤 ${step}:已记录当前 ${existingMailIds.size} 封旧邮件快照`);
  173. const FALLBACK_AFTER = 3;
  174. for (let attempt = 1; attempt <= maxAttempts; attempt++) {
  175. log(`步骤 ${step}:正在轮询 163 邮箱,第 ${attempt}/${maxAttempts} 次`);
  176. if (attempt > 1) {
  177. await refreshInbox();
  178. await sleep(1000);
  179. }
  180. const allItems = findMailItems();
  181. const useFallback = attempt > FALLBACK_AFTER;
  182. for (const item of allItems) {
  183. const id = item.getAttribute('id') || '';
  184. const mailTimestamp = getMailTimestamp(item);
  185. const mailMinute = normalizeMinuteTimestamp(mailTimestamp || 0);
  186. const passesTimeFilter = !filterAfterMinute || (mailMinute && mailMinute >= filterAfterMinute);
  187. const shouldBypassOldSnapshot = Boolean(filterAfterMinute && passesTimeFilter && mailMinute > 0);
  188. if (!passesTimeFilter) {
  189. continue;
  190. }
  191. if (!useFallback && !shouldBypassOldSnapshot && existingMailIds.has(id)) continue;
  192. const senderEl = item.querySelector('.nui-user');
  193. const sender = senderEl ? senderEl.textContent.toLowerCase() : '';
  194. const subjectEl = item.querySelector('span.da0');
  195. const subject = subjectEl ? subjectEl.textContent : '';
  196. const ariaLabel = (item.getAttribute('aria-label') || '').toLowerCase();
  197. const senderMatch = senderFilters.some(f => sender.includes(f.toLowerCase()) || ariaLabel.includes(f.toLowerCase()));
  198. const subjectMatch = subjectFilters.some(f => subject.toLowerCase().includes(f.toLowerCase()) || ariaLabel.includes(f.toLowerCase()));
  199. if (senderMatch || subjectMatch) {
  200. const code = extractVerificationCode(subject + ' ' + ariaLabel);
  201. if (code && excludedCodeSet.has(code)) {
  202. log(`步骤 ${step}:跳过排除的验证码:${code}`, 'info');
  203. } else if (code && !seenCodes.has(code)) {
  204. seenCodes.add(code);
  205. persistSeenCodes();
  206. const source = useFallback && existingMailIds.has(id) ? '回退匹配邮件' : '新邮件';
  207. const timeLabel = mailTimestamp ? `,时间:${new Date(mailTimestamp).toLocaleString('zh-CN', { hour12: false })}` : '';
  208. log(`步骤 ${step}:已找到验证码:${code}(来源:${source}${timeLabel},主题:${subject.slice(0, 40)})`, 'ok');
  209. // Trigger cleanup only as a best-effort side effect.
  210. scheduleEmailCleanup(item, step);
  211. return { ok: true, code, emailTimestamp: Date.now(), mailId: id };
  212. } else if (code && seenCodes.has(code)) {
  213. log(`步骤 ${step}:跳过已处理过的验证码:${code}`, 'info');
  214. }
  215. }
  216. }
  217. if (attempt === FALLBACK_AFTER + 1) {
  218. log(`步骤 ${step}:连续 ${FALLBACK_AFTER} 次未发现新邮件,开始回退到首封匹配邮件`, 'warn');
  219. }
  220. if (attempt < maxAttempts) {
  221. await sleep(intervalMs);
  222. }
  223. }
  224. throw new Error(
  225. `${(maxAttempts * intervalMs / 1000).toFixed(0)} 秒后仍未在 163 邮箱中找到新的匹配邮件。` +
  226. '请手动检查收件箱。'
  227. );
  228. }
  229. // ============================================================
  230. // Delete Email via Hover Trash / Toolbar Fallback
  231. // ============================================================
  232. async function deleteEmail(item, step) {
  233. try {
  234. log(`步骤 ${step}:正在删除邮件...`);
  235. // Strategy 1: Click the trash icon inside the mail item
  236. // Each mail item has: <b class="nui-ico nui-ico-delete" title="删除邮件" sign="trash">
  237. // These icons appear on hover, so we trigger mouseover first
  238. item.dispatchEvent(new MouseEvent('mouseover', { bubbles: true }));
  239. item.dispatchEvent(new MouseEvent('mouseenter', { bubbles: true }));
  240. await sleep(300);
  241. const trashIcon = item.querySelector('[sign="trash"], .nui-ico-delete, [title="删除邮件"]');
  242. if (trashIcon) {
  243. trashIcon.click();
  244. log(`步骤 ${step}:已点击删除图标`, 'ok');
  245. await sleep(1500);
  246. // Check if item disappeared (confirm deletion)
  247. const stillExists = document.getElementById(item.id);
  248. if (!stillExists || stillExists.style.display === 'none') {
  249. log(`步骤 ${step}:邮件已成功删除`);
  250. } else {
  251. log(`步骤 ${step}:邮件可能尚未删除,列表中仍可见`, 'warn');
  252. }
  253. return;
  254. }
  255. // Strategy 2: Select checkbox then click toolbar delete button
  256. log(`步骤 ${step}:未找到删除图标,尝试使用复选框加工具栏删除...`);
  257. const checkbox = item.querySelector('[sign="checkbox"], .nui-chk');
  258. if (checkbox) {
  259. checkbox.click();
  260. await sleep(300);
  261. // Click toolbar delete button
  262. const toolbarBtns = document.querySelectorAll('.nui-btn .nui-btn-text');
  263. for (const btn of toolbarBtns) {
  264. if (btn.textContent.replace(/\s/g, '').includes('删除')) {
  265. btn.closest('.nui-btn').click();
  266. log(`步骤 ${step}:已点击工具栏删除`, 'ok');
  267. await sleep(1500);
  268. return;
  269. }
  270. }
  271. }
  272. log(`步骤 ${step}:无法删除邮件(未找到删除按钮)`, 'warn');
  273. } catch (err) {
  274. log(`步骤 ${step}:删除邮件失败:${err.message}`, 'warn');
  275. }
  276. }
  277. // ============================================================
  278. // Inbox Refresh
  279. // ============================================================
  280. async function refreshInbox() {
  281. // Try toolbar "刷 新" button
  282. const toolbarBtns = document.querySelectorAll('.nui-btn .nui-btn-text');
  283. for (const btn of toolbarBtns) {
  284. if (btn.textContent.replace(/\s/g, '') === '刷新') {
  285. btn.closest('.nui-btn').click();
  286. console.log(MAIL163_PREFIX, 'Clicked "刷新" button');
  287. await sleep(800);
  288. return;
  289. }
  290. }
  291. // Fallback: click sidebar "收 信"
  292. const shouXinBtns = document.querySelectorAll('.ra0');
  293. for (const btn of shouXinBtns) {
  294. if (btn.textContent.replace(/\s/g, '').includes('收信')) {
  295. btn.click();
  296. console.log(MAIL163_PREFIX, 'Clicked "收信" button');
  297. await sleep(800);
  298. return;
  299. }
  300. }
  301. console.log(MAIL163_PREFIX, 'Could not find refresh button');
  302. }
  303. // ============================================================
  304. // Verification Code Extraction
  305. // ============================================================
  306. function extractVerificationCode(text) {
  307. const matchCn = text.match(/(?:代码为|验证码[^0-9]*?)[\s::]*(\d{6})/);
  308. if (matchCn) return matchCn[1];
  309. const matchEn = text.match(/code[:\s]+is[:\s]+(\d{6})|code[:\s]+(\d{6})/i);
  310. if (matchEn) return matchEn[1] || matchEn[2];
  311. const match6 = text.match(/\b(\d{6})\b/);
  312. if (match6) return match6[1];
  313. return null;
  314. }
  315. } // end of isTopFrame else block