mail-2925.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  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. function findMailItems() {
  59. for (const selector of MAIL_ITEM_SELECTORS) {
  60. const items = document.querySelectorAll(selector);
  61. if (items.length > 0) {
  62. return Array.from(items);
  63. }
  64. }
  65. return [];
  66. }
  67. function getMailItemText(item) {
  68. if (!item) return '';
  69. const contentCell = item.querySelector('td.content, .content, .mail-content');
  70. const titleEl = item.querySelector('.mail-content-title');
  71. const textEl = item.querySelector('.mail-content-text');
  72. return [
  73. titleEl?.getAttribute('title') || '',
  74. titleEl?.textContent || '',
  75. textEl?.textContent || '',
  76. contentCell?.textContent || '',
  77. item.textContent || '',
  78. ].join(' ');
  79. }
  80. function getMailItemTimeText(item) {
  81. const timeEl = item?.querySelector('.date-time-text, [class*="date-time"], [class*="time"], td.time');
  82. return (timeEl?.textContent || '').replace(/\s+/g, ' ').trim();
  83. }
  84. function normalizeMailIdentityPart(value) {
  85. return (value || '').replace(/\s+/g, ' ').trim().toLowerCase();
  86. }
  87. function getMailItemId(item, index = 0) {
  88. const candidates = [
  89. item?.getAttribute?.('data-id'),
  90. item?.dataset?.id,
  91. item?.getAttribute?.('data-mail-id'),
  92. item?.dataset?.mailId,
  93. item?.getAttribute?.('data-key'),
  94. item?.getAttribute?.('key'),
  95. ].filter(Boolean);
  96. if (candidates.length > 0) {
  97. return String(candidates[0]);
  98. }
  99. return [
  100. index,
  101. normalizeMailIdentityPart(getMailItemTimeText(item)),
  102. normalizeMailIdentityPart(getMailItemText(item)).slice(0, 240),
  103. ].join('|');
  104. }
  105. function getCurrentMailIds(items = []) {
  106. const ids = new Set();
  107. items.forEach((item, index) => {
  108. ids.add(getMailItemId(item, index));
  109. });
  110. return ids;
  111. }
  112. function normalizeMinuteTimestamp(timestamp) {
  113. if (!Number.isFinite(timestamp) || timestamp <= 0) return 0;
  114. const date = new Date(timestamp);
  115. date.setSeconds(0, 0);
  116. return date.getTime();
  117. }
  118. function matchesMailFilters(text, senderFilters, subjectFilters) {
  119. const lower = (text || '').toLowerCase();
  120. const senderMatch = senderFilters.some(filter => lower.includes(filter.toLowerCase()));
  121. const subjectMatch = subjectFilters.some(filter => lower.includes(filter.toLowerCase()));
  122. return senderMatch || subjectMatch;
  123. }
  124. function extractVerificationCode(text, strictChatGPTCodeOnly = false) {
  125. if (strictChatGPTCodeOnly) {
  126. const strictMatch = text.match(/your\s+chatgpt\s+code\s+is\s+(\d{6})/i);
  127. return strictMatch ? strictMatch[1] : null;
  128. }
  129. const matchCn = text.match(/(?:代码为|验证码[^0-9]*?)[\s::]*(\d{6})/);
  130. if (matchCn) return matchCn[1];
  131. const matchChatGPT = text.match(/your\s+chatgpt\s+code\s+is\s+(\d{6})/i);
  132. if (matchChatGPT) return matchChatGPT[1];
  133. const matchEn = text.match(/code[:\s]+is[:\s]+(\d{6})|code[:\s]+(\d{6})/i);
  134. if (matchEn) return matchEn[1] || matchEn[2];
  135. const match6 = text.match(/\b(\d{6})\b/);
  136. if (match6) return match6[1];
  137. return null;
  138. }
  139. function extractEmails(text) {
  140. const matches = text.match(/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/ig) || [];
  141. return [...new Set(matches.map(item => item.toLowerCase()))];
  142. }
  143. function emailMatchesTarget(candidate, targetEmail) {
  144. const normalizedCandidate = String(candidate || '').trim().toLowerCase();
  145. const normalizedTarget = String(targetEmail || '').trim().toLowerCase();
  146. return Boolean(normalizedCandidate && normalizedTarget && normalizedCandidate === normalizedTarget);
  147. }
  148. function getTargetEmailMatchState(text, targetEmail) {
  149. const normalizedTarget = String(targetEmail || '').trim().toLowerCase();
  150. if (!normalizedTarget) {
  151. return { matches: true, hasExplicitEmail: false };
  152. }
  153. const normalizedText = String(text || '').toLowerCase();
  154. if (normalizedText.includes(normalizedTarget)) {
  155. return { matches: true, hasExplicitEmail: true };
  156. }
  157. const atIndex = normalizedTarget.indexOf('@');
  158. if (atIndex > 0) {
  159. const encodedTarget = `${normalizedTarget.slice(0, atIndex)}=${normalizedTarget.slice(atIndex + 1)}`;
  160. if (normalizedText.includes(encodedTarget)) {
  161. return { matches: true, hasExplicitEmail: true };
  162. }
  163. }
  164. const emails = extractEmails(text);
  165. if (!emails.length) {
  166. return { matches: false, hasExplicitEmail: false };
  167. }
  168. return {
  169. matches: emails.some(email => emailMatchesTarget(email, normalizedTarget)),
  170. hasExplicitEmail: true,
  171. };
  172. }
  173. function parseMailItemTimestamp(item) {
  174. const timeText = getMailItemTimeText(item);
  175. if (!timeText) return null;
  176. const now = new Date();
  177. const date = new Date(now);
  178. let match = null;
  179. if (/刚刚/.test(timeText)) {
  180. return now.getTime();
  181. }
  182. match = timeText.match(/(\d+)\s*分(?:钟)?前/);
  183. if (match) {
  184. return now.getTime() - Number(match[1]) * 60 * 1000;
  185. }
  186. match = timeText.match(/(\d+)\s*秒前/);
  187. if (match) {
  188. return now.getTime() - Number(match[1]) * 1000;
  189. }
  190. match = timeText.match(/^(\d{1,2}):(\d{2})$/);
  191. if (match) {
  192. date.setHours(Number(match[1]), Number(match[2]), 0, 0);
  193. return date.getTime();
  194. }
  195. match = timeText.match(/今天\s*(\d{1,2}):(\d{2})/);
  196. if (match) {
  197. date.setHours(Number(match[1]), Number(match[2]), 0, 0);
  198. return date.getTime();
  199. }
  200. match = timeText.match(/昨天\s*(\d{1,2}):(\d{2})/);
  201. if (match) {
  202. date.setDate(date.getDate() - 1);
  203. date.setHours(Number(match[1]), Number(match[2]), 0, 0);
  204. return date.getTime();
  205. }
  206. match = timeText.match(/(\d{1,2})-(\d{1,2})\s*(\d{1,2}):(\d{2})/);
  207. if (match) {
  208. date.setMonth(Number(match[1]) - 1, Number(match[2]));
  209. date.setHours(Number(match[3]), Number(match[4]), 0, 0);
  210. return date.getTime();
  211. }
  212. match = timeText.match(/(\d{4})-(\d{1,2})-(\d{1,2})\s*(\d{1,2}):(\d{2})/);
  213. if (match) {
  214. return new Date(
  215. Number(match[1]),
  216. Number(match[2]) - 1,
  217. Number(match[3]),
  218. Number(match[4]),
  219. Number(match[5]),
  220. 0,
  221. 0
  222. ).getTime();
  223. }
  224. return null;
  225. }
  226. async function sleepRandom(minMs, maxMs = minMs) {
  227. const duration = Math.floor(Math.random() * (maxMs - minMs + 1)) + minMs;
  228. await sleep(duration);
  229. }
  230. async function refreshInbox() {
  231. const refreshBtn = document.querySelector(
  232. '[class*="refresh"], [title*="刷新"], [aria-label*="刷新"], [class*="Refresh"]'
  233. );
  234. if (refreshBtn) {
  235. simulateClick(refreshBtn);
  236. await sleepRandom(700, 1200);
  237. return;
  238. }
  239. const inboxLink = document.querySelector(
  240. 'a[href*="mailList"], [class*="inbox"], [class*="Inbox"], [title*="收件箱"]'
  241. );
  242. if (inboxLink) {
  243. simulateClick(inboxLink);
  244. await sleepRandom(700, 1200);
  245. }
  246. }
  247. async function handlePollEmail(step, payload) {
  248. const {
  249. senderFilters,
  250. subjectFilters,
  251. maxAttempts,
  252. intervalMs,
  253. filterAfterTimestamp = 0,
  254. excludeCodes = [],
  255. strictChatGPTCodeOnly = false,
  256. targetEmail = '',
  257. } = payload;
  258. const excludedCodeSet = new Set(excludeCodes.filter(Boolean));
  259. const filterAfterMinute = normalizeMinuteTimestamp(Number(filterAfterTimestamp) || 0);
  260. log(`步骤 ${step}:开始轮询 2925 邮箱(最多 ${maxAttempts} 次)`);
  261. if (filterAfterMinute) {
  262. log(`步骤 ${step}:仅尝试 ${new Date(filterAfterMinute).toLocaleString('zh-CN', { hour12: false })} 及之后时间的邮件。`);
  263. }
  264. let initialItems = [];
  265. for (let i = 0; i < 20; i++) {
  266. initialItems = findMailItems();
  267. if (initialItems.length > 0) break;
  268. await sleep(500);
  269. }
  270. if (initialItems.length === 0) {
  271. await refreshInbox();
  272. await sleep(2000);
  273. initialItems = findMailItems();
  274. }
  275. if (initialItems.length === 0) {
  276. throw new Error('2925 邮箱列表未加载完成,请确认当前已打开收件箱。');
  277. }
  278. const existingMailIds = getCurrentMailIds(initialItems);
  279. log(`步骤 ${step}:邮件列表已加载,共 ${initialItems.length} 封邮件`);
  280. log(`步骤 ${step}:已记录当前 ${existingMailIds.size} 封旧邮件快照`);
  281. const FALLBACK_AFTER = 3;
  282. for (let attempt = 1; attempt <= maxAttempts; attempt++) {
  283. log(`步骤 ${step}:正在轮询 2925 邮箱,第 ${attempt}/${maxAttempts} 次`);
  284. if (attempt > 1) {
  285. await refreshInbox();
  286. await sleepRandom(900, 1500);
  287. }
  288. const items = findMailItems();
  289. if (items.length > 0) {
  290. const useFallback = attempt > FALLBACK_AFTER;
  291. for (let index = 0; index < items.length; index++) {
  292. const item = items[index];
  293. const itemId = getMailItemId(item, index);
  294. const itemTimestamp = parseMailItemTimestamp(item);
  295. const itemMinute = normalizeMinuteTimestamp(itemTimestamp || 0);
  296. const passesTimeFilter = !filterAfterMinute || (itemMinute && itemMinute >= filterAfterMinute);
  297. const shouldBypassOldSnapshot = Boolean(filterAfterMinute && passesTimeFilter && itemMinute > 0);
  298. if (!passesTimeFilter) {
  299. continue;
  300. }
  301. if (!useFallback && !shouldBypassOldSnapshot && existingMailIds.has(itemId)) {
  302. continue;
  303. }
  304. const text = getMailItemText(item);
  305. if (!matchesMailFilters(text, senderFilters, subjectFilters)) {
  306. continue;
  307. }
  308. const previewEmails = extractEmails(text);
  309. const previewTargetState = getTargetEmailMatchState(text, targetEmail);
  310. const previewMatchesTarget = previewTargetState.matches;
  311. if (targetEmail && previewEmails.length > 0 && !previewMatchesTarget) {
  312. continue;
  313. }
  314. const code = extractVerificationCode(text, strictChatGPTCodeOnly);
  315. if (code && previewMatchesTarget) {
  316. if (excludedCodeSet.has(code)) {
  317. log(`步骤 ${step}:跳过排除的验证码:${code}`, 'info');
  318. continue;
  319. }
  320. if (seenCodes.has(code)) {
  321. log(`步骤 ${step}:跳过已处理过的验证码:${code}`, 'info');
  322. continue;
  323. }
  324. seenCodes.add(code);
  325. persistSeenCodes();
  326. const source = useFallback && existingMailIds.has(itemId) ? '回退匹配邮件' : '新邮件';
  327. const timeLabel = itemTimestamp ? `,时间:${new Date(itemTimestamp).toLocaleString('zh-CN', { hour12: false })}` : '';
  328. log(`步骤 ${step}:已找到验证码:${code}(来源:${source}${timeLabel})`, 'ok');
  329. await sleep(1000);
  330. return { ok: true, code, emailTimestamp: Date.now() };
  331. }
  332. simulateClick(item);
  333. await sleepRandom(1200, 2200);
  334. const openedText = document.body?.textContent || '';
  335. const bodyCode = extractVerificationCode(openedText, strictChatGPTCodeOnly);
  336. const openedTargetState = getTargetEmailMatchState(openedText, targetEmail);
  337. if (targetEmail && openedTargetState.hasExplicitEmail && !openedTargetState.matches) {
  338. continue;
  339. }
  340. if (bodyCode) {
  341. if (excludedCodeSet.has(bodyCode)) {
  342. log(`步骤 ${step}:跳过排除的验证码:${bodyCode}`, 'info');
  343. continue;
  344. }
  345. if (seenCodes.has(bodyCode)) {
  346. log(`步骤 ${step}:跳过已处理过的验证码:${bodyCode}`, 'info');
  347. continue;
  348. }
  349. seenCodes.add(bodyCode);
  350. persistSeenCodes();
  351. const source = useFallback && existingMailIds.has(itemId) ? '回退匹配邮件正文' : '新邮件正文';
  352. const timeLabel = itemTimestamp ? `,时间:${new Date(itemTimestamp).toLocaleString('zh-CN', { hour12: false })}` : '';
  353. log(`步骤 ${step}:已在邮件正文中找到验证码:${bodyCode}(来源:${source}${timeLabel})`, 'ok');
  354. await sleep(1000);
  355. return { ok: true, code: bodyCode, emailTimestamp: Date.now() };
  356. }
  357. }
  358. }
  359. if (attempt === FALLBACK_AFTER + 1) {
  360. log(`步骤 ${step}:连续 ${FALLBACK_AFTER} 次未发现新邮件,开始回退到首封匹配邮件`, 'warn');
  361. }
  362. if (attempt < maxAttempts) {
  363. await sleepRandom(intervalMs, intervalMs + 1200);
  364. }
  365. }
  366. throw new Error(
  367. `${(maxAttempts * intervalMs / 1000).toFixed(0)} 秒后仍未在 2925 邮箱中找到新的匹配邮件。请手动检查收件箱。`
  368. );
  369. }
  370. }