feat: support 2925 mail provider in OAuth signup flow

- 合并 PR #37 的核心改动:新增 2925 邮箱选项、步骤 3 自动别名邮箱生成,以及步骤 4/7 的 2925 收件箱轮询
- 本地补充修复:整合侧边栏邮箱登录与邮箱生成显隐冲突,并在离开 2925 或导入配置时清空托管邮箱残留状态
- 影响范围:sidepanel mail provider config、background step orchestration、2925 mail content script
This commit is contained in:
QLHazyCoder
2026-04-13 20:59:19 +08:00
5 changed files with 573 additions and 12 deletions
+60 -3
View File
@@ -73,6 +73,7 @@ const PERSISTED_SETTING_DEFAULTS = {
cloudflareDomain: '', // 仅当 emailGenerator=cloudflare 时填写自定义域名。
cloudflareDomains: [], // Cloudflare 可选域名列表。
hotmailAccounts: [],
emailPrefix: '',
};
const PERSISTED_SETTING_KEYS = Object.keys(PERSISTED_SETTING_DEFAULTS);
@@ -187,6 +188,7 @@ function normalizeMailProvider(value = '') {
case '163-vip':
case 'qq':
case 'inbucket':
case '2925':
return normalized;
default:
return PERSISTED_SETTING_DEFAULTS.mailProvider;
@@ -262,6 +264,8 @@ function normalizePersistentSettingValue(key, value) {
return normalizeMailProvider(value);
case 'emailGenerator':
return normalizeEmailGenerator(value);
case 'emailPrefix':
return String(value || '').trim();
case 'inbucketHost':
return String(value || '').trim();
case 'inbucketMailbox':
@@ -406,10 +410,8 @@ async function importSettingsBundle(configBundle) {
const sessionUpdates = {
...importedSettings,
currentHotmailAccountId: null,
email: null,
};
if (importedSettings.mailProvider === HOTMAIL_PROVIDER) {
sessionUpdates.email = null;
}
await setState(sessionUpdates);
broadcastDataUpdate({
@@ -1107,6 +1109,34 @@ async function pollHotmailVerificationCode(step, state, pollPayload = {}) {
throw lastError || new Error(`步骤 ${step}:未在 Hotmail 收件箱中找到新的匹配验证码。`);
}
function generateRandomSuffix(length = 6) {
const chars = 'abcdefghjkmnpqrstuvwxyz23456789';
let suffix = '';
for (let i = 0; i < length; i++) {
suffix += chars[Math.floor(Math.random() * chars.length)];
}
return suffix;
}
function isGeneratedAliasProvider(provider) {
return provider === '2925';
}
function buildGeneratedAliasEmail(state) {
const provider = state.mailProvider || '163';
const emailPrefix = (state.emailPrefix || '').trim();
if (!emailPrefix) {
throw new Error('2925 邮箱前缀未设置,请先在侧边栏填写。');
}
if (provider === '2925') {
return `${emailPrefix}${generateRandomSuffix(6)}@2925.com`;
}
throw new Error(`未支持的别名邮箱类型:${provider}`);
}
// ============================================================
// Tab Registry
// ============================================================
@@ -1226,6 +1256,8 @@ function matchesSourceUrlFamily(source, candidateUrl, referenceUrl) {
return Boolean(reference)
&& candidate.origin === reference.origin
&& candidate.pathname.startsWith('/m/');
case 'mail-2925':
return candidate.hostname === '2925.com' || candidate.hostname === 'www.2925.com';
case 'vps-panel':
return Boolean(reference)
&& candidate.origin === reference.origin
@@ -1923,6 +1955,7 @@ function getSourceLabel(source) {
'sub2api-panel': 'SUB2API 后台',
'qq-mail': 'QQ 邮箱',
'mail-163': '163 邮箱',
'mail-2925': '2925 邮箱',
'inbucket-mail': 'Inbucket 邮箱',
'duck-mail': 'Duck 邮箱',
'hotmail-api': 'Hotmail(微软 Graph',
@@ -2638,6 +2671,10 @@ async function handleMessage(message, sender) {
if (message.payload.email) {
await setEmailState(message.payload.email);
}
if (message.payload.emailPrefix !== undefined) {
await setPersistentSettings({ emailPrefix: message.payload.emailPrefix });
await setState({ emailPrefix: message.payload.emailPrefix });
}
await executeStep(step);
return { ok: true };
}
@@ -3260,6 +3297,14 @@ async function ensureAutoEmailReady(targetRun, totalRuns, attemptRuns) {
return account.email;
}
if (isGeneratedAliasProvider(currentState.mailProvider)) {
if (!currentState.emailPrefix) {
throw new Error('2925 邮箱前缀未设置,请先在侧边栏填写。');
}
await addLog(`=== 目标 ${targetRun}/${totalRuns} 轮:2925 模式已启用,将在步骤 3 自动生成邮箱(第 ${attemptRuns} 次尝试)===`, 'info');
return null;
}
if (currentState.email) {
return currentState.email;
}
@@ -3450,6 +3495,7 @@ async function autoRunLoop(totalRuns, options = {}) {
autoStepRandomDelayMaxSeconds: prevState.autoStepRandomDelayMaxSeconds,
mailProvider: prevState.mailProvider,
emailGenerator: prevState.emailGenerator,
emailPrefix: prevState.emailPrefix,
inbucketHost: prevState.inbucketHost,
inbucketMailbox: prevState.inbucketMailbox,
cloudflareDomain: prevState.cloudflareDomain,
@@ -3775,6 +3821,8 @@ async function executeStep3(state) {
preferredAccountId: state.currentHotmailAccountId || null,
});
resolvedEmail = account.email;
} else if (isGeneratedAliasProvider(state.mailProvider)) {
resolvedEmail = buildGeneratedAliasEmail(state);
}
if (!resolvedEmail) {
@@ -3836,6 +3884,15 @@ function getMailConfig(state) {
injectSource: 'inbucket-mail',
};
}
if (provider === '2925') {
return {
source: 'mail-2925',
url: 'https://2925.com/#/mailList',
label: '2925 邮箱',
inject: ['content/utils.js', 'content/mail-2925.js'],
injectSource: 'mail-2925',
};
}
return { source: 'qq-mail', url: 'https://wx.mail.qq.com/', label: 'QQ 邮箱' };
}
+437
View File
@@ -0,0 +1,437 @@
// content/mail-2925.js — Content script for 2925 Mail (steps 4, 7)
// Injected dynamically on: 2925.com
const MAIL2925_PREFIX = '[MultiPage:mail-2925]';
const isTopFrame = window === window.top;
console.log(MAIL2925_PREFIX, 'Content script loaded on', location.href, 'frame:', isTopFrame ? 'top' : 'child');
if (!isTopFrame) {
console.log(MAIL2925_PREFIX, 'Skipping child frame');
} else {
let seenCodes = new Set();
async function loadSeenCodes() {
try {
const data = await chrome.storage.session.get('seen2925Codes');
if (data.seen2925Codes && Array.isArray(data.seen2925Codes)) {
seenCodes = new Set(data.seen2925Codes);
console.log(MAIL2925_PREFIX, `Loaded ${seenCodes.size} previously seen codes`);
}
} catch (err) {
console.warn(MAIL2925_PREFIX, 'Session storage unavailable, using in-memory seen codes:', err?.message || err);
}
}
loadSeenCodes();
async function persistSeenCodes() {
try {
await chrome.storage.session.set({ seen2925Codes: [...seenCodes] });
} catch (err) {
console.warn(MAIL2925_PREFIX, 'Could not persist seen codes, continuing in-memory only:', err?.message || err);
}
}
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.type === 'POLL_EMAIL') {
resetStopState();
handlePollEmail(message.step, message.payload).then(result => {
sendResponse(result);
}).catch(err => {
if (isStopError(err)) {
log(`步骤 ${message.step}:已被用户停止。`, 'warn');
sendResponse({ stopped: true, error: err.message });
return;
}
log(`步骤 ${message.step}:邮箱轮询失败:${err.message}`, 'warn');
sendResponse({ error: err.message });
});
return true;
}
});
const MAIL_ITEM_SELECTORS = [
'.mail-item',
'.letter-item',
'[class*="mailItem"]',
'[class*="mail-item"]',
'[class*="MailItem"]',
'.el-table__row',
'tr[class*="mail"]',
'[class*="listItem"]',
'[class*="list-item"]',
'li[class*="mail"]',
];
function findMailItems() {
for (const selector of MAIL_ITEM_SELECTORS) {
const items = document.querySelectorAll(selector);
if (items.length > 0) {
return Array.from(items);
}
}
return [];
}
function getMailItemText(item) {
if (!item) return '';
const contentCell = item.querySelector('td.content, .content, .mail-content');
const titleEl = item.querySelector('.mail-content-title');
const textEl = item.querySelector('.mail-content-text');
return [
titleEl?.getAttribute('title') || '',
titleEl?.textContent || '',
textEl?.textContent || '',
contentCell?.textContent || '',
item.textContent || '',
].join(' ');
}
function getMailItemTimeText(item) {
const timeEl = item?.querySelector('.date-time-text, [class*="date-time"], [class*="time"], td.time');
return (timeEl?.textContent || '').replace(/\s+/g, ' ').trim();
}
function normalizeMailIdentityPart(value) {
return (value || '').replace(/\s+/g, ' ').trim().toLowerCase();
}
function getMailItemId(item, index = 0) {
const candidates = [
item?.getAttribute?.('data-id'),
item?.dataset?.id,
item?.getAttribute?.('data-mail-id'),
item?.dataset?.mailId,
item?.getAttribute?.('data-key'),
item?.getAttribute?.('key'),
].filter(Boolean);
if (candidates.length > 0) {
return String(candidates[0]);
}
return [
index,
normalizeMailIdentityPart(getMailItemTimeText(item)),
normalizeMailIdentityPart(getMailItemText(item)).slice(0, 240),
].join('|');
}
function getCurrentMailIds(items = []) {
const ids = new Set();
items.forEach((item, index) => {
ids.add(getMailItemId(item, index));
});
return ids;
}
function normalizeMinuteTimestamp(timestamp) {
if (!Number.isFinite(timestamp) || timestamp <= 0) return 0;
const date = new Date(timestamp);
date.setSeconds(0, 0);
return date.getTime();
}
function matchesMailFilters(text, senderFilters, subjectFilters) {
const lower = (text || '').toLowerCase();
const senderMatch = senderFilters.some(filter => lower.includes(filter.toLowerCase()));
const subjectMatch = subjectFilters.some(filter => lower.includes(filter.toLowerCase()));
return senderMatch || subjectMatch;
}
function extractVerificationCode(text, strictChatGPTCodeOnly = false) {
if (strictChatGPTCodeOnly) {
const strictMatch = text.match(/your\s+chatgpt\s+code\s+is\s+(\d{6})/i);
return strictMatch ? strictMatch[1] : null;
}
const matchCn = text.match(/(?:代码为|验证码[^0-9]*?)[\s:]*(\d{6})/);
if (matchCn) return matchCn[1];
const matchChatGPT = text.match(/your\s+chatgpt\s+code\s+is\s+(\d{6})/i);
if (matchChatGPT) return matchChatGPT[1];
const matchEn = text.match(/code[:\s]+is[:\s]+(\d{6})|code[:\s]+(\d{6})/i);
if (matchEn) return matchEn[1] || matchEn[2];
const match6 = text.match(/\b(\d{6})\b/);
if (match6) return match6[1];
return null;
}
function extractEmails(text) {
const matches = text.match(/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/ig) || [];
return [...new Set(matches.map(item => item.toLowerCase()))];
}
function emailMatchesTarget(candidate, targetEmail) {
const normalizedCandidate = String(candidate || '').trim().toLowerCase();
const normalizedTarget = String(targetEmail || '').trim().toLowerCase();
return Boolean(normalizedCandidate && normalizedTarget && normalizedCandidate === normalizedTarget);
}
function getTargetEmailMatchState(text, targetEmail) {
const normalizedTarget = String(targetEmail || '').trim().toLowerCase();
if (!normalizedTarget) {
return { matches: true, hasExplicitEmail: false };
}
const normalizedText = String(text || '').toLowerCase();
if (normalizedText.includes(normalizedTarget)) {
return { matches: true, hasExplicitEmail: true };
}
const atIndex = normalizedTarget.indexOf('@');
if (atIndex > 0) {
const encodedTarget = `${normalizedTarget.slice(0, atIndex)}=${normalizedTarget.slice(atIndex + 1)}`;
if (normalizedText.includes(encodedTarget)) {
return { matches: true, hasExplicitEmail: true };
}
}
const emails = extractEmails(text);
if (!emails.length) {
return { matches: false, hasExplicitEmail: false };
}
return {
matches: emails.some(email => emailMatchesTarget(email, normalizedTarget)),
hasExplicitEmail: true,
};
}
function parseMailItemTimestamp(item) {
const timeText = getMailItemTimeText(item);
if (!timeText) return null;
const now = new Date();
const date = new Date(now);
let match = null;
if (/刚刚/.test(timeText)) {
return now.getTime();
}
match = timeText.match(/(\d+)\s*分(?:钟)?前/);
if (match) {
return now.getTime() - Number(match[1]) * 60 * 1000;
}
match = timeText.match(/(\d+)\s*秒前/);
if (match) {
return now.getTime() - Number(match[1]) * 1000;
}
match = timeText.match(/^(\d{1,2}):(\d{2})$/);
if (match) {
date.setHours(Number(match[1]), Number(match[2]), 0, 0);
return date.getTime();
}
match = timeText.match(/今天\s*(\d{1,2}):(\d{2})/);
if (match) {
date.setHours(Number(match[1]), Number(match[2]), 0, 0);
return date.getTime();
}
match = timeText.match(/昨天\s*(\d{1,2}):(\d{2})/);
if (match) {
date.setDate(date.getDate() - 1);
date.setHours(Number(match[1]), Number(match[2]), 0, 0);
return date.getTime();
}
match = timeText.match(/(\d{1,2})-(\d{1,2})\s*(\d{1,2}):(\d{2})/);
if (match) {
date.setMonth(Number(match[1]) - 1, Number(match[2]));
date.setHours(Number(match[3]), Number(match[4]), 0, 0);
return date.getTime();
}
match = timeText.match(/(\d{4})-(\d{1,2})-(\d{1,2})\s*(\d{1,2}):(\d{2})/);
if (match) {
return new Date(
Number(match[1]),
Number(match[2]) - 1,
Number(match[3]),
Number(match[4]),
Number(match[5]),
0,
0
).getTime();
}
return null;
}
async function sleepRandom(minMs, maxMs = minMs) {
const duration = Math.floor(Math.random() * (maxMs - minMs + 1)) + minMs;
await sleep(duration);
}
async function refreshInbox() {
const refreshBtn = document.querySelector(
'[class*="refresh"], [title*="刷新"], [aria-label*="刷新"], [class*="Refresh"]'
);
if (refreshBtn) {
simulateClick(refreshBtn);
await sleepRandom(700, 1200);
return;
}
const inboxLink = document.querySelector(
'a[href*="mailList"], [class*="inbox"], [class*="Inbox"], [title*="收件箱"]'
);
if (inboxLink) {
simulateClick(inboxLink);
await sleepRandom(700, 1200);
}
}
async function handlePollEmail(step, payload) {
const {
senderFilters,
subjectFilters,
maxAttempts,
intervalMs,
filterAfterTimestamp = 0,
excludeCodes = [],
strictChatGPTCodeOnly = false,
targetEmail = '',
} = payload;
const excludedCodeSet = new Set(excludeCodes.filter(Boolean));
const filterAfterMinute = normalizeMinuteTimestamp(Number(filterAfterTimestamp) || 0);
log(`步骤 ${step}:开始轮询 2925 邮箱(最多 ${maxAttempts} 次)`);
if (filterAfterMinute) {
log(`步骤 ${step}:仅尝试 ${new Date(filterAfterMinute).toLocaleString('zh-CN', { hour12: false })} 及之后时间的邮件。`);
}
let initialItems = [];
for (let i = 0; i < 20; i++) {
initialItems = findMailItems();
if (initialItems.length > 0) break;
await sleep(500);
}
if (initialItems.length === 0) {
await refreshInbox();
await sleep(2000);
initialItems = findMailItems();
}
if (initialItems.length === 0) {
throw new Error('2925 邮箱列表未加载完成,请确认当前已打开收件箱。');
}
const existingMailIds = getCurrentMailIds(initialItems);
log(`步骤 ${step}:邮件列表已加载,共 ${initialItems.length} 封邮件`);
log(`步骤 ${step}:已记录当前 ${existingMailIds.size} 封旧邮件快照`);
const FALLBACK_AFTER = 3;
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
log(`步骤 ${step}:正在轮询 2925 邮箱,第 ${attempt}/${maxAttempts}`);
if (attempt > 1) {
await refreshInbox();
await sleepRandom(900, 1500);
}
const items = findMailItems();
if (items.length > 0) {
const useFallback = attempt > FALLBACK_AFTER;
for (let index = 0; index < items.length; index++) {
const item = items[index];
const itemId = getMailItemId(item, index);
const itemTimestamp = parseMailItemTimestamp(item);
const itemMinute = normalizeMinuteTimestamp(itemTimestamp || 0);
const passesTimeFilter = !filterAfterMinute || (itemMinute && itemMinute >= filterAfterMinute);
const shouldBypassOldSnapshot = Boolean(filterAfterMinute && passesTimeFilter && itemMinute > 0);
if (!passesTimeFilter) {
continue;
}
if (!useFallback && !shouldBypassOldSnapshot && existingMailIds.has(itemId)) {
continue;
}
const text = getMailItemText(item);
if (!matchesMailFilters(text, senderFilters, subjectFilters)) {
continue;
}
const previewEmails = extractEmails(text);
const previewTargetState = getTargetEmailMatchState(text, targetEmail);
const previewMatchesTarget = previewTargetState.matches;
if (targetEmail && previewEmails.length > 0 && !previewMatchesTarget) {
continue;
}
const code = extractVerificationCode(text, strictChatGPTCodeOnly);
if (code && previewMatchesTarget) {
if (excludedCodeSet.has(code)) {
log(`步骤 ${step}:跳过排除的验证码:${code}`, 'info');
continue;
}
if (seenCodes.has(code)) {
log(`步骤 ${step}:跳过已处理过的验证码:${code}`, 'info');
continue;
}
seenCodes.add(code);
persistSeenCodes();
const source = useFallback && existingMailIds.has(itemId) ? '回退匹配邮件' : '新邮件';
const timeLabel = itemTimestamp ? `,时间:${new Date(itemTimestamp).toLocaleString('zh-CN', { hour12: false })}` : '';
log(`步骤 ${step}:已找到验证码:${code}(来源:${source}${timeLabel}`, 'ok');
await sleep(1000);
return { ok: true, code, emailTimestamp: Date.now() };
}
simulateClick(item);
await sleepRandom(1200, 2200);
const openedText = document.body?.textContent || '';
const bodyCode = extractVerificationCode(openedText, strictChatGPTCodeOnly);
const openedTargetState = getTargetEmailMatchState(openedText, targetEmail);
if (targetEmail && openedTargetState.hasExplicitEmail && !openedTargetState.matches) {
continue;
}
if (bodyCode) {
if (excludedCodeSet.has(bodyCode)) {
log(`步骤 ${step}:跳过排除的验证码:${bodyCode}`, 'info');
continue;
}
if (seenCodes.has(bodyCode)) {
log(`步骤 ${step}:跳过已处理过的验证码:${bodyCode}`, 'info');
continue;
}
seenCodes.add(bodyCode);
persistSeenCodes();
const source = useFallback && existingMailIds.has(itemId) ? '回退匹配邮件正文' : '新邮件正文';
const timeLabel = itemTimestamp ? `,时间:${new Date(itemTimestamp).toLocaleString('zh-CN', { hour12: false })}` : '';
log(`步骤 ${step}:已在邮件正文中找到验证码:${bodyCode}(来源:${source}${timeLabel}`, 'ok');
await sleep(1000);
return { ok: true, code: bodyCode, emailTimestamp: Date.now() };
}
}
}
if (attempt === FALLBACK_AFTER + 1) {
log(`步骤 ${step}:连续 ${FALLBACK_AFTER} 次未发现新邮件,开始回退到首封匹配邮件`, 'warn');
}
if (attempt < maxAttempts) {
await sleepRandom(intervalMs, intervalMs + 1200);
}
}
throw new Error(
`${(maxAttempts * intervalMs / 1000).toFixed(0)} 秒后仍未在 2925 邮箱中找到新的匹配邮件。请手动检查收件箱。`
);
}
}
+2 -1
View File
@@ -11,6 +11,7 @@ const SCRIPT_SOURCE = (() => {
if (hostname === 'mail.163.com' || hostname.endsWith('.mail.163.com') || hostname === 'webmail.vip.163.com') return 'mail-163';
if (url.includes('duckduckgo.com/email/settings/autofill')) return 'duck-mail';
if (url.includes('chatgpt.com')) return 'chatgpt';
if (url.includes("2925.com")) return "mail-2925";
// VPS panel — detected dynamically since URL is configurable
return 'vps-panel';
})();
@@ -404,7 +405,7 @@ async function humanPause(min = 250, max = 850) {
// Auto-report ready on load
// Skip ready signal from child iframes of mail pages to avoid overwriting the top frame's registration
const _isMailChildFrame = (SCRIPT_SOURCE === 'qq-mail' || SCRIPT_SOURCE === 'mail-163' || SCRIPT_SOURCE === 'inbucket-mail') && window !== window.top;
const _isMailChildFrame = (SCRIPT_SOURCE === 'qq-mail' || SCRIPT_SOURCE === 'mail-163' || SCRIPT_SOURCE === 'mail-2925' || SCRIPT_SOURCE === 'inbucket-mail') && window !== window.top;
if (!_isMailChildFrame) {
reportReady();
}
+5
View File
@@ -136,6 +136,7 @@
<option value="163-vip">163 VIP 邮箱 (webmail.vip.163.com)</option>
<option value="qq">QQ 邮箱 (wx.mail.qq.com)</option>
<option value="inbucket">Inbucket(自定义主机)</option>
<option value="2925">2925 邮箱 (2925.com)</option>
</select>
<button id="btn-mail-login" class="btn btn-outline btn-sm" type="button" disabled>登录</button>
</div>
@@ -156,6 +157,10 @@
<button id="btn-cf-domain-mode" class="btn btn-outline btn-sm" type="button">添加</button>
</div>
</div>
<div class="data-row" id="row-email-prefix" style="display:none;">
<span class="data-label" id="label-email-prefix">邮箱前缀</span>
<input type="text" id="input-email-prefix" class="data-input" placeholder="例如 abc" />
</div>
<div class="data-row" id="row-inbucket-host" style="display:none;">
<span class="data-label">Inbucket</span>
<input type="text" id="input-inbucket-host" class="data-input" placeholder="填写主机或 https://主机地址" />
+69 -8
View File
@@ -73,6 +73,9 @@ const btnDeleteAllHotmailAccounts = document.getElementById('btn-delete-all-hotm
const btnToggleHotmailList = document.getElementById('btn-toggle-hotmail-list');
const hotmailListShell = document.getElementById('hotmail-list-shell');
const hotmailAccountsList = document.getElementById('hotmail-accounts-list');
const rowEmailPrefix = document.getElementById('row-email-prefix');
const labelEmailPrefix = document.getElementById('label-email-prefix');
const inputEmailPrefix = document.getElementById('input-email-prefix');
const rowInbucketHost = document.getElementById('row-inbucket-host');
const inputInbucketHost = document.getElementById('input-inbucket-host');
const rowInbucketMailbox = document.getElementById('row-inbucket-mailbox');
@@ -160,6 +163,10 @@ const MAIL_PROVIDER_LOGIN_CONFIGS = {
label: 'QQ 邮箱',
url: 'https://wx.mail.qq.com/',
},
'2925': {
label: '2925 邮箱',
url: 'https://2925.com/#/mailList',
},
};
// ============================================================
@@ -182,6 +189,10 @@ const LOG_LEVEL_LABELS = {
error: '错误',
};
function usesGeneratedAliasMailProvider(provider) {
return provider === '2925';
}
function showToast(message, type = 'error', duration = 4000) {
const toast = document.createElement('div');
toast.className = `toast toast-${type}`;
@@ -637,6 +648,7 @@ function collectSettingsPayload() {
customPassword: inputPassword.value,
mailProvider: selectMailProvider.value,
emailGenerator: selectEmailGenerator.value,
emailPrefix: inputEmailPrefix.value.trim(),
inbucketHost: inputInbucketHost.value.trim(),
inbucketMailbox: inputInbucketMailbox.value.trim(),
cloudflareDomain: selectedCloudflareDomain,
@@ -784,7 +796,7 @@ function applyAutoRunStatus(payload = currentAutoRun) {
inputRunCount.disabled = currentAutoRun.autoRunning;
btnAutoRun.disabled = currentAutoRun.autoRunning;
btnFetchEmail.disabled = locked;
btnFetchEmail.disabled = locked || usesGeneratedAliasMailProvider(selectMailProvider.value);
inputEmail.disabled = locked;
inputAutoSkipFailures.disabled = scheduled;
@@ -818,7 +830,7 @@ function applyAutoRunStatus(payload = currentAutoRun) {
setDefaultAutoRunButton();
inputEmail.disabled = false;
if (!locked) {
btnFetchEmail.disabled = false;
btnFetchEmail.disabled = usesGeneratedAliasMailProvider(selectMailProvider.value);
}
break;
}
@@ -880,6 +892,7 @@ function applySettingsState(state) {
inputSub2ApiGroup.value = state?.sub2apiGroupName || '';
selectMailProvider.value = state?.mailProvider || '163';
selectEmailGenerator.value = state?.emailGenerator || 'duck';
inputEmailPrefix.value = state?.emailPrefix || '';
inputInbucketHost.value = state?.inbucketHost || '';
inputInbucketMailbox.value = state?.inbucketMailbox || '';
renderCloudflareDomainOptions(state?.cloudflareDomain || '');
@@ -991,6 +1004,22 @@ function isCurrentEmailManagedByHotmail(state = latestState) {
return inputEmailValue === hotmailEmail || stateEmailValue === hotmailEmail;
}
function isCurrentEmailManagedByGeneratedAlias(provider = latestState?.mailProvider, state = latestState) {
const normalizedProvider = String(provider || '').trim();
if (!usesGeneratedAliasMailProvider(normalizedProvider)) {
return false;
}
const inputEmailValue = String(inputEmail.value || '').trim().toLowerCase();
const stateEmailValue = String(state?.email || '').trim().toLowerCase();
if (normalizedProvider === '2925') {
return inputEmailValue.endsWith('@2925.com') || stateEmailValue.endsWith('@2925.com');
}
return false;
}
function updateMailLoginButtonState() {
if (!btnMailLogin) {
return;
@@ -1206,10 +1235,13 @@ function renderHotmailAccounts() {
}
function updateMailProviderUI() {
const use2925 = selectMailProvider.value === '2925';
const useGeneratedAlias = usesGeneratedAliasMailProvider(selectMailProvider.value);
const useInbucket = selectMailProvider.value === 'inbucket';
const useHotmail = selectMailProvider.value === 'hotmail-api';
const useEmailGenerator = !useHotmail;
const useEmailGenerator = !useHotmail && !useGeneratedAlias;
updateMailLoginButtonState();
rowEmailPrefix.style.display = useGeneratedAlias ? '' : 'none';
rowInbucketHost.style.display = useInbucket ? '' : 'none';
rowInbucketMailbox.style.display = useInbucket ? '' : 'none';
const useCloudflare = selectEmailGenerator.value === 'cloudflare';
@@ -1228,18 +1260,23 @@ function updateMailProviderUI() {
if (hotmailSection) {
hotmailSection.style.display = useHotmail ? '' : 'none';
}
selectEmailGenerator.disabled = useHotmail;
labelEmailPrefix.textContent = '邮箱前缀';
inputEmailPrefix.placeholder = '例如 abc';
selectEmailGenerator.disabled = useHotmail || useGeneratedAlias;
btnFetchEmail.hidden = useHotmail;
inputEmail.readOnly = useHotmail;
inputEmail.readOnly = useHotmail || useGeneratedAlias;
const uiCopy = getEmailGeneratorUiCopy();
inputEmail.placeholder = useHotmail ? '由 Hotmail 账号池自动分配' : uiCopy.placeholder;
inputEmail.placeholder = useHotmail
? '由 Hotmail 账号池自动分配'
: (use2925 ? '步骤 3 自动生成 2925 邮箱并回填' : uiCopy.placeholder);
btnFetchEmail.disabled = useGeneratedAlias || isAutoRunLockedPhase();
if (!btnFetchEmail.disabled) {
btnFetchEmail.textContent = uiCopy.buttonLabel;
}
if (autoHintText) {
autoHintText.textContent = useHotmail
? '请先校验并选择一个 Hotmail 账号'
: '先自动获取邮箱,或手动粘贴邮箱后再继续';
: (useGeneratedAlias ? '步骤 3 会自动生成邮箱,无需手动获取' : '先自动获取邮箱,或手动粘贴邮箱后再继续');
}
if (useHotmail) {
inputEmail.value = getCurrentHotmailEmail();
@@ -1769,6 +1806,16 @@ document.querySelectorAll('.step-btn').forEach(btn => {
if (response?.error) {
throw new Error(response.error);
}
} else if (usesGeneratedAliasMailProvider(selectMailProvider.value)) {
const emailPrefix = inputEmailPrefix.value.trim();
if (!emailPrefix) {
showToast('请先填写 2925 邮箱前缀。', 'warn');
return;
}
const response = await chrome.runtime.sendMessage({ type: 'EXECUTE_STEP', source: 'sidepanel', payload: { step, emailPrefix } });
if (response?.error) {
throw new Error(response.error);
}
} else {
let email = inputEmail.value.trim();
if (!email) {
@@ -2291,7 +2338,13 @@ selectMailProvider.addEventListener('change', async () => {
const previousProvider = latestState?.mailProvider || '';
const nextProvider = selectMailProvider.value;
updateMailProviderUI();
if (previousProvider === 'hotmail-api' && nextProvider !== 'hotmail-api' && isCurrentEmailManagedByHotmail()) {
const leavingHotmail = previousProvider === 'hotmail-api'
&& nextProvider !== 'hotmail-api'
&& isCurrentEmailManagedByHotmail();
const leavingGeneratedAlias = previousProvider !== nextProvider
&& usesGeneratedAliasMailProvider(previousProvider)
&& isCurrentEmailManagedByGeneratedAlias(previousProvider);
if (leavingHotmail || leavingGeneratedAlias) {
await clearRegistrationEmail({ silent: true }).catch(() => { });
}
markSettingsDirty(true);
@@ -2379,6 +2432,14 @@ inputSub2ApiGroup.addEventListener('blur', () => {
saveSettings({ silent: true }).catch(() => { });
});
inputEmailPrefix.addEventListener('input', () => {
markSettingsDirty(true);
scheduleSettingsAutoSave();
});
inputEmailPrefix.addEventListener('blur', () => {
saveSettings({ silent: true }).catch(() => {});
});
inputInbucketMailbox.addEventListener('input', () => {
markSettingsDirty(true);
scheduleSettingsAutoSave();