gmail-mail.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604
  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 extractEmails(text) {
  68. const matches = String(text || '').match(/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/ig) || [];
  69. return [...new Set(matches.map((item) => item.toLowerCase()))];
  70. }
  71. function emailMatchesTarget(candidate, targetEmail) {
  72. const normalizedCandidate = String(candidate || '').trim().toLowerCase();
  73. const normalizedTarget = String(targetEmail || '').trim().toLowerCase();
  74. return Boolean(normalizedCandidate && normalizedTarget && normalizedCandidate === normalizedTarget);
  75. }
  76. function getTargetEmailMatchState(text, targetEmail) {
  77. const normalizedTarget = String(targetEmail || '').trim().toLowerCase();
  78. if (!normalizedTarget) {
  79. return { matches: true, hasExplicitEmail: false };
  80. }
  81. const normalizedText = String(text || '').toLowerCase();
  82. if (normalizedText.includes(normalizedTarget)) {
  83. return { matches: true, hasExplicitEmail: true };
  84. }
  85. const atIndex = normalizedTarget.indexOf('@');
  86. if (atIndex > 0) {
  87. const encodedTarget = `${normalizedTarget.slice(0, atIndex)}=${normalizedTarget.slice(atIndex + 1)}`;
  88. if (normalizedText.includes(encodedTarget)) {
  89. return { matches: true, hasExplicitEmail: true };
  90. }
  91. }
  92. const emails = extractEmails(text);
  93. if (!emails.length) {
  94. return { matches: false, hasExplicitEmail: false };
  95. }
  96. return {
  97. matches: emails.some((email) => emailMatchesTarget(email, normalizedTarget)),
  98. hasExplicitEmail: true,
  99. };
  100. }
  101. const MONTH_INDEX_MAP = {
  102. jan: 0,
  103. feb: 1,
  104. mar: 2,
  105. apr: 3,
  106. may: 4,
  107. jun: 5,
  108. jul: 6,
  109. aug: 7,
  110. sep: 8,
  111. oct: 9,
  112. nov: 10,
  113. dec: 11,
  114. };
  115. function parseGmailTimestampText(rawText) {
  116. const text = normalizeText(rawText);
  117. if (!text) return null;
  118. const parsedNative = Date.parse(text);
  119. if (Number.isFinite(parsedNative)) {
  120. return parsedNative;
  121. }
  122. let match = text.match(/(\d{4})[年/-](\d{1,2})[月/-](\d{1,2})日?\s+(\d{1,2}):(\d{2})(?:\s*([AP]M))?/i);
  123. if (match) {
  124. const [, year, month, day, hourText, minute, meridiem] = match;
  125. let hour = Number(hourText);
  126. if (/pm/i.test(meridiem) && hour < 12) hour += 12;
  127. if (/am/i.test(meridiem) && hour === 12) hour = 0;
  128. return new Date(Number(year), Number(month) - 1, Number(day), hour, Number(minute), 0, 0).getTime();
  129. }
  130. 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);
  131. if (match) {
  132. const [, monthText, day, year, hourText, minute, meridiem] = match;
  133. const month = MONTH_INDEX_MAP[monthText.slice(0, 3).toLowerCase()];
  134. if (month !== undefined) {
  135. let hour = Number(hourText);
  136. if (/pm/i.test(meridiem) && hour < 12) hour += 12;
  137. if (/am/i.test(meridiem) && hour === 12) hour = 0;
  138. return new Date(Number(year), month, Number(day), hour, Number(minute), 0, 0).getTime();
  139. }
  140. }
  141. match = text.match(/今天\s*(\d{1,2}):(\d{2})/);
  142. if (match) {
  143. const now = new Date();
  144. return new Date(now.getFullYear(), now.getMonth(), now.getDate(), Number(match[1]), Number(match[2]), 0, 0).getTime();
  145. }
  146. match = text.match(/昨天\s*(\d{1,2}):(\d{2})/);
  147. if (match) {
  148. const now = new Date();
  149. now.setDate(now.getDate() - 1);
  150. return new Date(now.getFullYear(), now.getMonth(), now.getDate(), Number(match[1]), Number(match[2]), 0, 0).getTime();
  151. }
  152. match = text.match(/^(\d{1,2}):(\d{2})$/);
  153. if (match) {
  154. const now = new Date();
  155. return new Date(now.getFullYear(), now.getMonth(), now.getDate(), Number(match[1]), Number(match[2]), 0, 0).getTime();
  156. }
  157. return null;
  158. }
  159. function extractVerificationCode(text) {
  160. const normalized = String(text || '');
  161. const cnMatch = normalized.match(/(?:验证码|代码)[^0-9]{0,16}(\d{6})/i);
  162. if (cnMatch) return cnMatch[1];
  163. 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);
  164. if (enMatch) return enMatch[1];
  165. const plainMatch = normalized.match(/\b(\d{6})\b/);
  166. if (plainMatch) return plainMatch[1];
  167. return null;
  168. }
  169. function findInboxLink() {
  170. const selectors = [
  171. 'a[href*="#inbox"]',
  172. 'a[aria-label*="收件箱"]',
  173. 'a[aria-label*="Inbox"]',
  174. ];
  175. for (const selector of selectors) {
  176. const candidates = Array.from(document.querySelectorAll(selector));
  177. const visible = candidates.find(isVisibleElement);
  178. if (visible) return visible;
  179. if (candidates[0]) return candidates[0];
  180. }
  181. return Array.from(document.querySelectorAll('a, [role="link"]')).find((element) => {
  182. const text = normalizeText(
  183. element.getAttribute('aria-label')
  184. || element.getAttribute('title')
  185. || element.textContent
  186. );
  187. return /收件箱|Inbox/i.test(text);
  188. }) || null;
  189. }
  190. function findRefreshButton() {
  191. const selectors = [
  192. 'div[role="button"][data-tooltip="刷新"]',
  193. 'div[role="button"][aria-label="刷新"]',
  194. 'div[role="button"][data-tooltip*="刷新"]',
  195. 'div[role="button"][aria-label*="刷新"]',
  196. 'div[role="button"][data-tooltip="Refresh"]',
  197. 'div[role="button"][aria-label="Refresh"]',
  198. 'div[role="button"][data-tooltip*="Refresh"]',
  199. 'div[role="button"][aria-label*="Refresh"]',
  200. 'div[act="20"][role="button"]',
  201. 'div.asf.T-I-J3.J-J5-Ji',
  202. ];
  203. for (const selector of selectors) {
  204. const matched = document.querySelector(selector);
  205. const button = matched?.closest?.('[role="button"]') || matched;
  206. if (button && isVisibleElement(button)) {
  207. return button;
  208. }
  209. }
  210. return Array.from(document.querySelectorAll('div[role="button"], button')).find((element) => {
  211. const text = normalizeText(
  212. element.getAttribute('aria-label')
  213. || element.getAttribute('data-tooltip')
  214. || element.getAttribute('title')
  215. || element.textContent
  216. );
  217. return /刷新|Refresh/i.test(text);
  218. }) || null;
  219. }
  220. function collectThreadRows() {
  221. const candidates = [
  222. ...document.querySelectorAll('tr.zA'),
  223. ...document.querySelectorAll('tr[role="row"]'),
  224. ];
  225. const rows = [];
  226. const seenRows = new Set();
  227. candidates.forEach((row) => {
  228. if (!row || seenRows.has(row)) return;
  229. seenRows.add(row);
  230. if (!isDisplayed(row)) return;
  231. const text = normalizeText(row.textContent || row.innerText || '');
  232. if (!text) return;
  233. if (
  234. row.matches('tr.zA')
  235. || row.querySelector('.bog, .y6, .y2, .afn, [data-thread-id], [data-legacy-thread-id], [data-legacy-last-message-id]')
  236. || /openai|chatgpt|verify|verification|code|验证码/i.test(text)
  237. ) {
  238. rows.push(row);
  239. }
  240. });
  241. return rows;
  242. }
  243. function getRowPreviewText(row) {
  244. const sender = normalizeText(
  245. row.querySelector('.zF, .yP, span[email], [email]')?.textContent
  246. || row.querySelector('[email]')?.getAttribute?.('email')
  247. || ''
  248. );
  249. const subject = normalizeText(
  250. row.querySelector('.bog [data-thread-id], .bog [data-legacy-thread-id], .bog, .y6, .bqe')?.textContent
  251. || ''
  252. );
  253. const digest = normalizeText(
  254. row.querySelector('.y2, .afn, .a4W, .bog + .y2')?.textContent
  255. || ''
  256. );
  257. const timeText = normalizeText(
  258. row.querySelector('td.xW span')?.getAttribute?.('title')
  259. || row.querySelector('td.xW span, td.xW time')?.getAttribute?.('title')
  260. || row.querySelector('td.xW span, td.xW time')?.textContent
  261. || ''
  262. );
  263. const fullText = normalizeText(row.textContent || row.innerText || '');
  264. return {
  265. sender,
  266. subject,
  267. digest,
  268. timeText,
  269. fullText,
  270. combinedText: normalizeText([sender, subject, digest, timeText, fullText].filter(Boolean).join(' ')),
  271. };
  272. }
  273. function getRowTimestamp(row) {
  274. const timeCell = row.querySelector('td.xW span, td.xW time, td.xW [title]');
  275. const candidates = [
  276. timeCell?.getAttribute?.('title'),
  277. timeCell?.getAttribute?.('aria-label'),
  278. timeCell?.textContent,
  279. ].filter(Boolean);
  280. for (const candidate of candidates) {
  281. const parsed = parseGmailTimestampText(candidate);
  282. if (parsed) return parsed;
  283. }
  284. return null;
  285. }
  286. function getRowFingerprint(row, index = 0) {
  287. const marker = row.querySelector('[data-thread-id], [data-legacy-thread-id], [data-legacy-last-message-id]');
  288. const stableId = row.getAttribute('data-thread-id')
  289. || row.getAttribute('data-legacy-thread-id')
  290. || row.getAttribute('data-legacy-last-message-id')
  291. || marker?.getAttribute?.('data-thread-id')
  292. || marker?.getAttribute?.('data-legacy-thread-id')
  293. || marker?.getAttribute?.('data-legacy-last-message-id')
  294. || row.getAttribute('id')
  295. || `row-${index}`;
  296. const preview = getRowPreviewText(row);
  297. return `${stableId}::${preview.subject}::${preview.timeText}`.slice(0, 300);
  298. }
  299. function getCurrentMailIds(rows = []) {
  300. const ids = new Set();
  301. const sourceRows = rows.length ? rows : collectThreadRows();
  302. sourceRows.forEach((row, index) => {
  303. ids.add(getRowFingerprint(row, index));
  304. });
  305. return ids;
  306. }
  307. function rowMatchesFilters(preview, senderFilters, subjectFilters) {
  308. const senderText = normalizeText(preview.sender).toLowerCase();
  309. const subjectText = normalizeText(preview.subject).toLowerCase();
  310. const combinedText = normalizeText(preview.combinedText).toLowerCase();
  311. const senderMatch = senderFilters.some((filter) => {
  312. const value = String(filter || '').toLowerCase();
  313. return value && (senderText.includes(value) || combinedText.includes(value));
  314. });
  315. const subjectMatch = subjectFilters.some((filter) => {
  316. const value = String(filter || '').toLowerCase();
  317. return value && (subjectText.includes(value) || combinedText.includes(value));
  318. });
  319. return senderMatch || subjectMatch;
  320. }
  321. async function ensureInboxReady(step) {
  322. if (!/#inbox/i.test(location.href)) {
  323. const inboxLink = findInboxLink();
  324. if (inboxLink) {
  325. simulateClick(inboxLink);
  326. await sleep(800);
  327. log(`步骤 ${step}:已切回 Gmail 收件箱。`);
  328. } else {
  329. location.hash = '#inbox';
  330. await sleep(800);
  331. }
  332. }
  333. for (let i = 0; i < 20; i++) {
  334. const rows = collectThreadRows();
  335. if (rows.length > 0) {
  336. return rows;
  337. }
  338. await sleep(400);
  339. }
  340. return [];
  341. }
  342. async function refreshInbox(step) {
  343. const refreshButton = findRefreshButton();
  344. if (refreshButton) {
  345. simulateClick(refreshButton);
  346. log(`步骤 ${step}:已点击 Gmail 刷新。`);
  347. await sleep(1500);
  348. return;
  349. }
  350. const inboxLink = findInboxLink();
  351. if (inboxLink) {
  352. simulateClick(inboxLink);
  353. log(`步骤 ${step}:未找到刷新按钮,已重新进入收件箱。`);
  354. await sleep(1200);
  355. return;
  356. }
  357. location.reload();
  358. log(`步骤 ${step}:未找到刷新按钮,已直接刷新页面。`);
  359. await sleep(2500);
  360. }
  361. async function returnToInbox() {
  362. if (/#inbox/i.test(location.href) && collectThreadRows().length > 0) {
  363. return;
  364. }
  365. const inboxLink = findInboxLink();
  366. if (inboxLink) {
  367. simulateClick(inboxLink);
  368. } else {
  369. location.hash = '#inbox';
  370. }
  371. for (let i = 0; i < 20; i++) {
  372. if (collectThreadRows().length > 0) {
  373. return;
  374. }
  375. await sleep(250);
  376. }
  377. }
  378. async function openRowAndGetMessageText(row) {
  379. simulateClick(row);
  380. for (let i = 0; i < 20; i++) {
  381. const messageContainer = document.querySelector('div[role="main"] .a3s, div[role="main"] [data-message-id], h2[data-thread-perm-id]');
  382. if (messageContainer || !/#inbox/i.test(location.href)) {
  383. break;
  384. }
  385. await sleep(250);
  386. }
  387. await sleep(900);
  388. const main = document.querySelector('div[role="main"]');
  389. const text = normalizeText(main?.innerText || document.body?.innerText || document.body?.textContent || '');
  390. await returnToInbox();
  391. return text;
  392. }
  393. async function handlePollEmail(step, payload) {
  394. const {
  395. senderFilters = [],
  396. subjectFilters = [],
  397. maxAttempts = 5,
  398. intervalMs = 3000,
  399. filterAfterTimestamp = 0,
  400. excludeCodes = [],
  401. targetEmail = '',
  402. } = payload || {};
  403. const excludedCodeSet = new Set(excludeCodes.filter(Boolean));
  404. const filterAfterMinute = normalizeMinuteTimestamp(Number(filterAfterTimestamp) || 0);
  405. log(`步骤 ${step}:开始轮询 Gmail(最多 ${maxAttempts} 次)`);
  406. if (filterAfterMinute) {
  407. log(`步骤 ${step}:仅尝试 ${new Date(filterAfterMinute).toLocaleString('zh-CN', { hour12: false })} 及之后时间的邮件。`);
  408. }
  409. let initialRows = await ensureInboxReady(step);
  410. if (!initialRows.length) {
  411. await refreshInbox(step);
  412. initialRows = await ensureInboxReady(step);
  413. }
  414. if (!initialRows.length) {
  415. throw new Error('Gmail 收件箱列表未加载完成,请确认当前已打开 Gmail 收件箱。');
  416. }
  417. const existingMailIds = getCurrentMailIds(initialRows);
  418. log(`步骤 ${step}:已记录当前 ${existingMailIds.size} 封旧邮件快照`);
  419. for (let attempt = 1; attempt <= maxAttempts; attempt++) {
  420. log(`步骤 ${step}:正在轮询 Gmail,第 ${attempt}/${maxAttempts} 次`);
  421. if (attempt > 1) {
  422. await refreshInbox(step);
  423. }
  424. const rows = collectThreadRows();
  425. const useFallback = attempt > GMAIL_FALLBACK_AFTER;
  426. for (let index = 0; index < rows.length; index++) {
  427. const row = rows[index];
  428. const rowId = getRowFingerprint(row, index);
  429. const rowTimestamp = getRowTimestamp(row);
  430. const rowMinute = normalizeMinuteTimestamp(rowTimestamp || 0);
  431. const passesTimeFilter = !filterAfterMinute || (rowMinute && rowMinute >= filterAfterMinute);
  432. const shouldBypassOldSnapshot = Boolean(filterAfterMinute && passesTimeFilter && rowMinute > 0);
  433. if (!passesTimeFilter) {
  434. continue;
  435. }
  436. if (!useFallback && !shouldBypassOldSnapshot && existingMailIds.has(rowId)) {
  437. continue;
  438. }
  439. const preview = getRowPreviewText(row);
  440. if (!rowMatchesFilters(preview, senderFilters, subjectFilters)) {
  441. continue;
  442. }
  443. const previewTargetState = getTargetEmailMatchState(preview.combinedText, targetEmail);
  444. const previewEmails = extractEmails(preview.combinedText);
  445. if (targetEmail && previewEmails.length > 0 && !previewTargetState.matches) {
  446. continue;
  447. }
  448. const previewCode = extractVerificationCode(preview.combinedText);
  449. if (previewCode && previewTargetState.matches) {
  450. if (excludedCodeSet.has(previewCode)) {
  451. log(`步骤 ${step}:跳过排除的验证码:${previewCode}`, 'info');
  452. continue;
  453. }
  454. if (seenCodes.has(previewCode)) {
  455. log(`步骤 ${step}:跳过已处理过的验证码:${previewCode}`, 'info');
  456. continue;
  457. }
  458. seenCodes.add(previewCode);
  459. persistSeenCodes();
  460. const source = useFallback && existingMailIds.has(rowId) ? '回退匹配邮件' : '新邮件';
  461. const timeLabel = rowTimestamp ? `,时间:${new Date(rowTimestamp).toLocaleString('zh-CN', { hour12: false })}` : '';
  462. log(`步骤 ${step}:已在 Gmail 找到验证码:${previewCode}(来源:${source}${timeLabel})`, 'ok');
  463. return {
  464. ok: true,
  465. code: previewCode,
  466. emailTimestamp: Date.now(),
  467. mailId: rowId,
  468. };
  469. }
  470. const openedText = await openRowAndGetMessageText(row);
  471. const openedTargetState = getTargetEmailMatchState(openedText, targetEmail);
  472. if (targetEmail && openedTargetState.hasExplicitEmail && !openedTargetState.matches) {
  473. continue;
  474. }
  475. const bodyCode = extractVerificationCode(openedText);
  476. if (!bodyCode) {
  477. continue;
  478. }
  479. if (excludedCodeSet.has(bodyCode)) {
  480. log(`步骤 ${step}:跳过排除的验证码:${bodyCode}`, 'info');
  481. continue;
  482. }
  483. if (seenCodes.has(bodyCode)) {
  484. log(`步骤 ${step}:跳过已处理过的验证码:${bodyCode}`, 'info');
  485. continue;
  486. }
  487. seenCodes.add(bodyCode);
  488. persistSeenCodes();
  489. const source = useFallback && existingMailIds.has(rowId) ? '回退匹配邮件正文' : '新邮件正文';
  490. const timeLabel = rowTimestamp ? `,时间:${new Date(rowTimestamp).toLocaleString('zh-CN', { hour12: false })}` : '';
  491. log(`步骤 ${step}:已在 Gmail 正文中找到验证码:${bodyCode}(来源:${source}${timeLabel})`, 'ok');
  492. return {
  493. ok: true,
  494. code: bodyCode,
  495. emailTimestamp: Date.now(),
  496. mailId: rowId,
  497. };
  498. }
  499. if (attempt === GMAIL_FALLBACK_AFTER + 1) {
  500. log(`步骤 ${step}:连续 ${GMAIL_FALLBACK_AFTER} 次未发现新邮件,开始回退到首封匹配邮件`, 'warn');
  501. }
  502. if (attempt < maxAttempts) {
  503. await sleep(intervalMs);
  504. }
  505. }
  506. throw new Error(
  507. `${(maxAttempts * intervalMs / 1000).toFixed(0)} 秒后仍未在 Gmail 中找到匹配邮件。请手动检查 Gmail 收件箱。`
  508. );
  509. }
  510. }