mail-2925.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489
  1. // content/mail-2925.js — Content script for 2925 Mail (steps 4, 7)
  2. // Injected dynamically on: 2925.com
  3. const MAIL2925_PREFIX = '[MultiPage:mail-2925]';
  4. const isTopFrame = window === window.top;
  5. console.log(MAIL2925_PREFIX, 'Content script loaded on', location.href, 'frame:', isTopFrame ? 'top' : 'child');
  6. if (!isTopFrame) {
  7. console.log(MAIL2925_PREFIX, 'Skipping child frame');
  8. } else {
  9. let seenCodes = new Set();
  10. async function loadSeenCodes() {
  11. try {
  12. const data = await chrome.storage.session.get('seen2925Codes');
  13. if (data.seen2925Codes && Array.isArray(data.seen2925Codes)) {
  14. seenCodes = new Set(data.seen2925Codes);
  15. console.log(MAIL2925_PREFIX, `Loaded ${seenCodes.size} previously seen codes`);
  16. }
  17. } catch (err) {
  18. console.warn(MAIL2925_PREFIX, 'Session storage unavailable, using in-memory seen codes:', err?.message || err);
  19. }
  20. }
  21. loadSeenCodes();
  22. async function persistSeenCodes() {
  23. try {
  24. await chrome.storage.session.set({ seen2925Codes: [...seenCodes] });
  25. } catch (err) {
  26. console.warn(MAIL2925_PREFIX, 'Could not persist seen codes, continuing in-memory only:', err?.message || err);
  27. }
  28. }
  29. chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  30. if (message.type === 'POLL_EMAIL') {
  31. resetStopState();
  32. handlePollEmail(message.step, message.payload).then(result => {
  33. sendResponse(result);
  34. }).catch(err => {
  35. if (isStopError(err)) {
  36. log(`步骤 ${message.step}:已被用户停止。`, 'warn');
  37. sendResponse({ stopped: true, error: err.message });
  38. return;
  39. }
  40. log(`步骤 ${message.step}:邮箱轮询失败:${err.message}`, 'warn');
  41. sendResponse({ error: err.message });
  42. });
  43. return true;
  44. }
  45. });
  46. const MAIL_ITEM_SELECTORS = [
  47. '.mail-item',
  48. '.letter-item',
  49. '[class*="mailItem"]',
  50. '[class*="mail-item"]',
  51. '[class*="MailItem"]',
  52. '.el-table__row',
  53. 'tr[class*="mail"]',
  54. '[class*="listItem"]',
  55. '[class*="list-item"]',
  56. 'li[class*="mail"]',
  57. ];
  58. const MAIL_REFRESH_SELECTOR = '[class*="refresh"], [title*="鍒锋柊"], [aria-label*="鍒锋柊"], [class*="Refresh"]';
  59. const MAIL_INBOX_SELECTORS = [
  60. 'a[href*="mailList"]',
  61. '[class*="inbox"]',
  62. '[class*="Inbox"]',
  63. '[title*="鏀朵欢绠?]',
  64. ];
  65. function findMailItems() {
  66. for (const selector of MAIL_ITEM_SELECTORS) {
  67. const items = document.querySelectorAll(selector);
  68. if (items.length > 0) {
  69. return Array.from(items);
  70. }
  71. }
  72. return [];
  73. }
  74. function findRefreshButton() {
  75. return document.querySelector(MAIL_REFRESH_SELECTOR);
  76. }
  77. function findInboxLink() {
  78. for (const selector of MAIL_INBOX_SELECTORS) {
  79. const node = document.querySelector(selector);
  80. if (node) {
  81. return node;
  82. }
  83. }
  84. return null;
  85. }
  86. function getMailItemText(item) {
  87. if (!item) return '';
  88. const contentCell = item.querySelector('td.content, .content, .mail-content');
  89. const titleEl = item.querySelector('.mail-content-title');
  90. const textEl = item.querySelector('.mail-content-text');
  91. return [
  92. titleEl?.getAttribute('title') || '',
  93. titleEl?.textContent || '',
  94. textEl?.textContent || '',
  95. contentCell?.textContent || '',
  96. item.textContent || '',
  97. ].join(' ');
  98. }
  99. function getMailItemTimeText(item) {
  100. const timeEl = item?.querySelector('.date-time-text, [class*="date-time"], [class*="time"], td.time');
  101. return (timeEl?.textContent || '').replace(/\s+/g, ' ').trim();
  102. }
  103. function normalizeMailIdentityPart(value) {
  104. return (value || '').replace(/\s+/g, ' ').trim().toLowerCase();
  105. }
  106. function getMailItemId(item, index = 0) {
  107. const candidates = [
  108. item?.getAttribute?.('data-id'),
  109. item?.dataset?.id,
  110. item?.getAttribute?.('data-mail-id'),
  111. item?.dataset?.mailId,
  112. item?.getAttribute?.('data-key'),
  113. item?.getAttribute?.('key'),
  114. ].filter(Boolean);
  115. if (candidates.length > 0) {
  116. return String(candidates[0]);
  117. }
  118. return [
  119. index,
  120. normalizeMailIdentityPart(getMailItemTimeText(item)),
  121. normalizeMailIdentityPart(getMailItemText(item)).slice(0, 240),
  122. ].join('|');
  123. }
  124. function getCurrentMailIds(items = []) {
  125. const ids = new Set();
  126. items.forEach((item, index) => {
  127. ids.add(getMailItemId(item, index));
  128. });
  129. return ids;
  130. }
  131. function normalizeMinuteTimestamp(timestamp) {
  132. if (!Number.isFinite(timestamp) || timestamp <= 0) return 0;
  133. const date = new Date(timestamp);
  134. date.setSeconds(0, 0);
  135. return date.getTime();
  136. }
  137. function matchesMailFilters(text, senderFilters, subjectFilters) {
  138. const lower = (text || '').toLowerCase();
  139. const senderMatch = senderFilters.some(filter => lower.includes(filter.toLowerCase()));
  140. const subjectMatch = subjectFilters.some(filter => lower.includes(filter.toLowerCase()));
  141. return senderMatch || subjectMatch;
  142. }
  143. function extractVerificationCode(text, strictChatGPTCodeOnly = false) {
  144. if (strictChatGPTCodeOnly) {
  145. const strictMatch = text.match(/your\s+chatgpt\s+code\s+is\s+(\d{6})/i);
  146. return strictMatch ? strictMatch[1] : null;
  147. }
  148. const matchCn = text.match(/(?:代码为|验证码[^0-9]*?)[\s::]*(\d{6})/);
  149. if (matchCn) return matchCn[1];
  150. const matchChatGPT = text.match(/your\s+chatgpt\s+code\s+is\s+(\d{6})/i);
  151. if (matchChatGPT) return matchChatGPT[1];
  152. const matchEn = text.match(/code[:\s]+is[:\s]+(\d{6})|code[:\s]+(\d{6})/i);
  153. if (matchEn) return matchEn[1] || matchEn[2];
  154. const match6 = text.match(/\b(\d{6})\b/);
  155. if (match6) return match6[1];
  156. return null;
  157. }
  158. function extractEmails(text) {
  159. const matches = text.match(/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/ig) || [];
  160. return [...new Set(matches.map(item => item.toLowerCase()))];
  161. }
  162. function emailMatchesTarget(candidate, targetEmail) {
  163. const normalizedCandidate = String(candidate || '').trim().toLowerCase();
  164. const normalizedTarget = String(targetEmail || '').trim().toLowerCase();
  165. return Boolean(normalizedCandidate && normalizedTarget && normalizedCandidate === normalizedTarget);
  166. }
  167. function getTargetEmailMatchState(text, targetEmail) {
  168. const normalizedTarget = String(targetEmail || '').trim().toLowerCase();
  169. if (!normalizedTarget) {
  170. return { matches: true, hasExplicitEmail: false };
  171. }
  172. const normalizedText = String(text || '').toLowerCase();
  173. if (normalizedText.includes(normalizedTarget)) {
  174. return { matches: true, hasExplicitEmail: true };
  175. }
  176. const atIndex = normalizedTarget.indexOf('@');
  177. if (atIndex > 0) {
  178. const encodedTarget = `${normalizedTarget.slice(0, atIndex)}=${normalizedTarget.slice(atIndex + 1)}`;
  179. if (normalizedText.includes(encodedTarget)) {
  180. return { matches: true, hasExplicitEmail: true };
  181. }
  182. }
  183. const emails = extractEmails(text);
  184. if (!emails.length) {
  185. return { matches: false, hasExplicitEmail: false };
  186. }
  187. return {
  188. matches: emails.some(email => emailMatchesTarget(email, normalizedTarget)),
  189. hasExplicitEmail: true,
  190. };
  191. }
  192. function parseMailItemTimestamp(item) {
  193. const timeText = getMailItemTimeText(item);
  194. if (!timeText) return null;
  195. const now = new Date();
  196. const date = new Date(now);
  197. let match = null;
  198. if (/刚刚/.test(timeText)) {
  199. return now.getTime();
  200. }
  201. match = timeText.match(/(\d+)\s*分(?:钟)?前/);
  202. if (match) {
  203. return now.getTime() - Number(match[1]) * 60 * 1000;
  204. }
  205. match = timeText.match(/(\d+)\s*秒前/);
  206. if (match) {
  207. return now.getTime() - Number(match[1]) * 1000;
  208. }
  209. match = timeText.match(/^(\d{1,2}):(\d{2})$/);
  210. if (match) {
  211. date.setHours(Number(match[1]), Number(match[2]), 0, 0);
  212. return date.getTime();
  213. }
  214. match = timeText.match(/今天\s*(\d{1,2}):(\d{2})/);
  215. if (match) {
  216. date.setHours(Number(match[1]), Number(match[2]), 0, 0);
  217. return date.getTime();
  218. }
  219. match = timeText.match(/昨天\s*(\d{1,2}):(\d{2})/);
  220. if (match) {
  221. date.setDate(date.getDate() - 1);
  222. date.setHours(Number(match[1]), Number(match[2]), 0, 0);
  223. return date.getTime();
  224. }
  225. match = timeText.match(/(\d{1,2})-(\d{1,2})\s*(\d{1,2}):(\d{2})/);
  226. if (match) {
  227. date.setMonth(Number(match[1]) - 1, Number(match[2]));
  228. date.setHours(Number(match[3]), Number(match[4]), 0, 0);
  229. return date.getTime();
  230. }
  231. match = timeText.match(/(\d{4})-(\d{1,2})-(\d{1,2})\s*(\d{1,2}):(\d{2})/);
  232. if (match) {
  233. return new Date(
  234. Number(match[1]),
  235. Number(match[2]) - 1,
  236. Number(match[3]),
  237. Number(match[4]),
  238. Number(match[5]),
  239. 0,
  240. 0
  241. ).getTime();
  242. }
  243. return null;
  244. }
  245. async function sleepRandom(minMs, maxMs = minMs) {
  246. const duration = Math.floor(Math.random() * (maxMs - minMs + 1)) + minMs;
  247. await sleep(duration);
  248. }
  249. async function returnToInbox() {
  250. if (findMailItems().length > 0) {
  251. return true;
  252. }
  253. const inboxLink = findInboxLink();
  254. if (!inboxLink) {
  255. return false;
  256. }
  257. simulateClick(inboxLink);
  258. for (let attempt = 0; attempt < 20; attempt += 1) {
  259. await sleep(250);
  260. if (findMailItems().length > 0) {
  261. return true;
  262. }
  263. }
  264. return false;
  265. }
  266. async function openMailAndGetMessageText(item) {
  267. simulateClick(item);
  268. try {
  269. await sleepRandom(1200, 2200);
  270. return document.body?.textContent || '';
  271. } finally {
  272. await returnToInbox();
  273. }
  274. }
  275. async function refreshInbox() {
  276. const refreshBtn = document.querySelector(
  277. '[class*="refresh"], [title*="刷新"], [aria-label*="刷新"], [class*="Refresh"]'
  278. );
  279. if (refreshBtn) {
  280. simulateClick(refreshBtn);
  281. await sleepRandom(700, 1200);
  282. return;
  283. }
  284. const inboxLink = document.querySelector(
  285. 'a[href*="mailList"], [class*="inbox"], [class*="Inbox"], [title*="收件箱"]'
  286. );
  287. if (inboxLink) {
  288. simulateClick(inboxLink);
  289. await sleepRandom(700, 1200);
  290. }
  291. }
  292. async function handlePollEmail(step, payload) {
  293. const {
  294. senderFilters,
  295. subjectFilters,
  296. maxAttempts,
  297. intervalMs,
  298. filterAfterTimestamp = 0,
  299. excludeCodes = [],
  300. strictChatGPTCodeOnly = false,
  301. targetEmail = '',
  302. } = payload;
  303. const excludedCodeSet = new Set(excludeCodes.filter(Boolean));
  304. const filterAfterMinute = normalizeMinuteTimestamp(Number(filterAfterTimestamp) || 0);
  305. log(`步骤 ${step}:开始轮询 2925 邮箱(最多 ${maxAttempts} 次)`);
  306. if (filterAfterMinute) {
  307. log(`步骤 ${step}:仅尝试 ${new Date(filterAfterMinute).toLocaleString('zh-CN', { hour12: false })} 及之后时间的邮件。`);
  308. }
  309. let initialItems = [];
  310. for (let i = 0; i < 20; i++) {
  311. initialItems = findMailItems();
  312. if (initialItems.length > 0) break;
  313. await sleep(500);
  314. }
  315. if (initialItems.length === 0) {
  316. await returnToInbox();
  317. await refreshInbox();
  318. await sleep(2000);
  319. initialItems = findMailItems();
  320. }
  321. if (initialItems.length === 0) {
  322. throw new Error('2925 邮箱列表未加载完成,请确认当前已打开收件箱。');
  323. }
  324. const existingMailIds = getCurrentMailIds(initialItems);
  325. log(`步骤 ${step}:邮件列表已加载,共 ${initialItems.length} 封邮件`);
  326. log(`步骤 ${step}:已记录当前 ${existingMailIds.size} 封旧邮件快照`);
  327. const FALLBACK_AFTER = 3;
  328. for (let attempt = 1; attempt <= maxAttempts; attempt++) {
  329. log(`步骤 ${step}:正在轮询 2925 邮箱,第 ${attempt}/${maxAttempts} 次`);
  330. if (attempt > 1) {
  331. await returnToInbox();
  332. await refreshInbox();
  333. await sleepRandom(900, 1500);
  334. }
  335. const items = findMailItems();
  336. if (items.length > 0) {
  337. const useFallback = attempt > FALLBACK_AFTER;
  338. for (let index = 0; index < items.length; index++) {
  339. const item = items[index];
  340. const itemId = getMailItemId(item, index);
  341. const itemTimestamp = parseMailItemTimestamp(item);
  342. const itemMinute = normalizeMinuteTimestamp(itemTimestamp || 0);
  343. const passesTimeFilter = !filterAfterMinute || (itemMinute && itemMinute >= filterAfterMinute);
  344. const shouldBypassOldSnapshot = Boolean(filterAfterMinute && passesTimeFilter && itemMinute > 0);
  345. if (!passesTimeFilter) {
  346. continue;
  347. }
  348. if (!useFallback && !shouldBypassOldSnapshot && existingMailIds.has(itemId)) {
  349. continue;
  350. }
  351. const text = getMailItemText(item);
  352. if (!matchesMailFilters(text, senderFilters, subjectFilters)) {
  353. continue;
  354. }
  355. const previewEmails = extractEmails(text);
  356. const previewTargetState = getTargetEmailMatchState(text, targetEmail);
  357. const previewMatchesTarget = previewTargetState.matches;
  358. if (targetEmail && previewEmails.length > 0 && !previewMatchesTarget) {
  359. continue;
  360. }
  361. const code = extractVerificationCode(text, strictChatGPTCodeOnly);
  362. if (code && previewMatchesTarget) {
  363. if (excludedCodeSet.has(code)) {
  364. log(`步骤 ${step}:跳过排除的验证码:${code}`, 'info');
  365. continue;
  366. }
  367. if (seenCodes.has(code)) {
  368. log(`步骤 ${step}:跳过已处理过的验证码:${code}`, 'info');
  369. continue;
  370. }
  371. seenCodes.add(code);
  372. persistSeenCodes();
  373. const source = useFallback && existingMailIds.has(itemId) ? '回退匹配邮件' : '新邮件';
  374. const timeLabel = itemTimestamp ? `,时间:${new Date(itemTimestamp).toLocaleString('zh-CN', { hour12: false })}` : '';
  375. log(`步骤 ${step}:已找到验证码:${code}(来源:${source}${timeLabel})`, 'ok');
  376. await sleep(1000);
  377. return { ok: true, code, emailTimestamp: Date.now() };
  378. }
  379. const openedText = await openMailAndGetMessageText(item);
  380. const bodyCode = extractVerificationCode(openedText, strictChatGPTCodeOnly);
  381. const openedTargetState = getTargetEmailMatchState(openedText, targetEmail);
  382. if (targetEmail && openedTargetState.hasExplicitEmail && !openedTargetState.matches) {
  383. continue;
  384. }
  385. if (bodyCode) {
  386. if (excludedCodeSet.has(bodyCode)) {
  387. log(`步骤 ${step}:跳过排除的验证码:${bodyCode}`, 'info');
  388. continue;
  389. }
  390. if (seenCodes.has(bodyCode)) {
  391. log(`步骤 ${step}:跳过已处理过的验证码:${bodyCode}`, 'info');
  392. continue;
  393. }
  394. seenCodes.add(bodyCode);
  395. persistSeenCodes();
  396. const source = useFallback && existingMailIds.has(itemId) ? '回退匹配邮件正文' : '新邮件正文';
  397. const timeLabel = itemTimestamp ? `,时间:${new Date(itemTimestamp).toLocaleString('zh-CN', { hour12: false })}` : '';
  398. log(`步骤 ${step}:已在邮件正文中找到验证码:${bodyCode}(来源:${source}${timeLabel})`, 'ok');
  399. await sleep(1000);
  400. return { ok: true, code: bodyCode, emailTimestamp: Date.now() };
  401. }
  402. }
  403. }
  404. if (attempt === FALLBACK_AFTER + 1) {
  405. log(`步骤 ${step}:连续 ${FALLBACK_AFTER} 次未发现新邮件,开始回退到首封匹配邮件`, 'warn');
  406. }
  407. if (attempt < maxAttempts) {
  408. await sleepRandom(intervalMs, intervalMs + 1200);
  409. }
  410. }
  411. throw new Error(
  412. `${(maxAttempts * intervalMs / 1000).toFixed(0)} 秒后仍未在 2925 邮箱中找到新的匹配邮件。请手动检查收件箱。`
  413. );
  414. }
  415. }