| let currentConfig = null; |
|
|
| |
| function copyToClipboard(text, button) { |
| navigator.clipboard.writeText(text).then(() => { |
| |
| const originalText = button.innerHTML; |
| button.innerHTML = '✓'; |
| button.classList.add('copied'); |
|
|
| |
| setTimeout(() => { |
| button.innerHTML = originalText; |
| button.classList.remove('copied'); |
| }, 2000); |
| }).catch(err => { |
| console.error('复制失败:', err); |
| alert('复制失败,请手动复制'); |
| }); |
| } |
|
|
| |
| function switchTab(tabName) { |
| |
| document.querySelectorAll('.tab-content').forEach(content => { |
| content.classList.remove('active'); |
| }); |
| |
| document.querySelectorAll('.tab-button').forEach(button => { |
| button.classList.remove('active'); |
| }); |
|
|
| |
| document.getElementById('tab-' + tabName).classList.add('active'); |
| |
| event.target.classList.add('active'); |
| } |
|
|
| |
| async function refreshPage() { |
| try { |
| await fetch(`/${window.ADMIN_PATH}/accounts/reload`, { |
| method: 'POST' |
| }); |
| } catch (e) { |
| console.error('账户同步失败:', e); |
| } |
| window.location.reload(); |
| } |
|
|
| |
| async function handleApiResponse(response) { |
| if (!response.ok) { |
| const errorText = await response.text(); |
| let errorMsg; |
| try { |
| const errorJson = JSON.parse(errorText); |
| errorMsg = errorJson.detail || errorJson.message || errorText; |
| } catch { |
| errorMsg = errorText; |
| } |
| throw new Error(`HTTP $${response.status}: $${errorMsg}`); |
| } |
| return await response.json(); |
| } |
|
|
| async function showEditConfig() { |
| const config = await fetch(`/${window.ADMIN_PATH}/accounts-config`).then(r => r.json()); |
| currentConfig = config.accounts; |
| const json = JSON.stringify(config.accounts, null, 2); |
| document.getElementById('jsonEditor').value = json; |
| document.getElementById('jsonError').classList.remove('show'); |
| document.getElementById('jsonModal').classList.add('show'); |
|
|
| |
| document.getElementById('jsonEditor').addEventListener('input', validateJSON); |
| } |
|
|
| function validateJSON() { |
| const editor = document.getElementById('jsonEditor'); |
| const errorDiv = document.getElementById('jsonError'); |
| try { |
| JSON.parse(editor.value); |
| errorDiv.classList.remove('show'); |
| errorDiv.textContent = ''; |
| return true; |
| } catch (e) { |
| errorDiv.classList.add('show'); |
| errorDiv.textContent = '❌ JSON 格式错误: ' + e.message; |
| return false; |
| } |
| } |
|
|
| function closeModal() { |
| document.getElementById('jsonModal').classList.remove('show'); |
| document.getElementById('jsonEditor').removeEventListener('input', validateJSON); |
| } |
|
|
| async function saveConfig() { |
| if (!validateJSON()) { |
| alert('JSON 格式错误,请修正后再保存'); |
| return; |
| } |
|
|
| const newJson = document.getElementById('jsonEditor').value; |
| const originalJson = JSON.stringify(currentConfig, null, 2); |
|
|
| if (newJson === originalJson) { |
| closeModal(); |
| return; |
| } |
|
|
| try { |
| const data = JSON.parse(newJson); |
| const response = await fetch(`/${window.ADMIN_PATH}/accounts-config`, { |
| method: 'PUT', |
| headers: { 'Content-Type': 'application/json' }, |
| body: JSON.stringify(data) |
| }); |
|
|
| await handleApiResponse(response); |
| closeModal(); |
| refreshPage(); |
| } catch (error) { |
| console.error('保存失败:', error); |
| alert('更新失败: ' + error.message); |
| } |
| } |
|
|
| async function deleteAccount(accountId) { |
| if (!confirm(`确定删除账户 $${accountId}?`)) return; |
|
|
| try { |
| const response = await fetch(`/${window.ADMIN_PATH}/accounts/${accountId}`, { |
| method: 'DELETE' |
| }); |
|
|
| await handleApiResponse(response); |
| refreshPage(); |
| } catch (error) { |
| console.error('删除失败:', error); |
| alert('删除失败: ' + error.message); |
| } |
| } |
|
|
| async function disableAccount(accountId) { |
| try { |
| const response = await fetch(`/${window.ADMIN_PATH}/accounts/${accountId}/disable`, { |
| method: 'PUT' |
| }); |
|
|
| await handleApiResponse(response); |
| refreshPage(); |
| } catch (error) { |
| console.error('禁用失败:', error); |
| alert('禁用失败: ' + error.message); |
| } |
| } |
|
|
| async function enableAccount(accountId) { |
| try { |
| const response = await fetch(`/${window.ADMIN_PATH}/accounts/${accountId}/enable`, { |
| method: 'PUT' |
| }); |
|
|
| await handleApiResponse(response); |
| refreshPage(); |
| } catch (error) { |
| console.error('启用失败:', error); |
| alert('启用失败: ' + error.message); |
| } |
| } |
|
|
| async function refreshAccount(accountId) { |
| if (!confirm(`确定刷新账户 ${accountId} 的凭证?\n这将通过重新登录来获取新的凭证。`)) return; |
|
|
| try { |
| const response = await fetch(`/${window.ADMIN_PATH}/login/start`, { |
| method: 'POST', |
| headers: { 'Content-Type': 'application/json' }, |
| body: JSON.stringify([accountId]) |
| }); |
|
|
| const result = await handleApiResponse(response); |
| alert(`刷新任务已启动!\n任务ID: ${result.task.id}\n请在日志中查看进度。`); |
|
|
| |
| startLoginPolling(result.task.id); |
| } catch (error) { |
| console.error('刷新失败:', error); |
| alert('刷新失败: ' + error.message); |
| } |
| } |
|
|
| |
| let loginPollingInterval = null; |
| function startLoginPolling(taskId) { |
| if (loginPollingInterval) { |
| clearInterval(loginPollingInterval); |
| } |
|
|
| loginPollingInterval = setInterval(async () => { |
| try { |
| const response = await fetch(`/${window.ADMIN_PATH}/login/task/${taskId}`); |
| const result = await response.json(); |
| const task = result.task; |
|
|
| if (task.status === 'success' || task.status === 'failed') { |
| clearInterval(loginPollingInterval); |
| loginPollingInterval = null; |
|
|
| |
| await fetch(`/${window.ADMIN_PATH}/accounts/reload`, { |
| method: 'POST' |
| }); |
|
|
| |
| setTimeout(() => { |
| refreshPage(); |
| }, 1000); |
| } |
| } catch (error) { |
| console.error('获取刷新进度失败:', error); |
| clearInterval(loginPollingInterval); |
| loginPollingInterval = null; |
| } |
| }, 2000); |
| } |
|
|
| |
| async function handleFileUpload(event) { |
| const files = event.target.files; |
| if (!files.length) return; |
|
|
| let newAccounts = []; |
| for (const file of files) { |
| try { |
| const text = await file.text(); |
| const data = JSON.parse(text); |
| if (Array.isArray(data)) { |
| newAccounts.push(...data); |
| } else { |
| newAccounts.push(data); |
| } |
| } catch (e) { |
| alert(`文件 $${file.name} 解析失败: $${e.message}`); |
| event.target.value = ''; |
| return; |
| } |
| } |
|
|
| if (!newAccounts.length) { |
| alert('未找到有效账户数据'); |
| event.target.value = ''; |
| return; |
| } |
|
|
| try { |
| |
| const configResp = await fetch(`/${window.ADMIN_PATH}/accounts-config`); |
| const configData = await handleApiResponse(configResp); |
| const existing = configData.accounts || []; |
|
|
| |
| const idToIndex = new Map(); |
| existing.forEach((acc, idx) => { |
| if (acc.id) idToIndex.set(acc.id, idx); |
| }); |
|
|
| |
| let added = 0; |
| let updated = 0; |
| for (const acc of newAccounts) { |
| if (!acc.secure_c_ses || !acc.csesidx || !acc.config_id) continue; |
| const accId = acc.id || `account_${existing.length + added + 1}`; |
| acc.id = accId; |
|
|
| if (idToIndex.has(accId)) { |
| |
| existing[idToIndex.get(accId)] = acc; |
| updated++; |
| } else { |
| |
| existing.push(acc); |
| idToIndex.set(accId, existing.length - 1); |
| added++; |
| } |
| } |
|
|
| if (added === 0 && updated === 0) { |
| alert('没有有效账户可导入'); |
| event.target.value = ''; |
| return; |
| } |
|
|
| |
| const response = await fetch(`/${window.ADMIN_PATH}/accounts-config`, { |
| method: 'PUT', |
| headers: { 'Content-Type': 'application/json' }, |
| body: JSON.stringify(existing) |
| }); |
|
|
| await handleApiResponse(response); |
| event.target.value = ''; |
| refreshPage(); |
| } catch (error) { |
| console.error('导入失败:', error); |
| alert('导入失败: ' + error.message); |
| event.target.value = ''; |
| } |
| } |
|
|
| |
| document.getElementById('jsonModal').addEventListener('click', function (e) { |
| if (e.target === this) { |
| closeModal(); |
| } |
| }); |
|
|
| |
|
|
| |
| function updateProxyHealthCheckOptions() { |
| const healthCheckEnabled = document.getElementById('setting-proxy-health-check').checked; |
| const optionsDiv = document.getElementById('proxy-health-check-options'); |
| const strategySelect = document.getElementById('setting-proxy-check-fail-strategy'); |
| const retryCountItem = document.getElementById('proxy-retry-count-item'); |
|
|
| |
| if (optionsDiv) { |
| optionsDiv.style.display = healthCheckEnabled ? 'block' : 'none'; |
| } |
|
|
| |
| if (retryCountItem && strategySelect) { |
| retryCountItem.style.display = strategySelect.value === 'switch_then_direct' ? 'block' : 'none'; |
| } |
| } |
|
|
| |
| function initProxyHealthCheckListeners() { |
| const healthCheckbox = document.getElementById('setting-proxy-health-check'); |
| const strategySelect = document.getElementById('setting-proxy-check-fail-strategy'); |
|
|
| if (healthCheckbox) { |
| healthCheckbox.addEventListener('change', updateProxyHealthCheckOptions); |
| } |
| if (strategySelect) { |
| strategySelect.addEventListener('change', updateProxyHealthCheckOptions); |
| } |
| } |
|
|
| async function loadSettings() { |
| try { |
| const response = await fetch(`/${window.ADMIN_PATH}/settings`); |
| const settings = await handleApiResponse(response); |
|
|
| |
| document.getElementById('setting-api-key').value = settings.basic?.api_key || ''; |
| document.getElementById('setting-base-url').value = settings.basic?.base_url || ''; |
| document.getElementById('setting-proxy').value = settings.basic?.proxy || ''; |
|
|
| |
| |
| const proxyPoolArray = settings.basic?.proxy_pool || []; |
| document.getElementById('setting-proxy-pool').value = proxyPoolArray.join('\n'); |
|
|
| |
| document.getElementById('setting-proxy-strategy').value = settings.basic?.proxy_strategy || 'random'; |
|
|
| |
| document.getElementById('setting-proxy-health-check').checked = settings.basic?.proxy_health_check ?? false; |
|
|
| |
| document.getElementById('setting-proxy-check-fail-strategy').value = settings.basic?.proxy_check_fail_strategy || 'switch_then_direct'; |
| document.getElementById('setting-proxy-check-retry-count').value = settings.basic?.proxy_check_retry_count || 3; |
|
|
| |
| document.getElementById('setting-proxy-timeout').value = settings.basic?.proxy_timeout || 10; |
|
|
| |
| updateProxyHealthCheckOptions(); |
|
|
| |
| document.getElementById('setting-mail-api').value = settings.basic?.mail_api || ''; |
| document.getElementById('setting-mail-admin-key').value = settings.basic?.mail_admin_key || ''; |
| document.getElementById('setting-google-mail').value = settings.basic?.google_mail || ''; |
| document.getElementById('setting-email-domain').value = settings.basic?.email_domain?.join(',') || ''; |
| document.getElementById('setting-register-number').value = settings.basic?.register_number || 5; |
|
|
| |
| document.getElementById('setting-auto-register-enabled').checked = settings.auto_register?.enabled ?? false; |
| document.getElementById('setting-auto-register-cron').value = settings.auto_register?.cron || ''; |
|
|
| |
| document.getElementById('setting-image-enabled').checked = settings.image_generation?.enabled ?? true; |
| const supportedModels = settings.image_generation?.supported_models || []; |
| document.querySelectorAll('#setting-image-models input[type="checkbox"]').forEach(cb => { |
| cb.checked = supportedModels.includes(cb.value); |
| }); |
|
|
| |
| document.getElementById('setting-max-new-session').value = settings.retry?.max_new_session_tries || 5; |
| document.getElementById('setting-max-retries').value = settings.retry?.max_request_retries || 3; |
| document.getElementById('setting-max-switch').value = settings.retry?.max_account_switch_tries || 5; |
| document.getElementById('setting-failure-threshold').value = settings.retry?.account_failure_threshold || 3; |
| document.getElementById('setting-cooldown').value = settings.retry?.rate_limit_cooldown_seconds || 600; |
| document.getElementById('setting-cache-ttl').value = settings.retry?.session_cache_ttl_seconds || 3600; |
|
|
| |
| document.getElementById('setting-verification-retry-enabled').checked = settings.retry?.verification_retry_enabled ?? false; |
| document.getElementById('setting-verification-retries').value = settings.retry?.max_verification_retries || 3; |
| document.getElementById('setting-verification-interval').value = settings.retry?.verification_retry_interval_seconds || 5; |
|
|
| |
| document.getElementById('setting-logo-url').value = settings.public_display?.logo_url || ''; |
| document.getElementById('setting-chat-url').value = settings.public_display?.chat_url || ''; |
| document.getElementById('setting-session-hours').value = settings.session?.expire_hours || 24; |
| } catch (error) { |
| console.error('加载设置失败:', error); |
| alert('加载设置失败: ' + error.message); |
| } |
| } |
|
|
| async function saveSettings() { |
| try { |
| |
| const supportedModels = []; |
| document.querySelectorAll('#setting-image-models input[type="checkbox"]:checked').forEach(cb => { |
| supportedModels.push(cb.value); |
| }); |
|
|
| |
| |
| const proxyPoolText = document.getElementById('setting-proxy-pool').value; |
| const proxyPoolArray = proxyPoolText |
| .split('\n') |
| .map(line => line.trim()) |
| .filter(line => line.length > 0); |
|
|
| const settings = { |
| basic: { |
| api_key: document.getElementById('setting-api-key').value, |
| base_url: document.getElementById('setting-base-url').value, |
| proxy: document.getElementById('setting-proxy').value, |
|
|
| |
| proxy_pool: proxyPoolArray, |
| proxy_strategy: document.getElementById('setting-proxy-strategy').value, |
| proxy_health_check: document.getElementById('setting-proxy-health-check').checked, |
| proxy_timeout: parseInt(document.getElementById('setting-proxy-timeout').value) || 10, |
| |
| proxy_check_fail_strategy: document.getElementById('setting-proxy-check-fail-strategy').value, |
| proxy_check_retry_count: parseInt(document.getElementById('setting-proxy-check-retry-count').value) || 3, |
|
|
| mail_api: document.getElementById('setting-mail-api').value, |
| mail_admin_key: document.getElementById('setting-mail-admin-key').value, |
| google_mail: document.getElementById('setting-google-mail').value, |
| email_domain: document.getElementById('setting-email-domain').value.split(',').map(d => d.trim()).filter(d => d), |
| register_number: parseInt(document.getElementById('setting-register-number').value) || 5 |
| }, |
| auto_register: { |
| enabled: document.getElementById('setting-auto-register-enabled').checked, |
| cron: document.getElementById('setting-auto-register-cron').value.trim() |
| }, |
| image_generation: { |
| enabled: document.getElementById('setting-image-enabled').checked, |
| supported_models: supportedModels |
| }, |
| retry: { |
| max_new_session_tries: parseInt(document.getElementById('setting-max-new-session').value) || 5, |
| max_request_retries: parseInt(document.getElementById('setting-max-retries').value) || 3, |
| max_account_switch_tries: parseInt(document.getElementById('setting-max-switch').value) || 5, |
| account_failure_threshold: parseInt(document.getElementById('setting-failure-threshold').value) || 3, |
| rate_limit_cooldown_seconds: parseInt(document.getElementById('setting-cooldown').value) || 600, |
| session_cache_ttl_seconds: parseInt(document.getElementById('setting-cache-ttl').value) || 3600, |
|
|
| |
| verification_retry_enabled: document.getElementById('setting-verification-retry-enabled').checked, |
| max_verification_retries: parseInt(document.getElementById('setting-verification-retries').value) || 3, |
| verification_retry_interval_seconds: parseInt(document.getElementById('setting-verification-interval').value) || 5 |
| }, |
| public_display: { |
| logo_url: document.getElementById('setting-logo-url').value, |
| chat_url: document.getElementById('setting-chat-url').value |
| }, |
| session: { |
| expire_hours: parseInt(document.getElementById('setting-session-hours').value) || 24 |
| } |
| }; |
|
|
| const response = await fetch(`/${window.ADMIN_PATH}/settings`, { |
| method: 'PUT', |
| headers: { 'Content-Type': 'application/json' }, |
| body: JSON.stringify(settings) |
| }); |
|
|
| await handleApiResponse(response); |
|
|
| |
| window.location.reload(); |
| } catch (error) { |
| console.error('保存设置失败:', error); |
| alert('保存设置失败: ' + error.message); |
| } |
| } |
|
|
| |
| document.addEventListener('DOMContentLoaded', async function () { |
| loadSettings(); |
|
|
| |
| initProxyHealthCheckListeners(); |
|
|
| |
| try { |
| await fetch(`/${window.ADMIN_PATH}/accounts/reload`, { |
| method: 'POST' |
| }); |
| console.log('✅ 账户数据已同步'); |
| } catch (error) { |
| console.error('账户同步失败:', error); |
| } |
|
|
| |
| checkRunningRegisterTask(); |
|
|
| |
| startAccountReloadPolling(); |
| }); |
|
|
| |
| let registerPollingInterval = null; |
| let lastSuccessCount = 0; |
|
|
| |
| async function checkRunningRegisterTask() { |
| try { |
| const response = await fetch(`/${window.ADMIN_PATH}/register/current`); |
| const result = await response.json(); |
|
|
| if (result.task && (result.task.status === 'running' || result.task.status === 'pending')) { |
| |
| document.getElementById('register-progress').style.display = 'block'; |
| lastSuccessCount = result.task.success_count || 0; |
| startRegisterPolling(result.task.id); |
| } |
| } catch (error) { |
| console.error('检查注册任务失败:', error); |
| } |
| } |
|
|
| |
| function startAccountReloadPolling() { |
| setInterval(async () => { |
| try { |
| await fetch(`/${window.ADMIN_PATH}/accounts/reload`, { |
| method: 'POST' |
| }); |
| console.log('[自动刷新] 账户列表已更新'); |
| } catch (error) { |
| console.error('自动刷新账户失败:', error); |
| } |
| }, 60000); |
| } |
|
|
| |
| function showRegisterModal() { |
| |
| const emailDomain = document.getElementById('setting-email-domain').value; |
| const domains = emailDomain ? emailDomain.split(',').map(d => d.trim()).filter(d => d) : []; |
|
|
| |
| const select = document.getElementById('register-domain'); |
| select.innerHTML = '<option value="">随机选择域名</option>'; |
| domains.forEach(domain => { |
| const option = document.createElement('option'); |
| option.value = domain; |
| option.textContent = domain; |
| select.appendChild(option); |
| }); |
|
|
| |
| const registerNumber = parseInt(document.getElementById('setting-register-number').value) || 5; |
| document.getElementById('register-count').value = registerNumber; |
|
|
| document.getElementById('registerModal').style.display = 'flex'; |
| } |
|
|
| |
| function closeRegisterModal() { |
| document.getElementById('registerModal').style.display = 'none'; |
| } |
|
|
| |
| async function startRegister() { |
| const count = parseInt(document.getElementById('register-count').value); |
| const domain = document.getElementById('register-domain').value; |
|
|
| if (!count || count < 1 || count > 50) { |
| alert('请输入有效的注册数量(1-50)'); |
| return; |
| } |
|
|
| try { |
| const response = await fetch(`/${window.ADMIN_PATH}/register/start`, { |
| method: 'POST', |
| headers: { 'Content-Type': 'application/json' }, |
| body: JSON.stringify({ |
| count: count, |
| domain: domain || null |
| }) |
| }); |
|
|
| const result = await handleApiResponse(response); |
|
|
| closeRegisterModal(); |
|
|
| |
| document.getElementById('register-progress').style.display = 'block'; |
|
|
| |
| startRegisterPolling(result.task.id); |
|
|
| } catch (error) { |
| console.error('启动注册失败:', error); |
| alert('启动注册失败: ' + error.message); |
| } |
| } |
|
|
| |
| function startRegisterPolling(taskId) { |
| updateRegisterProgress(taskId); |
|
|
| registerPollingInterval = setInterval(() => { |
| updateRegisterProgress(taskId); |
| }, 2000); |
| } |
|
|
| |
| async function updateRegisterProgress(taskId) { |
| try { |
| const response = await fetch(`/${window.ADMIN_PATH}/register/task/${taskId}`); |
| const result = await response.json(); |
| const task = result.task; |
|
|
| |
| document.getElementById('reg-current').textContent = task.progress || 0; |
| document.getElementById('reg-total').textContent = task.count || 0; |
| document.getElementById('reg-success').textContent = task.success_count || 0; |
| document.getElementById('reg-fail').textContent = task.fail_count || 0; |
|
|
| const total = task.count || 1; |
| const current = task.progress || 0; |
| const percentage = Math.round((current / total) * 100); |
| document.getElementById('reg-progress-bar').style.width = percentage + '%'; |
|
|
| const successRate = current > 0 ? Math.round((task.success_count / current) * 100) : 0; |
| document.getElementById('reg-rate').textContent = successRate + '%'; |
|
|
| |
| const currentSuccessCount = task.success_count || 0; |
| if (currentSuccessCount > lastSuccessCount) { |
| lastSuccessCount = currentSuccessCount; |
|
|
| |
| try { |
| await fetch(`/${window.ADMIN_PATH}/accounts/reload`, { |
| method: 'POST' |
| }); |
| console.log(`[注册] 成功 ${currentSuccessCount} 个,账户列表已刷新`); |
| } catch (error) { |
| console.error('刷新账户列表失败:', error); |
| } |
| } |
|
|
| |
| if (task.status === 'success' || task.status === 'failed') { |
| clearInterval(registerPollingInterval); |
| registerPollingInterval = null; |
| lastSuccessCount = 0; |
|
|
| |
| try { |
| await fetch(`/${window.ADMIN_PATH}/accounts/reload`, { |
| method: 'POST' |
| }); |
| } catch (error) { |
| console.error('最终刷新账户失败:', error); |
| } |
|
|
| |
| setTimeout(() => { |
| window.location.reload(); |
| }, 3000); |
| } |
| } catch (error) { |
| console.error('获取注册进度失败:', error); |
| clearInterval(registerPollingInterval); |
| registerPollingInterval = null; |
| lastSuccessCount = 0; |
| } |
| } |
|
|
| |
| async function stopRegister() { |
| if (!confirm('确定要停止当前注册任务吗?\n已成功注册的账户会保留,正在注册的账户会被中止。')) { |
| return; |
| } |
|
|
| try { |
| const response = await fetch(`/${window.ADMIN_PATH}/register/stop`, { |
| method: 'POST' |
| }); |
|
|
| const result = await handleApiResponse(response); |
|
|
| if (result.status === 'success') { |
| alert('已发送停止信号,正在中止注册任务...'); |
| } else { |
| alert(result.message || '停止失败'); |
| } |
| } catch (error) { |
| console.error('停止注册失败:', error); |
| alert('停止失败: ' + error.message); |
| } |
| } |
|
|