gmail-mail.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685
  1. // content/gmail-mail.js — Content script for Gmail polling (steps 4, 7)
  2. // Injected dynamically on: mail.google.com
  3. const GMAIL_PREFIX = '[MultiPage:gmail-mail]';
  4. const GMAIL_SEEN_CODES_KEY = 'seenGmailCodes';
  5. const GMAIL_FALLBACK_AFTER = 3;
  6. const isTopFrame = window === window.top;
  7. console.log(GMAIL_PREFIX, 'Content script loaded on', location.href, 'frame:', isTopFrame ? 'top' : 'child');
  8. if (!isTopFrame) {
  9. console.log(GMAIL_PREFIX, 'Skipping child frame');
  10. } else {
  11. let seenCodes = new Set();
  12. async function loadSeenCodes() {
  13. try {
  14. const data = await chrome.storage.session.get(GMAIL_SEEN_CODES_KEY);
  15. if (Array.isArray(data[GMAIL_SEEN_CODES_KEY])) {
  16. seenCodes = new Set(data[GMAIL_SEEN_CODES_KEY]);
  17. console.log(GMAIL_PREFIX, `Loaded ${seenCodes.size} previously seen codes`);
  18. }
  19. } catch (err) {
  20. console.warn(GMAIL_PREFIX, 'Session storage unavailable, using in-memory seen codes:', err?.message || err);
  21. }
  22. }
  23. async function persistSeenCodes() {
  24. try {
  25. await chrome.storage.session.set({ [GMAIL_SEEN_CODES_KEY]: [...seenCodes] });
  26. } catch (err) {
  27. console.warn(GMAIL_PREFIX, 'Could not persist seen codes, continuing in-memory only:', err?.message || err);
  28. }
  29. }
  30. loadSeenCodes();
  31. chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  32. if (message.type === 'POLL_EMAIL') {
  33. resetStopState();
  34. handlePollEmail(message.step, message.payload).then((result) => {
  35. sendResponse(result);
  36. }).catch((err) => {
  37. if (isStopError(err)) {
  38. log(`步骤 ${message.step}:已被用户停止。`, 'warn');
  39. sendResponse({ stopped: true, error: err.message });
  40. return;
  41. }
  42. log(`步骤 ${message.step}:Gmail 轮询失败:${err.message}`, 'warn');
  43. sendResponse({ error: err.message });
  44. });
  45. return true;
  46. }
  47. });
  48. function normalizeText(value) {
  49. return String(value || '').replace(/\s+/g, ' ').trim();
  50. }
  51. function isDisplayed(element) {
  52. if (!element) return false;
  53. const style = window.getComputedStyle(element);
  54. return style.display !== 'none' && style.visibility !== 'hidden';
  55. }
  56. function isVisibleElement(element) {
  57. if (!isDisplayed(element)) return false;
  58. const rect = element.getBoundingClientRect();
  59. return rect.width > 0 && rect.height > 0;
  60. }
  61. function normalizeMinuteTimestamp(timestamp) {
  62. if (!Number.isFinite(timestamp) || timestamp <= 0) return 0;
  63. const date = new Date(timestamp);
  64. date.setSeconds(0, 0);
  65. return date.getTime();
  66. }
  67. function getTargetEmailMatchState(text, targetEmail) {
  68. const normalizedTarget = String(targetEmail || '').trim().toLowerCase();
  69. if (!normalizedTarget) {
  70. return { matches: true, hasExplicitEmail: false };
  71. }
  72. const normalizedText = String(text || '').toLowerCase();
  73. if (normalizedText.includes(normalizedTarget)) {
  74. return { matches: true, hasExplicitEmail: true };
  75. }
  76. const atIndex = normalizedTarget.indexOf('@');
  77. if (atIndex > 0) {
  78. const encodedTarget = `${normalizedTarget.slice(0, atIndex)}=${normalizedTarget.slice(atIndex + 1)}`;
  79. if (normalizedText.includes(encodedTarget)) {
  80. return { matches: true, hasExplicitEmail: true };
  81. }
  82. }
  83. return { matches: false, hasExplicitEmail: false };
  84. }
  85. const MONTH_INDEX_MAP = {
  86. jan: 0,
  87. feb: 1,
  88. mar: 2,
  89. apr: 3,
  90. may: 4,
  91. jun: 5,
  92. jul: 6,
  93. aug: 7,
  94. sep: 8,
  95. oct: 9,
  96. nov: 10,
  97. dec: 11,
  98. };
  99. function parseGmailTimestampText(rawText) {
  100. const text = normalizeText(rawText);
  101. if (!text) return null;
  102. const parsedNative = Date.parse(text);
  103. if (Number.isFinite(parsedNative)) {
  104. return parsedNative;
  105. }
  106. let match = text.match(/(\d{4})[年/-](\d{1,2})[月/-](\d{1,2})日?\s+(\d{1,2}):(\d{2})(?:\s*([AP]M))?/i);
  107. if (match) {
  108. const [, year, month, day, hourText, minute, meridiem] = match;
  109. let hour = Number(hourText);
  110. if (/pm/i.test(meridiem) && hour < 12) hour += 12;
  111. if (/am/i.test(meridiem) && hour === 12) hour = 0;
  112. return new Date(Number(year), Number(month) - 1, Number(day), hour, Number(minute), 0, 0).getTime();
  113. }
  114. match = text.match(/\b([A-Za-z]{3,9})\s+(\d{1,2}),\s*(\d{4}),?\s*(\d{1,2}):(\d{2})\s*([AP]M)\b/i);
  115. if (match) {
  116. const [, monthText, day, year, hourText, minute, meridiem] = match;
  117. const month = MONTH_INDEX_MAP[monthText.slice(0, 3).toLowerCase()];
  118. if (month !== undefined) {
  119. let hour = Number(hourText);
  120. if (/pm/i.test(meridiem) && hour < 12) hour += 12;
  121. if (/am/i.test(meridiem) && hour === 12) hour = 0;
  122. return new Date(Number(year), month, Number(day), hour, Number(minute), 0, 0).getTime();
  123. }
  124. }
  125. match = text.match(/今天\s*(\d{1,2}):(\d{2})/);
  126. if (match) {
  127. const now = new Date();
  128. return new Date(now.getFullYear(), now.getMonth(), now.getDate(), Number(match[1]), Number(match[2]), 0, 0).getTime();
  129. }
  130. match = text.match(/昨天\s*(\d{1,2}):(\d{2})/);
  131. if (match) {
  132. const now = new Date();
  133. now.setDate(now.getDate() - 1);
  134. return new Date(now.getFullYear(), now.getMonth(), now.getDate(), Number(match[1]), Number(match[2]), 0, 0).getTime();
  135. }
  136. match = text.match(/^(\d{1,2}):(\d{2})$/);
  137. if (match) {
  138. const now = new Date();
  139. return new Date(now.getFullYear(), now.getMonth(), now.getDate(), Number(match[1]), Number(match[2]), 0, 0).getTime();
  140. }
  141. return null;
  142. }
  143. function extractVerificationCode(text) {
  144. const normalized = String(text || '');
  145. const cnMatch = normalized.match(/(?:验证码|代码)[^0-9]{0,16}(\d{6})/i);
  146. if (cnMatch) return cnMatch[1];
  147. const enMatch = normalized.match(/(?:verification\s+code|temporary\s+verification\s+code|your\s+chatgpt\s+code|code(?:\s+is)?)[^0-9]{0,16}(\d{6})/i);
  148. if (enMatch) return enMatch[1];
  149. const plainMatch = normalized.match(/\b(\d{6})\b/);
  150. if (plainMatch) return plainMatch[1];
  151. return null;
  152. }
  153. function findInboxLink() {
  154. const selectors = [
  155. 'a[href*="#inbox"]',
  156. 'a[aria-label*="收件箱"]',
  157. 'a[aria-label*="Inbox"]',
  158. ];
  159. for (const selector of selectors) {
  160. const candidates = Array.from(document.querySelectorAll(selector));
  161. const visible = candidates.find(isVisibleElement);
  162. if (visible) return visible;
  163. if (candidates[0]) return candidates[0];
  164. }
  165. return Array.from(document.querySelectorAll('a, [role="link"]')).find((element) => {
  166. const text = normalizeText(
  167. element.getAttribute('aria-label')
  168. || element.getAttribute('title')
  169. || element.textContent
  170. );
  171. return /收件箱|Inbox/i.test(text);
  172. }) || null;
  173. }
  174. const GMAIL_CATEGORY_LABELS = {
  175. primary: [/^primary$/i, /^inbox$/i, /^主要$/],
  176. updates: [/^updates$/i, /^更新$/],
  177. promotions: [/^promotions$/i, /^推广$/],
  178. social: [/^social$/i, /^社交$/],
  179. };
  180. function getCategoryKeyFromText(text) {
  181. const normalizedText = normalizeText(text);
  182. if (!normalizedText) return '';
  183. for (const [key, patterns] of Object.entries(GMAIL_CATEGORY_LABELS)) {
  184. if (patterns.some((pattern) => pattern.test(normalizedText))) {
  185. return key;
  186. }
  187. }
  188. return '';
  189. }
  190. function getCategoryTabLabel(tab) {
  191. const text = normalizeText(
  192. tab?.getAttribute?.('aria-label')
  193. || tab?.getAttribute?.('data-tooltip')
  194. || tab?.getAttribute?.('title')
  195. || tab?.textContent
  196. || ''
  197. );
  198. return text;
  199. }
  200. function collectCategoryTabs() {
  201. const tabs = Array.from(document.querySelectorAll('[role="tab"], [data-tooltip-align][role="link"]'));
  202. const categoryTabs = [];
  203. const seenKeys = new Set();
  204. tabs.forEach((tab) => {
  205. if (!isVisibleElement(tab)) return;
  206. const label = getCategoryTabLabel(tab);
  207. const key = getCategoryKeyFromText(label);
  208. if (!key || seenKeys.has(key)) return;
  209. seenKeys.add(key);
  210. categoryTabs.push({
  211. key,
  212. label,
  213. selected: tab.getAttribute('aria-selected') === 'true' || /\bTO\b/.test(tab.className || ''),
  214. tab,
  215. });
  216. });
  217. return categoryTabs;
  218. }
  219. function getCategoryScanOrder() {
  220. const categoryTabs = collectCategoryTabs();
  221. if (!categoryTabs.length) {
  222. return [{ key: 'primary', label: 'Primary', selected: true, tab: null }];
  223. }
  224. const ordered = ['updates', 'primary']
  225. .map((key) => categoryTabs.find((item) => item.key === key))
  226. .filter(Boolean);
  227. return ordered.length
  228. ? ordered
  229. : [{ key: 'primary', label: 'Primary', selected: true, tab: null }];
  230. }
  231. async function activateCategoryTab(step, categoryKey) {
  232. const categoryTabs = collectCategoryTabs();
  233. const target = categoryTabs.find((item) => item.key === categoryKey);
  234. if (!target?.tab) {
  235. return { key: categoryKey, label: categoryKey, switched: false };
  236. }
  237. if (target.selected) {
  238. return { key: target.key, label: target.label, switched: false };
  239. }
  240. simulateClick(target.tab);
  241. for (let i = 0; i < 20; i++) {
  242. await sleep(200);
  243. const refreshed = collectCategoryTabs().find((item) => item.key === categoryKey);
  244. if (refreshed?.selected) {
  245. await sleep(500);
  246. log(`步骤 ${step}:已切换到 Gmail 分类 ${refreshed.label}。`);
  247. return { key: refreshed.key, label: refreshed.label, switched: true };
  248. }
  249. }
  250. await sleep(600);
  251. log(`步骤 ${step}:已尝试切换到 Gmail 分类 ${target.label}。`, 'info');
  252. return { key: target.key, label: target.label, switched: true };
  253. }
  254. function findRefreshButton() {
  255. const selectors = [
  256. 'div[role="button"][data-tooltip="刷新"]',
  257. 'div[role="button"][aria-label="刷新"]',
  258. 'div[role="button"][data-tooltip*="刷新"]',
  259. 'div[role="button"][aria-label*="刷新"]',
  260. 'div[role="button"][data-tooltip="Refresh"]',
  261. 'div[role="button"][aria-label="Refresh"]',
  262. 'div[role="button"][data-tooltip*="Refresh"]',
  263. 'div[role="button"][aria-label*="Refresh"]',
  264. 'div[act="20"][role="button"]',
  265. 'div.asf.T-I-J3.J-J5-Ji',
  266. ];
  267. for (const selector of selectors) {
  268. const matched = document.querySelector(selector);
  269. const button = matched?.closest?.('[role="button"]') || matched;
  270. if (button && isVisibleElement(button)) {
  271. return button;
  272. }
  273. }
  274. return Array.from(document.querySelectorAll('div[role="button"], button')).find((element) => {
  275. const text = normalizeText(
  276. element.getAttribute('aria-label')
  277. || element.getAttribute('data-tooltip')
  278. || element.getAttribute('title')
  279. || element.textContent
  280. );
  281. return /刷新|Refresh/i.test(text);
  282. }) || null;
  283. }
  284. function collectThreadRows() {
  285. const candidates = [
  286. ...document.querySelectorAll('tr.zA'),
  287. ...document.querySelectorAll('tr[role="row"]'),
  288. ];
  289. const rows = [];
  290. const seenRows = new Set();
  291. candidates.forEach((row) => {
  292. if (!row || seenRows.has(row)) return;
  293. seenRows.add(row);
  294. if (!isDisplayed(row)) return;
  295. const text = normalizeText(row.textContent || row.innerText || '');
  296. if (!text) return;
  297. if (
  298. row.matches('tr.zA')
  299. || row.querySelector('.bog, .y6, .y2, .afn, [data-thread-id], [data-legacy-thread-id], [data-legacy-last-message-id]')
  300. || /openai|chatgpt|verify|verification|code|验证码/i.test(text)
  301. ) {
  302. rows.push(row);
  303. }
  304. });
  305. return rows;
  306. }
  307. function getRowPreviewText(row) {
  308. const sender = normalizeText(
  309. row.querySelector('.zF, .yP, span[email], [email]')?.textContent
  310. || row.querySelector('[email]')?.getAttribute?.('email')
  311. || ''
  312. );
  313. const subject = normalizeText(
  314. row.querySelector('.bog [data-thread-id], .bog [data-legacy-thread-id], .bog, .y6, .bqe')?.textContent
  315. || ''
  316. );
  317. const digest = normalizeText(
  318. row.querySelector('.y2, .afn, .a4W, .bog + .y2')?.textContent
  319. || ''
  320. );
  321. const timeText = normalizeText(
  322. row.querySelector('td.xW span')?.getAttribute?.('title')
  323. || row.querySelector('td.xW span, td.xW time')?.getAttribute?.('title')
  324. || row.querySelector('td.xW span, td.xW time')?.textContent
  325. || ''
  326. );
  327. const fullText = normalizeText(row.textContent || row.innerText || '');
  328. return {
  329. sender,
  330. subject,
  331. digest,
  332. timeText,
  333. fullText,
  334. combinedText: normalizeText([sender, subject, digest, timeText, fullText].filter(Boolean).join(' ')),
  335. };
  336. }
  337. function getRowTimestamp(row) {
  338. const timeCell = row.querySelector('td.xW span, td.xW time, td.xW [title]');
  339. const candidates = [
  340. timeCell?.getAttribute?.('title'),
  341. timeCell?.getAttribute?.('aria-label'),
  342. timeCell?.textContent,
  343. ].filter(Boolean);
  344. for (const candidate of candidates) {
  345. const parsed = parseGmailTimestampText(candidate);
  346. if (parsed) return parsed;
  347. }
  348. return null;
  349. }
  350. function getRowFingerprint(row, index = 0) {
  351. const marker = row.querySelector('[data-thread-id], [data-legacy-thread-id], [data-legacy-last-message-id]');
  352. const stableId = row.getAttribute('data-thread-id')
  353. || row.getAttribute('data-legacy-thread-id')
  354. || row.getAttribute('data-legacy-last-message-id')
  355. || marker?.getAttribute?.('data-thread-id')
  356. || marker?.getAttribute?.('data-legacy-thread-id')
  357. || marker?.getAttribute?.('data-legacy-last-message-id')
  358. || row.getAttribute('id')
  359. || `row-${index}`;
  360. const preview = getRowPreviewText(row);
  361. return `${stableId}::${preview.subject}::${preview.timeText}`.slice(0, 300);
  362. }
  363. function getCurrentMailIds(rows = []) {
  364. const ids = new Set();
  365. const sourceRows = rows.length ? rows : collectThreadRows();
  366. sourceRows.forEach((row, index) => {
  367. ids.add(getRowFingerprint(row, index));
  368. });
  369. return ids;
  370. }
  371. function rowMatchesFilters(preview, senderFilters, subjectFilters) {
  372. const senderText = normalizeText(preview.sender).toLowerCase();
  373. const subjectText = normalizeText(preview.subject).toLowerCase();
  374. const combinedText = normalizeText(preview.combinedText).toLowerCase();
  375. const senderMatch = senderFilters.some((filter) => {
  376. const value = String(filter || '').toLowerCase();
  377. return value && (senderText.includes(value) || combinedText.includes(value));
  378. });
  379. const subjectMatch = subjectFilters.some((filter) => {
  380. const value = String(filter || '').toLowerCase();
  381. return value && (subjectText.includes(value) || combinedText.includes(value));
  382. });
  383. return senderMatch || subjectMatch;
  384. }
  385. async function ensureInboxReady(step) {
  386. if (!/#inbox/i.test(location.href)) {
  387. const inboxLink = findInboxLink();
  388. if (inboxLink) {
  389. simulateClick(inboxLink);
  390. await sleep(800);
  391. log(`步骤 ${step}:已切回 Gmail 收件箱。`);
  392. } else {
  393. location.hash = '#inbox';
  394. await sleep(800);
  395. }
  396. }
  397. for (let i = 0; i < 20; i++) {
  398. const rows = collectThreadRows();
  399. if (rows.length > 0) {
  400. return rows;
  401. }
  402. await sleep(400);
  403. }
  404. return [];
  405. }
  406. async function refreshInbox(step) {
  407. const refreshButton = findRefreshButton();
  408. if (refreshButton) {
  409. simulateClick(refreshButton);
  410. log(`步骤 ${step}:已点击 Gmail 刷新。`);
  411. await sleep(1500);
  412. return;
  413. }
  414. const inboxLink = findInboxLink();
  415. if (inboxLink) {
  416. simulateClick(inboxLink);
  417. log(`步骤 ${step}:未找到刷新按钮,已重新进入收件箱。`);
  418. await sleep(1200);
  419. return;
  420. }
  421. location.reload();
  422. log(`步骤 ${step}:未找到刷新按钮,已直接刷新页面。`);
  423. await sleep(2500);
  424. }
  425. async function returnToInbox() {
  426. if (/#inbox/i.test(location.href) && collectThreadRows().length > 0) {
  427. return;
  428. }
  429. const inboxLink = findInboxLink();
  430. if (inboxLink) {
  431. simulateClick(inboxLink);
  432. } else {
  433. location.hash = '#inbox';
  434. }
  435. for (let i = 0; i < 20; i++) {
  436. if (collectThreadRows().length > 0) {
  437. return;
  438. }
  439. await sleep(250);
  440. }
  441. }
  442. async function openRowAndGetMessageText(row) {
  443. simulateClick(row);
  444. for (let i = 0; i < 20; i++) {
  445. const messageContainer = document.querySelector('div[role="main"] .a3s, div[role="main"] [data-message-id], h2[data-thread-perm-id]');
  446. if (messageContainer || !/#inbox/i.test(location.href)) {
  447. break;
  448. }
  449. await sleep(250);
  450. }
  451. await sleep(900);
  452. const main = document.querySelector('div[role="main"]');
  453. const text = normalizeText(main?.innerText || document.body?.innerText || document.body?.textContent || '');
  454. await returnToInbox();
  455. return text;
  456. }
  457. async function handlePollEmail(step, payload) {
  458. const {
  459. senderFilters = [],
  460. subjectFilters = [],
  461. maxAttempts = 5,
  462. intervalMs = 3000,
  463. filterAfterTimestamp = 0,
  464. excludeCodes = [],
  465. targetEmail = '',
  466. } = payload || {};
  467. const excludedCodeSet = new Set(excludeCodes.filter(Boolean));
  468. const filterAfterMinute = normalizeMinuteTimestamp(Number(filterAfterTimestamp) || 0);
  469. log(`步骤 ${step}:开始轮询 Gmail(最多 ${maxAttempts} 次)`);
  470. if (filterAfterMinute) {
  471. log(`步骤 ${step}:仅尝试 ${new Date(filterAfterMinute).toLocaleString('zh-CN', { hour12: false })} 及之后时间的邮件。`);
  472. }
  473. let initialRows = await ensureInboxReady(step);
  474. if (!initialRows.length) {
  475. await refreshInbox(step);
  476. initialRows = await ensureInboxReady(step);
  477. }
  478. if (!initialRows.length) {
  479. throw new Error('Gmail 收件箱列表未加载完成,请确认当前已打开 Gmail 收件箱。');
  480. }
  481. const categoryOrder = getCategoryScanOrder();
  482. const existingMailIdsByCategory = new Map();
  483. for (const category of categoryOrder) {
  484. const activeCategory = await activateCategoryTab(step, category.key);
  485. const rows = collectThreadRows();
  486. existingMailIdsByCategory.set(activeCategory.key, getCurrentMailIds(rows));
  487. log(`步骤 ${step}:已记录 Gmail 分类 ${activeCategory.label} 的 ${rows.length} 封旧邮件快照`);
  488. }
  489. for (let attempt = 1; attempt <= maxAttempts; attempt++) {
  490. log(`步骤 ${step}:正在轮询 Gmail,第 ${attempt}/${maxAttempts} 次`);
  491. if (attempt > 1) {
  492. await refreshInbox(step);
  493. }
  494. const useFallback = attempt > GMAIL_FALLBACK_AFTER;
  495. for (const category of categoryOrder) {
  496. const activeCategory = await activateCategoryTab(step, category.key);
  497. const rows = collectThreadRows();
  498. const existingMailIds = existingMailIdsByCategory.get(activeCategory.key) || new Set();
  499. for (let index = 0; index < rows.length; index++) {
  500. const row = rows[index];
  501. const rowId = getRowFingerprint(row, index);
  502. const rowTimestamp = getRowTimestamp(row);
  503. const rowMinute = normalizeMinuteTimestamp(rowTimestamp || 0);
  504. const passesTimeFilter = !filterAfterMinute || (rowMinute && rowMinute >= filterAfterMinute);
  505. const shouldBypassOldSnapshot = Boolean(filterAfterMinute && passesTimeFilter && rowMinute > 0);
  506. if (!passesTimeFilter) {
  507. continue;
  508. }
  509. if (!useFallback && !shouldBypassOldSnapshot && existingMailIds.has(rowId)) {
  510. continue;
  511. }
  512. const preview = getRowPreviewText(row);
  513. if (!rowMatchesFilters(preview, senderFilters, subjectFilters)) {
  514. continue;
  515. }
  516. const previewTargetState = getTargetEmailMatchState(preview.combinedText, targetEmail);
  517. const previewCode = extractVerificationCode(preview.combinedText);
  518. if (previewCode) {
  519. if (excludedCodeSet.has(previewCode)) {
  520. log(`步骤 ${step}:跳过排除的验证码:${previewCode}`, 'info');
  521. continue;
  522. }
  523. if (seenCodes.has(previewCode)) {
  524. log(`步骤 ${step}:跳过已处理过的验证码:${previewCode}`, 'info');
  525. continue;
  526. }
  527. seenCodes.add(previewCode);
  528. persistSeenCodes();
  529. const source = useFallback && existingMailIds.has(rowId) ? '回退匹配邮件' : '新邮件';
  530. const timeLabel = rowTimestamp ? `,时间:${new Date(rowTimestamp).toLocaleString('zh-CN', { hour12: false })}` : '';
  531. const targetLabel = previewTargetState.matches ? ',目标邮箱命中' : '';
  532. log(`步骤 ${step}:已在 Gmail ${activeCategory.label} 分类找到验证码:${previewCode}(来源:${source}${timeLabel}${targetLabel})`, 'ok');
  533. return {
  534. ok: true,
  535. code: previewCode,
  536. emailTimestamp: Date.now(),
  537. mailId: rowId,
  538. };
  539. }
  540. const openedText = await openRowAndGetMessageText(row);
  541. const openedTargetState = getTargetEmailMatchState(openedText, targetEmail);
  542. const bodyCode = extractVerificationCode(openedText);
  543. if (!bodyCode) {
  544. continue;
  545. }
  546. if (excludedCodeSet.has(bodyCode)) {
  547. log(`步骤 ${step}:跳过排除的验证码:${bodyCode}`, 'info');
  548. continue;
  549. }
  550. if (seenCodes.has(bodyCode)) {
  551. log(`步骤 ${step}:跳过已处理过的验证码:${bodyCode}`, 'info');
  552. continue;
  553. }
  554. seenCodes.add(bodyCode);
  555. persistSeenCodes();
  556. const source = useFallback && existingMailIds.has(rowId) ? '回退匹配邮件正文' : '新邮件正文';
  557. const timeLabel = rowTimestamp ? `,时间:${new Date(rowTimestamp).toLocaleString('zh-CN', { hour12: false })}` : '';
  558. const targetLabel = openedTargetState.matches ? ',目标邮箱命中' : '';
  559. log(`步骤 ${step}:已在 Gmail ${activeCategory.label} 分类正文中找到验证码:${bodyCode}(来源:${source}${timeLabel}${targetLabel})`, 'ok');
  560. return {
  561. ok: true,
  562. code: bodyCode,
  563. emailTimestamp: Date.now(),
  564. mailId: rowId,
  565. };
  566. }
  567. }
  568. if (attempt === GMAIL_FALLBACK_AFTER + 1) {
  569. log(`步骤 ${step}:连续 ${GMAIL_FALLBACK_AFTER} 次未发现新邮件,开始回退到首封匹配邮件`, 'warn');
  570. }
  571. if (attempt < maxAttempts) {
  572. await sleep(intervalMs);
  573. }
  574. }
  575. throw new Error(
  576. `${(maxAttempts * intervalMs / 1000).toFixed(0)} 秒后仍未在 Gmail 中找到匹配邮件。请手动检查 Gmail 收件箱。`
  577. );
  578. }
  579. }