mail-163.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. // content/mail-163.js — Content script for 163 Mail (steps 4, 7)
  2. // Injected on: mail.163.com
  3. //
  4. // DOM structure:
  5. // Mail item: div[sign="letter"] with aria-label="你的 ChatGPT 代码为 479637 发件人 : OpenAI ..."
  6. // Sender: .nui-user (e.g., "OpenAI")
  7. // Subject: span.da0 (e.g., "你的 ChatGPT 代码为 479637")
  8. // Right-click menu: .nui-menu → .nui-menu-item with text "删除邮件"
  9. const MAIL163_PREFIX = '[MultiPage:mail-163]';
  10. const isTopFrame = window === window.top;
  11. console.log(MAIL163_PREFIX, 'Content script loaded on', location.href, 'frame:', isTopFrame ? 'top' : 'child');
  12. // Only operate in the top frame
  13. if (!isTopFrame) {
  14. console.log(MAIL163_PREFIX, 'Skipping child frame');
  15. } else {
  16. // Track codes we've already seen — persisted in chrome.storage.session to survive script re-injection
  17. let seenCodes = new Set();
  18. async function loadSeenCodes() {
  19. try {
  20. const data = await chrome.storage.session.get('seenCodes');
  21. if (data.seenCodes && Array.isArray(data.seenCodes)) {
  22. seenCodes = new Set(data.seenCodes);
  23. console.log(MAIL163_PREFIX, `Loaded ${seenCodes.size} previously seen codes`);
  24. }
  25. } catch (err) {
  26. console.warn(MAIL163_PREFIX, 'Session storage unavailable, using in-memory seen codes:', err?.message || err);
  27. }
  28. }
  29. // Load previously seen codes on startup
  30. loadSeenCodes();
  31. async function persistSeenCodes() {
  32. try {
  33. await chrome.storage.session.set({ seenCodes: [...seenCodes] });
  34. } catch (err) {
  35. console.warn(MAIL163_PREFIX, 'Could not persist seen codes, continuing in-memory only:', err?.message || err);
  36. }
  37. }
  38. // ============================================================
  39. // Message Handler (top frame only)
  40. // ============================================================
  41. chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  42. if (message.type === 'POLL_EMAIL') {
  43. resetStopState();
  44. handlePollEmail(message.step, message.payload).then(result => {
  45. sendResponse(result);
  46. }).catch(err => {
  47. if (isStopError(err)) {
  48. log(`步骤 ${message.step}:已被用户停止。`, 'warn');
  49. sendResponse({ stopped: true, error: err.message });
  50. return;
  51. }
  52. log(`步骤 ${message.step}:邮箱轮询失败:${err.message}`, 'warn');
  53. sendResponse({ error: err.message });
  54. });
  55. return true;
  56. }
  57. });
  58. // ============================================================
  59. // Find mail items
  60. // ============================================================
  61. function findMailItems() {
  62. return document.querySelectorAll('div[sign="letter"]');
  63. }
  64. function getCurrentMailIds() {
  65. const ids = new Set();
  66. findMailItems().forEach(item => {
  67. const id = item.getAttribute('id') || '';
  68. if (id) ids.add(id);
  69. });
  70. return ids;
  71. }
  72. function normalizeMinuteTimestamp(timestamp) {
  73. if (!Number.isFinite(timestamp) || timestamp <= 0) return 0;
  74. const date = new Date(timestamp);
  75. date.setSeconds(0, 0);
  76. return date.getTime();
  77. }
  78. function parseMail163Timestamp(rawText) {
  79. const text = (rawText || '').replace(/\s+/g, ' ').trim();
  80. if (!text) return null;
  81. let match = text.match(/(\d{4})年(\d{1,2})月(\d{1,2})日\s+(\d{1,2}):(\d{2})/);
  82. if (match) {
  83. const [, year, month, day, hour, minute] = match;
  84. return new Date(
  85. Number(year),
  86. Number(month) - 1,
  87. Number(day),
  88. Number(hour),
  89. Number(minute),
  90. 0,
  91. 0
  92. ).getTime();
  93. }
  94. match = text.match(/\b(\d{1,2}):(\d{2})\b/);
  95. if (match) {
  96. const [, hour, minute] = match;
  97. const now = new Date();
  98. return new Date(
  99. now.getFullYear(),
  100. now.getMonth(),
  101. now.getDate(),
  102. Number(hour),
  103. Number(minute),
  104. 0,
  105. 0
  106. ).getTime();
  107. }
  108. return null;
  109. }
  110. function getMailTimestamp(item) {
  111. const candidates = [];
  112. const timeCell = item.querySelector('.e00[title], [title*="年"][title*=":"]');
  113. if (timeCell?.getAttribute('title')) candidates.push(timeCell.getAttribute('title'));
  114. if (timeCell?.textContent) candidates.push(timeCell.textContent);
  115. const titledNodes = item.querySelectorAll('[title]');
  116. titledNodes.forEach((node) => {
  117. const title = node.getAttribute('title');
  118. if (title) candidates.push(title);
  119. });
  120. for (const candidate of candidates) {
  121. const parsed = parseMail163Timestamp(candidate);
  122. if (parsed) return parsed;
  123. }
  124. return null;
  125. }
  126. // ============================================================
  127. // Email Polling
  128. // ============================================================
  129. async function handlePollEmail(step, payload) {
  130. const { senderFilters, subjectFilters, maxAttempts, intervalMs, excludeCodes = [], filterAfterTimestamp = 0 } = payload;
  131. const excludedCodeSet = new Set(excludeCodes.filter(Boolean));
  132. const filterAfterMinute = normalizeMinuteTimestamp(Number(filterAfterTimestamp) || 0);
  133. log(`步骤 ${step}:开始轮询 163 邮箱(最多 ${maxAttempts} 次)`);
  134. if (filterAfterMinute) {
  135. log(`步骤 ${step}:仅尝试 ${new Date(filterAfterMinute).toLocaleString('zh-CN', { hour12: false })} 及之后时间的邮件。`);
  136. }
  137. // Click inbox in sidebar to ensure we're in inbox view
  138. log(`步骤 ${step}:正在等待侧边栏加载...`);
  139. try {
  140. const inboxLink = await waitForElement('.nui-tree-item-text[title="收件箱"]', 5000);
  141. inboxLink.click();
  142. log(`步骤 ${step}:已点击收件箱`);
  143. } catch {
  144. log(`步骤 ${step}:未找到收件箱入口,继续尝试后续流程...`, 'warn');
  145. }
  146. // Wait for mail list to appear
  147. log(`步骤 ${step}:正在等待邮件列表加载...`);
  148. let items = [];
  149. for (let i = 0; i < 20; i++) {
  150. items = findMailItems();
  151. if (items.length > 0) break;
  152. await sleep(500);
  153. }
  154. if (items.length === 0) {
  155. await refreshInbox();
  156. await sleep(2000);
  157. items = findMailItems();
  158. }
  159. if (items.length === 0) {
  160. throw new Error('163 邮箱列表未加载完成,请确认当前已打开收件箱。');
  161. }
  162. log(`步骤 ${step}:邮件列表已加载,共 ${items.length} 封邮件`);
  163. // Snapshot existing mail IDs
  164. const existingMailIds = getCurrentMailIds();
  165. log(`步骤 ${step}:已记录当前 ${existingMailIds.size} 封旧邮件快照`);
  166. const FALLBACK_AFTER = 3;
  167. for (let attempt = 1; attempt <= maxAttempts; attempt++) {
  168. log(`步骤 ${step}:正在轮询 163 邮箱,第 ${attempt}/${maxAttempts} 次`);
  169. if (attempt > 1) {
  170. await refreshInbox();
  171. await sleep(1000);
  172. }
  173. const allItems = findMailItems();
  174. const useFallback = attempt > FALLBACK_AFTER;
  175. for (const item of allItems) {
  176. const id = item.getAttribute('id') || '';
  177. const mailTimestamp = getMailTimestamp(item);
  178. const mailMinute = normalizeMinuteTimestamp(mailTimestamp || 0);
  179. const passesTimeFilter = !filterAfterMinute || (mailMinute && mailMinute >= filterAfterMinute);
  180. const shouldBypassOldSnapshot = Boolean(filterAfterMinute && passesTimeFilter && mailMinute > 0);
  181. if (!passesTimeFilter) {
  182. continue;
  183. }
  184. if (!useFallback && !shouldBypassOldSnapshot && existingMailIds.has(id)) continue;
  185. const senderEl = item.querySelector('.nui-user');
  186. const sender = senderEl ? senderEl.textContent.toLowerCase() : '';
  187. const subjectEl = item.querySelector('span.da0');
  188. const subject = subjectEl ? subjectEl.textContent : '';
  189. const ariaLabel = (item.getAttribute('aria-label') || '').toLowerCase();
  190. const senderMatch = senderFilters.some(f => sender.includes(f.toLowerCase()) || ariaLabel.includes(f.toLowerCase()));
  191. const subjectMatch = subjectFilters.some(f => subject.toLowerCase().includes(f.toLowerCase()) || ariaLabel.includes(f.toLowerCase()));
  192. if (senderMatch || subjectMatch) {
  193. const code = extractVerificationCode(subject + ' ' + ariaLabel);
  194. if (code && excludedCodeSet.has(code)) {
  195. log(`步骤 ${step}:跳过排除的验证码:${code}`, 'info');
  196. } else if (code && !seenCodes.has(code)) {
  197. seenCodes.add(code);
  198. persistSeenCodes();
  199. const source = useFallback && existingMailIds.has(id) ? '回退匹配邮件' : '新邮件';
  200. const timeLabel = mailTimestamp ? `,时间:${new Date(mailTimestamp).toLocaleString('zh-CN', { hour12: false })}` : '';
  201. log(`步骤 ${step}:已找到验证码:${code}(来源:${source}${timeLabel},主题:${subject.slice(0, 40)})`, 'ok');
  202. // Delete this email via right-click menu, WAIT for it to finish before returning
  203. await deleteEmail(item, step);
  204. // Extra wait to ensure deletion is processed
  205. await sleep(1000);
  206. return { ok: true, code, emailTimestamp: Date.now(), mailId: id };
  207. } else if (code && seenCodes.has(code)) {
  208. log(`步骤 ${step}:跳过已处理过的验证码:${code}`, 'info');
  209. }
  210. }
  211. }
  212. if (attempt === FALLBACK_AFTER + 1) {
  213. log(`步骤 ${step}:连续 ${FALLBACK_AFTER} 次未发现新邮件,开始回退到首封匹配邮件`, 'warn');
  214. }
  215. if (attempt < maxAttempts) {
  216. await sleep(intervalMs);
  217. }
  218. }
  219. throw new Error(
  220. `${(maxAttempts * intervalMs / 1000).toFixed(0)} 秒后仍未在 163 邮箱中找到新的匹配邮件。` +
  221. '请手动检查收件箱。'
  222. );
  223. }
  224. // ============================================================
  225. // Delete Email via Right-Click Menu
  226. // ============================================================
  227. async function deleteEmail(item, step) {
  228. try {
  229. log(`步骤 ${step}:正在删除邮件...`);
  230. // Strategy 1: Click the trash icon inside the mail item
  231. // Each mail item has: <b class="nui-ico nui-ico-delete" title="删除邮件" sign="trash">
  232. // These icons appear on hover, so we trigger mouseover first
  233. item.dispatchEvent(new MouseEvent('mouseover', { bubbles: true }));
  234. item.dispatchEvent(new MouseEvent('mouseenter', { bubbles: true }));
  235. await sleep(300);
  236. const trashIcon = item.querySelector('[sign="trash"], .nui-ico-delete, [title="删除邮件"]');
  237. if (trashIcon) {
  238. trashIcon.click();
  239. log(`步骤 ${step}:已点击删除图标`, 'ok');
  240. await sleep(1500);
  241. // Check if item disappeared (confirm deletion)
  242. const stillExists = document.getElementById(item.id);
  243. if (!stillExists || stillExists.style.display === 'none') {
  244. log(`步骤 ${step}:邮件已成功删除`);
  245. } else {
  246. log(`步骤 ${step}:邮件可能尚未删除,列表中仍可见`, 'warn');
  247. }
  248. return;
  249. }
  250. // Strategy 2: Select checkbox then click toolbar delete button
  251. log(`步骤 ${step}:未找到删除图标,尝试使用复选框加工具栏删除...`);
  252. const checkbox = item.querySelector('[sign="checkbox"], .nui-chk');
  253. if (checkbox) {
  254. checkbox.click();
  255. await sleep(300);
  256. // Click toolbar delete button
  257. const toolbarBtns = document.querySelectorAll('.nui-btn .nui-btn-text');
  258. for (const btn of toolbarBtns) {
  259. if (btn.textContent.replace(/\s/g, '').includes('删除')) {
  260. btn.closest('.nui-btn').click();
  261. log(`步骤 ${step}:已点击工具栏删除`, 'ok');
  262. await sleep(1500);
  263. return;
  264. }
  265. }
  266. }
  267. log(`步骤 ${step}:无法删除邮件(未找到删除按钮)`, 'warn');
  268. } catch (err) {
  269. log(`步骤 ${step}:删除邮件失败:${err.message}`, 'warn');
  270. }
  271. }
  272. // ============================================================
  273. // Inbox Refresh
  274. // ============================================================
  275. async function refreshInbox() {
  276. // Try toolbar "刷 新" button
  277. const toolbarBtns = document.querySelectorAll('.nui-btn .nui-btn-text');
  278. for (const btn of toolbarBtns) {
  279. if (btn.textContent.replace(/\s/g, '') === '刷新') {
  280. btn.closest('.nui-btn').click();
  281. console.log(MAIL163_PREFIX, 'Clicked "刷新" button');
  282. await sleep(800);
  283. return;
  284. }
  285. }
  286. // Fallback: click sidebar "收 信"
  287. const shouXinBtns = document.querySelectorAll('.ra0');
  288. for (const btn of shouXinBtns) {
  289. if (btn.textContent.replace(/\s/g, '').includes('收信')) {
  290. btn.click();
  291. console.log(MAIL163_PREFIX, 'Clicked "收信" button');
  292. await sleep(800);
  293. return;
  294. }
  295. }
  296. console.log(MAIL163_PREFIX, 'Could not find refresh button');
  297. }
  298. // ============================================================
  299. // Verification Code Extraction
  300. // ============================================================
  301. function extractVerificationCode(text) {
  302. const matchCn = text.match(/(?:代码为|验证码[^0-9]*?)[\s::]*(\d{6})/);
  303. if (matchCn) return matchCn[1];
  304. const matchEn = text.match(/code[:\s]+is[:\s]+(\d{6})|code[:\s]+(\d{6})/i);
  305. if (matchEn) return matchEn[1] || matchEn[2];
  306. const match6 = text.match(/\b(\d{6})\b/);
  307. if (match6) return match6[1];
  308. return null;
  309. }
  310. } // end of isTopFrame else block