gmail-mail.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577
  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. function findRefreshButton() {
  175. const selectors = [
  176. 'div[role="button"][data-tooltip="刷新"]',
  177. 'div[role="button"][aria-label="刷新"]',
  178. 'div[role="button"][data-tooltip*="刷新"]',
  179. 'div[role="button"][aria-label*="刷新"]',
  180. 'div[role="button"][data-tooltip="Refresh"]',
  181. 'div[role="button"][aria-label="Refresh"]',
  182. 'div[role="button"][data-tooltip*="Refresh"]',
  183. 'div[role="button"][aria-label*="Refresh"]',
  184. 'div[act="20"][role="button"]',
  185. 'div.asf.T-I-J3.J-J5-Ji',
  186. ];
  187. for (const selector of selectors) {
  188. const matched = document.querySelector(selector);
  189. const button = matched?.closest?.('[role="button"]') || matched;
  190. if (button && isVisibleElement(button)) {
  191. return button;
  192. }
  193. }
  194. return Array.from(document.querySelectorAll('div[role="button"], button')).find((element) => {
  195. const text = normalizeText(
  196. element.getAttribute('aria-label')
  197. || element.getAttribute('data-tooltip')
  198. || element.getAttribute('title')
  199. || element.textContent
  200. );
  201. return /刷新|Refresh/i.test(text);
  202. }) || null;
  203. }
  204. function collectThreadRows() {
  205. const candidates = [
  206. ...document.querySelectorAll('tr.zA'),
  207. ...document.querySelectorAll('tr[role="row"]'),
  208. ];
  209. const rows = [];
  210. const seenRows = new Set();
  211. candidates.forEach((row) => {
  212. if (!row || seenRows.has(row)) return;
  213. seenRows.add(row);
  214. if (!isDisplayed(row)) return;
  215. const text = normalizeText(row.textContent || row.innerText || '');
  216. if (!text) return;
  217. if (
  218. row.matches('tr.zA')
  219. || row.querySelector('.bog, .y6, .y2, .afn, [data-thread-id], [data-legacy-thread-id], [data-legacy-last-message-id]')
  220. || /openai|chatgpt|verify|verification|code|验证码/i.test(text)
  221. ) {
  222. rows.push(row);
  223. }
  224. });
  225. return rows;
  226. }
  227. function getRowPreviewText(row) {
  228. const sender = normalizeText(
  229. row.querySelector('.zF, .yP, span[email], [email]')?.textContent
  230. || row.querySelector('[email]')?.getAttribute?.('email')
  231. || ''
  232. );
  233. const subject = normalizeText(
  234. row.querySelector('.bog [data-thread-id], .bog [data-legacy-thread-id], .bog, .y6, .bqe')?.textContent
  235. || ''
  236. );
  237. const digest = normalizeText(
  238. row.querySelector('.y2, .afn, .a4W, .bog + .y2')?.textContent
  239. || ''
  240. );
  241. const timeText = normalizeText(
  242. row.querySelector('td.xW span')?.getAttribute?.('title')
  243. || row.querySelector('td.xW span, td.xW time')?.getAttribute?.('title')
  244. || row.querySelector('td.xW span, td.xW time')?.textContent
  245. || ''
  246. );
  247. const fullText = normalizeText(row.textContent || row.innerText || '');
  248. return {
  249. sender,
  250. subject,
  251. digest,
  252. timeText,
  253. fullText,
  254. combinedText: normalizeText([sender, subject, digest, timeText, fullText].filter(Boolean).join(' ')),
  255. };
  256. }
  257. function getRowTimestamp(row) {
  258. const timeCell = row.querySelector('td.xW span, td.xW time, td.xW [title]');
  259. const candidates = [
  260. timeCell?.getAttribute?.('title'),
  261. timeCell?.getAttribute?.('aria-label'),
  262. timeCell?.textContent,
  263. ].filter(Boolean);
  264. for (const candidate of candidates) {
  265. const parsed = parseGmailTimestampText(candidate);
  266. if (parsed) return parsed;
  267. }
  268. return null;
  269. }
  270. function getRowFingerprint(row, index = 0) {
  271. const marker = row.querySelector('[data-thread-id], [data-legacy-thread-id], [data-legacy-last-message-id]');
  272. const stableId = row.getAttribute('data-thread-id')
  273. || row.getAttribute('data-legacy-thread-id')
  274. || row.getAttribute('data-legacy-last-message-id')
  275. || marker?.getAttribute?.('data-thread-id')
  276. || marker?.getAttribute?.('data-legacy-thread-id')
  277. || marker?.getAttribute?.('data-legacy-last-message-id')
  278. || row.getAttribute('id')
  279. || `row-${index}`;
  280. const preview = getRowPreviewText(row);
  281. return `${stableId}::${preview.subject}::${preview.timeText}`.slice(0, 300);
  282. }
  283. function getCurrentMailIds(rows = []) {
  284. const ids = new Set();
  285. const sourceRows = rows.length ? rows : collectThreadRows();
  286. sourceRows.forEach((row, index) => {
  287. ids.add(getRowFingerprint(row, index));
  288. });
  289. return ids;
  290. }
  291. function rowMatchesFilters(preview, senderFilters, subjectFilters) {
  292. const senderText = normalizeText(preview.sender).toLowerCase();
  293. const subjectText = normalizeText(preview.subject).toLowerCase();
  294. const combinedText = normalizeText(preview.combinedText).toLowerCase();
  295. const senderMatch = senderFilters.some((filter) => {
  296. const value = String(filter || '').toLowerCase();
  297. return value && (senderText.includes(value) || combinedText.includes(value));
  298. });
  299. const subjectMatch = subjectFilters.some((filter) => {
  300. const value = String(filter || '').toLowerCase();
  301. return value && (subjectText.includes(value) || combinedText.includes(value));
  302. });
  303. return senderMatch || subjectMatch;
  304. }
  305. async function ensureInboxReady(step) {
  306. if (!/#inbox/i.test(location.href)) {
  307. const inboxLink = findInboxLink();
  308. if (inboxLink) {
  309. simulateClick(inboxLink);
  310. await sleep(800);
  311. log(`步骤 ${step}:已切回 Gmail 收件箱。`);
  312. } else {
  313. location.hash = '#inbox';
  314. await sleep(800);
  315. }
  316. }
  317. for (let i = 0; i < 20; i++) {
  318. const rows = collectThreadRows();
  319. if (rows.length > 0) {
  320. return rows;
  321. }
  322. await sleep(400);
  323. }
  324. return [];
  325. }
  326. async function refreshInbox(step) {
  327. const refreshButton = findRefreshButton();
  328. if (refreshButton) {
  329. simulateClick(refreshButton);
  330. log(`步骤 ${step}:已点击 Gmail 刷新。`);
  331. await sleep(1500);
  332. return;
  333. }
  334. const inboxLink = findInboxLink();
  335. if (inboxLink) {
  336. simulateClick(inboxLink);
  337. log(`步骤 ${step}:未找到刷新按钮,已重新进入收件箱。`);
  338. await sleep(1200);
  339. return;
  340. }
  341. location.reload();
  342. log(`步骤 ${step}:未找到刷新按钮,已直接刷新页面。`);
  343. await sleep(2500);
  344. }
  345. async function returnToInbox() {
  346. if (/#inbox/i.test(location.href) && collectThreadRows().length > 0) {
  347. return;
  348. }
  349. const inboxLink = findInboxLink();
  350. if (inboxLink) {
  351. simulateClick(inboxLink);
  352. } else {
  353. location.hash = '#inbox';
  354. }
  355. for (let i = 0; i < 20; i++) {
  356. if (collectThreadRows().length > 0) {
  357. return;
  358. }
  359. await sleep(250);
  360. }
  361. }
  362. async function openRowAndGetMessageText(row) {
  363. simulateClick(row);
  364. for (let i = 0; i < 20; i++) {
  365. const messageContainer = document.querySelector('div[role="main"] .a3s, div[role="main"] [data-message-id], h2[data-thread-perm-id]');
  366. if (messageContainer || !/#inbox/i.test(location.href)) {
  367. break;
  368. }
  369. await sleep(250);
  370. }
  371. await sleep(900);
  372. const main = document.querySelector('div[role="main"]');
  373. const text = normalizeText(main?.innerText || document.body?.innerText || document.body?.textContent || '');
  374. await returnToInbox();
  375. return text;
  376. }
  377. async function handlePollEmail(step, payload) {
  378. const {
  379. senderFilters = [],
  380. subjectFilters = [],
  381. maxAttempts = 5,
  382. intervalMs = 3000,
  383. filterAfterTimestamp = 0,
  384. excludeCodes = [],
  385. targetEmail = '',
  386. } = payload || {};
  387. const excludedCodeSet = new Set(excludeCodes.filter(Boolean));
  388. const filterAfterMinute = normalizeMinuteTimestamp(Number(filterAfterTimestamp) || 0);
  389. log(`步骤 ${step}:开始轮询 Gmail(最多 ${maxAttempts} 次)`);
  390. if (filterAfterMinute) {
  391. log(`步骤 ${step}:仅尝试 ${new Date(filterAfterMinute).toLocaleString('zh-CN', { hour12: false })} 及之后时间的邮件。`);
  392. }
  393. let initialRows = await ensureInboxReady(step);
  394. if (!initialRows.length) {
  395. await refreshInbox(step);
  396. initialRows = await ensureInboxReady(step);
  397. }
  398. if (!initialRows.length) {
  399. throw new Error('Gmail 收件箱列表未加载完成,请确认当前已打开 Gmail 收件箱。');
  400. }
  401. const existingMailIds = getCurrentMailIds(initialRows);
  402. log(`步骤 ${step}:已记录当前 ${existingMailIds.size} 封旧邮件快照`);
  403. for (let attempt = 1; attempt <= maxAttempts; attempt++) {
  404. log(`步骤 ${step}:正在轮询 Gmail,第 ${attempt}/${maxAttempts} 次`);
  405. if (attempt > 1) {
  406. await refreshInbox(step);
  407. }
  408. const rows = collectThreadRows();
  409. const useFallback = attempt > GMAIL_FALLBACK_AFTER;
  410. for (let index = 0; index < rows.length; index++) {
  411. const row = rows[index];
  412. const rowId = getRowFingerprint(row, index);
  413. const rowTimestamp = getRowTimestamp(row);
  414. const rowMinute = normalizeMinuteTimestamp(rowTimestamp || 0);
  415. const passesTimeFilter = !filterAfterMinute || (rowMinute && rowMinute >= filterAfterMinute);
  416. const shouldBypassOldSnapshot = Boolean(filterAfterMinute && passesTimeFilter && rowMinute > 0);
  417. if (!passesTimeFilter) {
  418. continue;
  419. }
  420. if (!useFallback && !shouldBypassOldSnapshot && existingMailIds.has(rowId)) {
  421. continue;
  422. }
  423. const preview = getRowPreviewText(row);
  424. if (!rowMatchesFilters(preview, senderFilters, subjectFilters)) {
  425. continue;
  426. }
  427. const previewTargetState = getTargetEmailMatchState(preview.combinedText, targetEmail);
  428. const previewCode = extractVerificationCode(preview.combinedText);
  429. if (previewCode) {
  430. if (excludedCodeSet.has(previewCode)) {
  431. log(`步骤 ${step}:跳过排除的验证码:${previewCode}`, 'info');
  432. continue;
  433. }
  434. if (seenCodes.has(previewCode)) {
  435. log(`步骤 ${step}:跳过已处理过的验证码:${previewCode}`, 'info');
  436. continue;
  437. }
  438. seenCodes.add(previewCode);
  439. persistSeenCodes();
  440. const source = useFallback && existingMailIds.has(rowId) ? '回退匹配邮件' : '新邮件';
  441. const timeLabel = rowTimestamp ? `,时间:${new Date(rowTimestamp).toLocaleString('zh-CN', { hour12: false })}` : '';
  442. const targetLabel = previewTargetState.matches ? ',目标邮箱命中' : '';
  443. log(`步骤 ${step}:已在 Gmail 找到验证码:${previewCode}(来源:${source}${timeLabel}${targetLabel})`, 'ok');
  444. return {
  445. ok: true,
  446. code: previewCode,
  447. emailTimestamp: Date.now(),
  448. mailId: rowId,
  449. };
  450. }
  451. const openedText = await openRowAndGetMessageText(row);
  452. const openedTargetState = getTargetEmailMatchState(openedText, targetEmail);
  453. const bodyCode = extractVerificationCode(openedText);
  454. if (!bodyCode) {
  455. continue;
  456. }
  457. if (excludedCodeSet.has(bodyCode)) {
  458. log(`步骤 ${step}:跳过排除的验证码:${bodyCode}`, 'info');
  459. continue;
  460. }
  461. if (seenCodes.has(bodyCode)) {
  462. log(`步骤 ${step}:跳过已处理过的验证码:${bodyCode}`, 'info');
  463. continue;
  464. }
  465. seenCodes.add(bodyCode);
  466. persistSeenCodes();
  467. const source = useFallback && existingMailIds.has(rowId) ? '回退匹配邮件正文' : '新邮件正文';
  468. const timeLabel = rowTimestamp ? `,时间:${new Date(rowTimestamp).toLocaleString('zh-CN', { hour12: false })}` : '';
  469. const targetLabel = openedTargetState.matches ? ',目标邮箱命中' : '';
  470. log(`步骤 ${step}:已在 Gmail 正文中找到验证码:${bodyCode}(来源:${source}${timeLabel}${targetLabel})`, 'ok');
  471. return {
  472. ok: true,
  473. code: bodyCode,
  474. emailTimestamp: Date.now(),
  475. mailId: rowId,
  476. };
  477. }
  478. if (attempt === GMAIL_FALLBACK_AFTER + 1) {
  479. log(`步骤 ${step}:连续 ${GMAIL_FALLBACK_AFTER} 次未发现新邮件,开始回退到首封匹配邮件`, 'warn');
  480. }
  481. if (attempt < maxAttempts) {
  482. await sleep(intervalMs);
  483. }
  484. }
  485. throw new Error(
  486. `${(maxAttempts * intervalMs / 1000).toFixed(0)} 秒后仍未在 Gmail 中找到匹配邮件。请手动检查 Gmail 收件箱。`
  487. );
  488. }
  489. }