gmail-mail.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  1. // content/gmail-mail.js — Content script for Gmail inbox polling (steps 4, 7)
  2. // Injected on: mail.google.com
  3. const GMAIL_PREFIX = '[MultiPage:gmail-mail]';
  4. const isTopFrame = window === window.top;
  5. console.log(GMAIL_PREFIX, 'Content script loaded on', location.href, 'frame:', isTopFrame ? 'top' : 'child');
  6. if (isTopFrame) {
  7. reportReady();
  8. }
  9. chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  10. if (message.type === 'POLL_EMAIL') {
  11. if (!isTopFrame) {
  12. sendResponse({ ok: false, reason: 'wrong-frame' });
  13. return;
  14. }
  15. resetStopState();
  16. handlePollEmail(message.step, message.payload).then(result => {
  17. sendResponse(result);
  18. }).catch(err => {
  19. if (isStopError(err)) {
  20. log(`Step ${message.step}: Stopped by user.`, 'warn');
  21. sendResponse({ stopped: true, error: err.message });
  22. return;
  23. }
  24. reportError(message.step, err.message);
  25. sendResponse({ error: err.message });
  26. });
  27. return true;
  28. }
  29. });
  30. function getInboxRows() {
  31. return Array.from(document.querySelectorAll('tr.zA'));
  32. }
  33. function getRowId(row, index = 0) {
  34. return row.getAttribute('data-legacy-message-id')
  35. || row.getAttribute('data-legacy-thread-id')
  36. || row.dataset.threadPermId
  37. || row.id
  38. || `gmail-row-${index}`;
  39. }
  40. function getRowText(row) {
  41. return [
  42. row.getAttribute('aria-label') || '',
  43. row.textContent || '',
  44. row.querySelector('[email]')?.getAttribute('email') || '',
  45. row.querySelector('[data-hovercard-id]')?.getAttribute('data-hovercard-id') || '',
  46. row.querySelector('.yP')?.getAttribute('email') || '',
  47. row.querySelector('.bA4 span')?.textContent || '',
  48. row.querySelector('.bog')?.textContent || '',
  49. row.querySelector('.y2')?.textContent || '',
  50. ].join(' ').replace(/\s+/g, ' ').trim();
  51. }
  52. function extractVerificationCode(text) {
  53. const matchCn = text.match(/(?:代码为|验证码[^0-9]*?)[\s::]*(\d{6})/);
  54. if (matchCn) return matchCn[1];
  55. const matchEn = text.match(/code[:\s]+is[:\s]+(\d{6})|code[:\s]+(\d{6})/i);
  56. if (matchEn) return matchEn[1] || matchEn[2];
  57. const match6 = text.match(/\b(\d{6})\b/);
  58. if (match6) return match6[1];
  59. return null;
  60. }
  61. function snapshotInboxState() {
  62. const snapshot = new Map();
  63. getInboxRows().forEach((row, index) => {
  64. const id = getRowId(row, index);
  65. snapshot.set(id, {
  66. text: getRowText(row),
  67. unread: isUnreadRow(row),
  68. });
  69. });
  70. return snapshot;
  71. }
  72. async function applyTargetSearch(targetEmail) {
  73. if (!targetEmail) return;
  74. const searchInput = document.querySelector('input[placeholder*="Search mail" i], input[aria-label*="Search mail" i], input[placeholder*="搜索邮件"], input[aria-label*="搜索邮件"]');
  75. if (!searchInput) return;
  76. const query = `to:${targetEmail}`;
  77. if ((searchInput.value || '').trim() === query) return;
  78. fillInput(searchInput, query);
  79. await sleep(200);
  80. searchInput.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', code: 'Enter', bubbles: true }));
  81. searchInput.dispatchEvent(new KeyboardEvent('keyup', { key: 'Enter', code: 'Enter', bubbles: true }));
  82. await sleep(1500);
  83. log(`Applied Gmail search filter: ${query}`);
  84. }
  85. function getOpenedMessageText() {
  86. const emailAttrs = Array.from(document.querySelectorAll('[email]'))
  87. .map(el => el.getAttribute('email') || '')
  88. .join(' ');
  89. const hovercardIds = Array.from(document.querySelectorAll('[data-hovercard-id]'))
  90. .map(el => el.getAttribute('data-hovercard-id') || '')
  91. .join(' ');
  92. const bodyText = document.body?.innerText || '';
  93. return `${bodyText}\n${emailAttrs}\n${hovercardIds}`.toLowerCase();
  94. }
  95. async function openRowAndReadMessageText(row) {
  96. const clickable = row.querySelector('.bog, .y6, td, div[role="link"]') || row;
  97. simulateClick(clickable);
  98. const start = Date.now();
  99. while (Date.now() - start < 12000) {
  100. const opened = document.querySelector('h2.hP, div[role="main"] .ii.gt');
  101. if (opened) {
  102. await sleep(800);
  103. return getOpenedMessageText();
  104. }
  105. await sleep(200);
  106. }
  107. return '';
  108. }
  109. async function returnToInboxView(targetEmail = '') {
  110. history.back();
  111. const start = Date.now();
  112. while (Date.now() - start < 10000) {
  113. if (getInboxRows().length > 0) {
  114. await sleep(400);
  115. if (targetEmail) {
  116. await applyTargetSearch(targetEmail);
  117. }
  118. return;
  119. }
  120. await sleep(200);
  121. }
  122. }
  123. async function refreshInbox() {
  124. const refreshBtn = document.querySelector('div[role="button"][data-tooltip="Refresh"], div[role="button"][aria-label*="Refresh"], div[role="button"][aria-label*="刷新"]');
  125. if (refreshBtn) {
  126. simulateClick(refreshBtn);
  127. console.log(GMAIL_PREFIX, 'Clicked refresh button');
  128. await sleep(1000);
  129. return;
  130. }
  131. const inboxLink = Array.from(document.querySelectorAll('a[title], a[aria-label], div[role="link"]'))
  132. .find(el => /inbox|收件箱/i.test((el.getAttribute('title') || '') + ' ' + (el.getAttribute('aria-label') || '') + ' ' + (el.textContent || '')));
  133. if (inboxLink) {
  134. simulateClick(inboxLink);
  135. console.log(GMAIL_PREFIX, 'Clicked inbox link');
  136. await sleep(1000);
  137. }
  138. }
  139. function normalizeGmailAlias(email) {
  140. const lower = String(email || '').trim().toLowerCase();
  141. const match = lower.match(/^([^@+]+)(?:\+([^@]+))?@gmail\.com$/i);
  142. if (!match) return { full: lower, base: lower, plus: '' };
  143. return {
  144. full: lower,
  145. base: `${match[1]}@gmail.com`,
  146. plus: match[2] || '',
  147. };
  148. }
  149. function rowMatchesTargetEmail(combinedText, targetEmail) {
  150. if (!targetEmail) return true;
  151. const text = String(combinedText || '').toLowerCase();
  152. const target = normalizeGmailAlias(targetEmail);
  153. if (text.includes(target.full)) return true;
  154. if (target.plus && text.includes(`+${target.plus}`)) return true;
  155. return false;
  156. }
  157. function isUnreadRow(row) {
  158. return row?.classList?.contains('zE');
  159. }
  160. async function handlePollEmail(step, payload) {
  161. const { senderFilters, subjectFilters, maxAttempts, intervalMs, usedMailIds, usedCodes, targetEmail } = payload;
  162. const usedMailIdSet = new Set((usedMailIds || []).map(String));
  163. const usedCodeSet = new Set(usedCodes || []);
  164. log(`Step ${step}: Starting email poll on Gmail (max ${maxAttempts} attempts, every ${intervalMs / 1000}s)`);
  165. try {
  166. await waitForElement('tr.zA, div[role="main"] table', 15000);
  167. log(`Step ${step}: Gmail inbox loaded`);
  168. } catch {
  169. throw new Error('Gmail inbox did not load. Please open https://mail.google.com/ and ensure you are logged in.');
  170. }
  171. await applyTargetSearch(targetEmail);
  172. const existingInboxState = snapshotInboxState();
  173. log(`Step ${step}: Snapshotted ${existingInboxState.size} existing Gmail emails`);
  174. const FALLBACK_AFTER = 6;
  175. for (let attempt = 1; attempt <= maxAttempts; attempt++) {
  176. log(`Polling Gmail... attempt ${attempt}/${maxAttempts}`);
  177. if (attempt > 1) {
  178. await refreshInbox();
  179. await sleep(1200);
  180. }
  181. const rows = getInboxRows();
  182. const useFallback = attempt > FALLBACK_AFTER;
  183. for (let index = 0; index < rows.length; index++) {
  184. const row = rows[index];
  185. const mailId = String(getRowId(row, index));
  186. const previousState = existingInboxState.get(mailId);
  187. const isNewRow = !previousState;
  188. if (usedMailIdSet.has(mailId)) continue;
  189. const combinedText = getRowText(row);
  190. const lower = combinedText.toLowerCase();
  191. const targetMatch = rowMatchesTargetEmail(combinedText, targetEmail);
  192. const senderMatch = senderFilters.some(f => lower.includes(f.toLowerCase()));
  193. const subjectMatch = subjectFilters.some(f => lower.includes(f.toLowerCase()));
  194. const code = extractVerificationCode(combinedText);
  195. const unread = isUnreadRow(row);
  196. const rowStateChanged = Boolean(previousState) && (
  197. previousState.text !== combinedText
  198. || (!previousState.unread && unread)
  199. );
  200. if (!useFallback && !isNewRow && !rowStateChanged) continue;
  201. if (rowStateChanged) {
  202. log(`Step ${step}: Gmail thread updated for ${mailId}, re-checking row`, 'info');
  203. }
  204. if ((senderMatch || subjectMatch || code) && code && (targetMatch || isNewRow)) {
  205. if (usedCodeSet.has(code)) {
  206. log(`Step ${step}: Skipping already-used code ${code} (mailId: ${mailId})`);
  207. continue;
  208. }
  209. const source = targetMatch
  210. ? (useFallback && previousState ? 'fallback-first-match' : (isNewRow ? 'new' : 'updated-thread-match'))
  211. : (isNewRow ? 'new-row-match' : 'updated-thread-match');
  212. log(`Step ${step}: Code found: ${code} (${source}, row: ${combinedText.slice(0, 60)})`, 'ok');
  213. return { ok: true, code, emailTimestamp: Date.now(), mailId };
  214. }
  215. if (code && !targetMatch && useFallback) {
  216. const openedMessageText = await openRowAndReadMessageText(row);
  217. const detailMatched = rowMatchesTargetEmail(openedMessageText, targetEmail);
  218. if (detailMatched) {
  219. if (usedCodeSet.has(code)) {
  220. log(`Step ${step}: Skipping already-used code ${code} (mailId: ${mailId})`);
  221. await returnToInboxView(targetEmail);
  222. continue;
  223. }
  224. const source = useFallback && previousState ? 'fallback-opened-match' : 'opened-match';
  225. log(`Step ${step}: Code found: ${code} (${source}, target alias matched in opened email)`, 'ok');
  226. return { ok: true, code, emailTimestamp: Date.now(), mailId };
  227. }
  228. // As a last resort in fallback mode, trust unread OpenAI verification emails
  229. // that appeared near the top of the filtered result set.
  230. if (unread && (senderMatch || subjectMatch)) {
  231. if (usedCodeSet.has(code)) {
  232. log(`Step ${step}: Skipping already-used code ${code} (mailId: ${mailId})`);
  233. await returnToInboxView(targetEmail);
  234. continue;
  235. }
  236. log(`Step ${step}: Code found: ${code} (fallback-unread-match, alias hidden in Gmail detail)`, 'ok');
  237. return { ok: true, code, emailTimestamp: Date.now(), mailId };
  238. }
  239. await returnToInboxView(targetEmail);
  240. log(`Step ${step}: Skipping Gmail code ${code} because neither row nor opened email matched target alias ${targetEmail}`, 'info');
  241. }
  242. }
  243. if (attempt === FALLBACK_AFTER + 1) {
  244. log(`Step ${step}: No new Gmail emails after ${FALLBACK_AFTER} attempts, falling back to first matching email`, 'warn');
  245. }
  246. if (attempt < maxAttempts) {
  247. await sleep(intervalMs);
  248. }
  249. }
  250. throw new Error(
  251. `No matching verification email found on Gmail after ${(maxAttempts * intervalMs / 1000).toFixed(0)}s. ` +
  252. 'Check Gmail manually and make sure the inbox tab is open.'
  253. );
  254. }