feat(s2a): Add S2A configuration profiles management system

- Add new `/api/s2a/profiles` endpoint supporting GET, POST, DELETE operations
- Create `s2a_profiles` database table with fields for API configuration, concurrency, priority, group IDs, and proxy settings
- Implement database methods: `GetS2AProfiles()`, `AddS2AProfile()`, `DeleteS2AProfile()`
- Add S2AProfile struct to database models with JSON serialization support
- Implement profile management UI in S2AConfig page with save, load, and delete functionality
- Add profile list display with ability to apply saved configurations
- Add S2AProfile type definition to frontend types
- Enable users to save and reuse S2A configurations as presets for faster setup
This commit is contained in:
2026-02-07 13:31:51 +08:00
parent 02ddb48f21
commit 3af01abc76
4 changed files with 539 additions and 206 deletions

View File

@@ -123,6 +123,7 @@ func startServer(cfg *config.Config) {
mux.HandleFunc("/api/s2a/proxy/", api.CORS(handleS2AProxy)) // 通配代理 mux.HandleFunc("/api/s2a/proxy/", api.CORS(handleS2AProxy)) // 通配代理
mux.HandleFunc("/api/s2a/clean-errors", api.CORS(api.HandleCleanErrorAccounts)) // 清理错误账号 mux.HandleFunc("/api/s2a/clean-errors", api.CORS(api.HandleCleanErrorAccounts)) // 清理错误账号
mux.HandleFunc("/api/s2a/cleaner/settings", api.CORS(handleCleanerSettings)) // 清理服务设置 mux.HandleFunc("/api/s2a/cleaner/settings", api.CORS(handleCleanerSettings)) // 清理服务设置
mux.HandleFunc("/api/s2a/profiles", api.CORS(handleS2AProfiles)) // S2A 配置预设管理
// 统计 API // 统计 API
mux.HandleFunc("/api/stats/max-rpm", api.CORS(api.HandleGetMaxRPM)) // 今日最高 RPM mux.HandleFunc("/api/stats/max-rpm", api.CORS(api.HandleGetMaxRPM)) // 今日最高 RPM
@@ -1138,6 +1139,62 @@ func handleCleanerSettings(w http.ResponseWriter, r *http.Request) {
} }
} }
// handleS2AProfiles GET/POST/DELETE /api/s2a/profiles
func handleS2AProfiles(w http.ResponseWriter, r *http.Request) {
if database.Instance == nil {
api.Error(w, http.StatusInternalServerError, "数据库未初始化")
return
}
switch r.Method {
case http.MethodGet:
profiles, err := database.Instance.GetS2AProfiles()
if err != nil {
api.Error(w, http.StatusInternalServerError, fmt.Sprintf("获取配置预设失败: %v", err))
return
}
// 确保 group_ids 解析为 JSON
// (数据库层返回的是 JSON string, 这里前端可以直接用,或者我们在 Go 里转一下)
// 由于 database.S2AProfile 定义 GroupIDs 为 string我们直接返回即可前端解析
api.Success(w, profiles)
case http.MethodPost:
var p database.S2AProfile
if err := json.NewDecoder(r.Body).Decode(&p); err != nil {
api.Error(w, http.StatusBadRequest, "请求格式错误")
return
}
if p.Name == "" {
api.Error(w, http.StatusBadRequest, "配置名称不能为空")
return
}
id, err := database.Instance.AddS2AProfile(p)
if err != nil {
api.Error(w, http.StatusInternalServerError, fmt.Sprintf("保存配置预设失败: %v", err))
return
}
p.ID = id
api.Success(w, p)
case http.MethodDelete:
idStr := r.URL.Query().Get("id")
id, err := strconv.ParseInt(idStr, 10, 64)
if err != nil {
api.Error(w, http.StatusBadRequest, "无效的 ID")
return
}
if err := database.Instance.DeleteS2AProfile(id); err != nil {
api.Error(w, http.StatusInternalServerError, fmt.Sprintf("删除配置预设失败: %v", err))
return
}
api.Success(w, map[string]string{"message": "已删除"})
default:
api.Error(w, http.StatusMethodNotAllowed, "不支持的方法")
}
}
// handleProxyTest POST /api/proxy/test - 测试代理连接 // handleProxyTest POST /api/proxy/test - 测试代理连接
func handleProxyTest(w http.ResponseWriter, r *http.Request) { func handleProxyTest(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost { if r.Method != http.MethodPost {

View File

@@ -23,6 +23,20 @@ type TeamOwner struct {
LastCheckedAt *time.Time `json:"last_checked_at,omitempty"` LastCheckedAt *time.Time `json:"last_checked_at,omitempty"`
} }
// S2AProfile S2A 配置预设
type S2AProfile struct {
ID int64 `json:"id"`
Name string `json:"name"`
APIBase string `json:"api_base"`
AdminKey string `json:"admin_key"`
Concurrency int `json:"concurrency"`
Priority int `json:"priority"`
GroupIDs string `json:"group_ids"` // JSON array string
ProxyEnabled bool `json:"proxy_enabled"`
ProxyAddress string `json:"proxy_address"`
CreatedAt time.Time `json:"created_at"`
}
// DB 数据库管理器 // DB 数据库管理器
type DB struct { type DB struct {
db *sql.DB db *sql.DB
@@ -161,6 +175,20 @@ func (d *DB) createTables() error {
CREATE INDEX IF NOT EXISTS idx_app_logs_timestamp ON app_logs(timestamp); CREATE INDEX IF NOT EXISTS idx_app_logs_timestamp ON app_logs(timestamp);
CREATE INDEX IF NOT EXISTS idx_app_logs_module ON app_logs(module); CREATE INDEX IF NOT EXISTS idx_app_logs_module ON app_logs(module);
CREATE INDEX IF NOT EXISTS idx_app_logs_level ON app_logs(level); CREATE INDEX IF NOT EXISTS idx_app_logs_level ON app_logs(level);
-- S2A 配置预设表
CREATE TABLE IF NOT EXISTS s2a_profiles (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
api_base TEXT NOT NULL,
admin_key TEXT NOT NULL,
concurrency INTEGER DEFAULT 2,
priority INTEGER DEFAULT 0,
group_ids TEXT,
proxy_enabled INTEGER DEFAULT 0,
proxy_address TEXT,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
`) `)
return err return err
} }
@@ -1260,3 +1288,51 @@ func (d *DB) Close() error {
} }
return nil return nil
} }
// GetS2AProfiles 获取所有 S2A 配置预设
func (d *DB) GetS2AProfiles() ([]S2AProfile, error) {
rows, err := d.db.Query(`
SELECT id, name, api_base, admin_key, concurrency, priority, group_ids, proxy_enabled, proxy_address, created_at
FROM s2a_profiles
ORDER BY created_at DESC
`)
if err != nil {
return nil, err
}
defer rows.Close()
var profiles []S2AProfile
for rows.Next() {
var p S2AProfile
var proxyEnabled int
err := rows.Scan(&p.ID, &p.Name, &p.APIBase, &p.AdminKey, &p.Concurrency, &p.Priority, &p.GroupIDs, &proxyEnabled, &p.ProxyAddress, &p.CreatedAt)
if err != nil {
continue
}
p.ProxyEnabled = proxyEnabled == 1
profiles = append(profiles, p)
}
return profiles, nil
}
// AddS2AProfile 添加 S2A 配置预设
func (d *DB) AddS2AProfile(p S2AProfile) (int64, error) {
proxyEnabled := 0
if p.ProxyEnabled {
proxyEnabled = 1
}
result, err := d.db.Exec(`
INSERT INTO s2a_profiles (name, api_base, admin_key, concurrency, priority, group_ids, proxy_enabled, proxy_address, created_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)
`, p.Name, p.APIBase, p.AdminKey, p.Concurrency, p.Priority, p.GroupIDs, proxyEnabled, p.ProxyAddress)
if err != nil {
return 0, err
}
return result.LastInsertId()
}
// DeleteS2AProfile 删除 S2A 配置预设
func (d *DB) DeleteS2AProfile(id int64) error {
_, err := d.db.Exec("DELETE FROM s2a_profiles WHERE id = ?", id)
return err
}

View File

@@ -1,7 +1,8 @@
import { useState, useEffect } from 'react' import { useState, useEffect, useCallback } from 'react'
import { TestTube, CheckCircle, XCircle, Loader2, Save, Server, Plus, X, Globe, ToggleLeft, ToggleRight } from 'lucide-react' import { TestTube, CheckCircle, XCircle, Loader2, Save, Server, Plus, X, Globe, ToggleLeft, ToggleRight, Bookmark, Trash2, Download } from 'lucide-react'
import { Card, CardHeader, CardTitle, CardContent, Button, Input } from '../components/common' import { Card, CardHeader, CardTitle, CardContent, Button, Input } from '../components/common'
import { useConfig } from '../hooks/useConfig' import { useConfig } from '../hooks/useConfig'
import type { S2AProfile } from '../types'
export default function S2AConfig() { export default function S2AConfig() {
const { const {
@@ -30,6 +31,25 @@ export default function S2AConfig() {
const [proxyEnabled, setProxyEnabled] = useState(false) const [proxyEnabled, setProxyEnabled] = useState(false)
const [proxyAddress, setProxyAddress] = useState('') const [proxyAddress, setProxyAddress] = useState('')
// 预设管理
const [profiles, setProfiles] = useState<S2AProfile[]>([])
const [profileName, setProfileName] = useState('')
const [showSavePreset, setShowSavePreset] = useState(false)
const [savingPreset, setSavingPreset] = useState(false)
// 加载预设列表
const fetchProfiles = useCallback(async () => {
try {
const res = await fetch('/api/s2a/profiles')
const data = await res.json()
if (data.code === 0 && data.data) {
setProfiles(data.data)
}
} catch (error) {
console.error('Failed to fetch profiles:', error)
}
}, [])
// 从服务器加载配置 // 从服务器加载配置
const fetchConfig = async () => { const fetchConfig = async () => {
setLoading(true) setLoading(true)
@@ -54,15 +74,13 @@ export default function S2AConfig() {
useEffect(() => { useEffect(() => {
fetchConfig() fetchConfig()
}, []) fetchProfiles()
}, [fetchProfiles])
const handleTestConnection = async () => { const handleTestConnection = async () => {
setTesting(true) setTesting(true)
setTestResult(null) setTestResult(null)
// 先保存配置
await handleSave() await handleSave()
const result = await testConnection() const result = await testConnection()
setTestResult(result) setTestResult(result)
setTesting(false) setTesting(false)
@@ -78,8 +96,8 @@ export default function S2AConfig() {
body: JSON.stringify({ body: JSON.stringify({
s2a_api_base: s2aApiBase, s2a_api_base: s2aApiBase,
s2a_admin_key: s2aAdminKey, s2a_admin_key: s2aAdminKey,
concurrency: concurrency, concurrency,
priority: priority, priority,
group_ids: groupIds, group_ids: groupIds,
proxy_enabled: proxyEnabled, proxy_enabled: proxyEnabled,
default_proxy: proxyAddress, default_proxy: proxyAddress,
@@ -111,6 +129,72 @@ export default function S2AConfig() {
setGroupIds(groupIds.filter(g => g !== id)) setGroupIds(groupIds.filter(g => g !== id))
} }
// 保存为预设
const handleSavePreset = async () => {
if (!profileName.trim()) return
setSavingPreset(true)
try {
const res = await fetch('/api/s2a/profiles', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
name: profileName.trim(),
api_base: s2aApiBase,
admin_key: s2aAdminKey,
concurrency,
priority,
group_ids: JSON.stringify(groupIds),
proxy_enabled: proxyEnabled,
proxy_address: proxyAddress,
}),
})
const data = await res.json()
if (data.code === 0) {
setMessage({ type: 'success', text: `预设「${profileName}」已保存` })
setProfileName('')
setShowSavePreset(false)
fetchProfiles()
} else {
setMessage({ type: 'error', text: data.message || '保存预设失败' })
}
} catch {
setMessage({ type: 'error', text: '网络错误' })
} finally {
setSavingPreset(false)
}
}
// 加载预设到表单
const handleLoadProfile = (profile: S2AProfile) => {
setS2aApiBase(profile.api_base)
setS2aAdminKey(profile.admin_key)
setConcurrency(profile.concurrency)
setPriority(profile.priority)
try {
const ids = JSON.parse(profile.group_ids || '[]')
setGroupIds(Array.isArray(ids) ? ids : [])
} catch {
setGroupIds([])
}
setProxyEnabled(profile.proxy_enabled)
setProxyAddress(profile.proxy_address || '')
setMessage({ type: 'success', text: `已加载预设「${profile.name}」,请点击保存配置以应用` })
}
// 删除预设
const handleDeleteProfile = async (id: number, name: string) => {
try {
const res = await fetch(`/api/s2a/profiles?id=${id}`, { method: 'DELETE' })
const data = await res.json()
if (data.code === 0) {
setMessage({ type: 'success', text: `预设「${name}」已删除` })
fetchProfiles()
}
} catch {
setMessage({ type: 'error', text: '删除失败' })
}
}
if (loading) { if (loading) {
return ( return (
<div className="flex items-center justify-center h-64"> <div className="flex items-center justify-center h-64">
@@ -130,13 +214,22 @@ export default function S2AConfig() {
</h1> </h1>
<p className="text-sm text-slate-500 dark:text-slate-400"> S2A </p> <p className="text-sm text-slate-500 dark:text-slate-400"> S2A </p>
</div> </div>
<Button <div className="flex gap-2">
onClick={handleSave} <Button
disabled={saving} variant="outline"
icon={saving ? <Loader2 className="h-4 w-4 animate-spin" /> : <Save className="h-4 w-4" />} onClick={() => setShowSavePreset(!showSavePreset)}
> icon={<Bookmark className="h-4 w-4" />}
{saving ? '保存中...' : '保存配置'} >
</Button>
</Button>
<Button
onClick={handleSave}
disabled={saving}
icon={saving ? <Loader2 className="h-4 w-4 animate-spin" /> : <Save className="h-4 w-4" />}
>
{saving ? '保存中...' : '保存配置'}
</Button>
</div>
</div> </div>
{/* Message */} {/* Message */}
@@ -149,207 +242,300 @@ export default function S2AConfig() {
</div> </div>
)} )}
{/* S2A Connection */} {/* Save Preset Inline */}
<Card> {showSavePreset && (
<CardHeader> <Card>
<CardTitle className="flex items-center gap-2"> <CardContent>
<Server className="h-5 w-5 text-blue-500" /> <div className="flex gap-3 items-end">
S2A <div className="flex-1">
</CardTitle>
<div className="flex items-center gap-2">
{isConnected ? (
<span className="flex items-center gap-1 text-sm text-green-600 dark:text-green-400">
<CheckCircle className="h-4 w-4" />
</span>
) : (
<span className="flex items-center gap-1 text-sm text-slate-500 dark:text-slate-400">
<XCircle className="h-4 w-4" />
</span>
)}
</div>
</CardHeader>
<CardContent className="space-y-4">
<div className="grid gap-4 md:grid-cols-2">
<Input
label="S2A API 地址"
placeholder="https://your-s2a-server.com"
value={s2aApiBase}
onChange={(e) => setS2aApiBase(e.target.value)}
hint="S2A 服务的 API 地址"
/>
<Input
label="Admin API Key"
type="password"
placeholder="admin-xxxxxxxxxxxxxxxx"
value={s2aAdminKey}
onChange={(e) => setS2aAdminKey(e.target.value)}
hint="S2A 管理密钥,可在 S2A 后台 Settings 页面获取"
/>
</div>
<div className="flex items-center gap-4">
<Button
variant="outline"
onClick={handleTestConnection}
disabled={testing || !s2aApiBase || !s2aAdminKey}
icon={
testing ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : (
<TestTube className="h-4 w-4" />
)
}
>
{testing ? '测试中...' : '测试连接'}
</Button>
{testResult !== null && (
<span
className={`text-sm ${testResult
? 'text-green-600 dark:text-green-400'
: 'text-red-600 dark:text-red-400'
}`}
>
{testResult ? '连接成功' : '连接失败'}
</span>
)}
</div>
</CardContent>
</Card>
{/* Pooling Settings */}
<Card>
<CardHeader>
<CardTitle></CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<Input
label="默认并发数"
type="number"
min={1}
max={100}
value={concurrency}
onChange={(e) => setConcurrency(Number(e.target.value))}
hint="账号的默认并发请求数"
/>
<Input
label="默认优先级"
type="number"
min={0}
max={100}
value={priority}
onChange={(e) => setPriority(Number(e.target.value))}
hint="账号的默认优先级,数值越大优先级越高"
/>
</div>
{/* Group IDs */}
<div className="space-y-2">
<label className="block text-sm font-medium text-slate-700 dark:text-slate-300">
ID
</label>
<div className="flex flex-wrap gap-2">
{groupIds.map(id => (
<span
key={id}
className="inline-flex items-center gap-1 px-3 py-1 rounded-full text-sm bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400"
>
{id}
<button
onClick={() => handleRemoveGroupId(id)}
className="hover:text-red-500 transition-colors"
>
<X className="h-3 w-3" />
</button>
</span>
))}
{groupIds.length === 0 && (
<span className="text-sm text-slate-400"></span>
)}
</div>
<div className="flex gap-3 mt-2 items-stretch">
<div className="flex-1 max-w-xs">
<Input <Input
placeholder="输入分组 ID" label="预设名称"
type="number" placeholder="例如:生产环境、测试环境"
min={1} value={profileName}
value={newGroupId} onChange={(e) => setProfileName(e.target.value)}
onChange={(e) => setNewGroupId(e.target.value)} onKeyDown={(e) => e.key === 'Enter' && handleSavePreset()}
onKeyDown={(e) => e.key === 'Enter' && handleAddGroupId()}
className="h-10"
/> />
</div> </div>
<Button <Button
variant="outline" onClick={handleSavePreset}
onClick={handleAddGroupId} disabled={savingPreset || !profileName.trim()}
disabled={!newGroupId} icon={savingPreset ? <Loader2 className="h-4 w-4 animate-spin" /> : <Bookmark className="h-4 w-4" />}
icon={<Plus className="h-4 w-4" />} className="h-10"
className="h-10 min-w-[100px] px-4"
> >
{savingPreset ? '保存中...' : '保存'}
</Button>
<Button
variant="outline"
onClick={() => { setShowSavePreset(false); setProfileName('') }}
className="h-10"
>
</Button> </Button>
</div> </div>
<p className="text-xs text-slate-500 dark:text-slate-400"> <p className="text-xs text-slate-500 dark:text-slate-400 mt-2">
便
</p> </p>
</div> </CardContent>
</CardContent> </Card>
</Card> )}
{/* Proxy Settings */} {/* Main Grid Layout */}
<Card> <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
<CardHeader> {/* Left: Main Config (col-span-2) */}
<CardTitle className="flex items-center gap-2"> <div className="lg:col-span-2 space-y-6">
<Globe className="h-5 w-5 text-orange-500" /> {/* S2A Connection */}
<Card>
</CardTitle> <CardHeader>
<button <CardTitle className="flex items-center gap-2">
onClick={() => setProxyEnabled(!proxyEnabled)} <Server className="h-5 w-5 text-blue-500" />
className="flex items-center gap-2 text-sm" S2A
> </CardTitle>
{proxyEnabled ? ( <div className="flex items-center gap-2">
<> {isConnected ? (
<ToggleRight className="h-6 w-6 text-green-500" /> <span className="flex items-center gap-1 text-sm text-green-600 dark:text-green-400">
<span className="text-green-600 dark:text-green-400"></span> <CheckCircle className="h-4 w-4" />
</>
) : ( </span>
<> ) : (
<ToggleLeft className="h-6 w-6 text-slate-400" /> <span className="flex items-center gap-1 text-sm text-slate-500 dark:text-slate-400">
<span className="text-slate-500"></span> <XCircle className="h-4 w-4" />
</>
)} </span>
</button> )}
</CardHeader> </div>
<CardContent> </CardHeader>
<Input <CardContent className="space-y-4">
value={proxyAddress} <div className="grid gap-4 md:grid-cols-2">
onChange={(e) => setProxyAddress(e.target.value)} <Input
placeholder="http://127.0.0.1:7890" label="S2A API 地址"
disabled={!proxyEnabled} placeholder="https://your-s2a-server.com"
className={!proxyEnabled ? 'opacity-50' : ''} value={s2aApiBase}
/> onChange={(e) => setS2aApiBase(e.target.value)}
<p className="text-xs text-slate-500 mt-2"> hint="S2A 服务的 API 地址"
/>
</p> <Input
</CardContent> label="Admin API Key"
</Card> type="password"
placeholder="admin-xxxxxxxxxxxxxxxx"
value={s2aAdminKey}
onChange={(e) => setS2aAdminKey(e.target.value)}
hint="S2A 管理密钥"
/>
</div>
<div className="flex items-center gap-4">
<Button
variant="outline"
onClick={handleTestConnection}
disabled={testing || !s2aApiBase || !s2aAdminKey}
icon={testing ? <Loader2 className="h-4 w-4 animate-spin" /> : <TestTube className="h-4 w-4" />}
>
{testing ? '测试中...' : '测试连接'}
</Button>
{testResult !== null && (
<span className={`text-sm ${testResult ? 'text-green-600 dark:text-green-400' : 'text-red-600 dark:text-red-400'}`}>
{testResult ? '连接成功' : '连接失败'}
</span>
)}
</div>
</CardContent>
</Card>
{/* Info */} {/* Pooling Settings */}
<Card> <Card>
<CardContent> <CardHeader>
<div className="text-sm text-slate-500 dark:text-slate-400"> <CardTitle></CardTitle>
<p className="font-medium mb-2"></p> </CardHeader>
<ul className="list-disc list-inside space-y-1"> <CardContent className="space-y-4">
<li>S2A API S2A URL</li> <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<li>Admin API Key </li> <Input
<li></li> label="默认并发数"
<li> ID </li> type="number"
<li></li> min={1}
</ul> max={100}
</div> value={concurrency}
</CardContent> onChange={(e) => setConcurrency(Number(e.target.value))}
</Card> hint="账号的默认并发请求数"
/>
<Input
label="默认优先级"
type="number"
min={0}
max={100}
value={priority}
onChange={(e) => setPriority(Number(e.target.value))}
hint="数值越大优先级越高"
/>
</div>
{/* Group IDs */}
<div className="space-y-2">
<label className="block text-sm font-medium text-slate-700 dark:text-slate-300">
ID
</label>
<div className="flex flex-wrap gap-2">
{groupIds.map(id => (
<span key={id} className="inline-flex items-center gap-1 px-3 py-1 rounded-full text-sm bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400">
{id}
<button onClick={() => handleRemoveGroupId(id)} className="hover:text-red-500 transition-colors">
<X className="h-3 w-3" />
</button>
</span>
))}
{groupIds.length === 0 && (
<span className="text-sm text-slate-400"></span>
)}
</div>
<div className="flex gap-3 mt-2 items-stretch">
<div className="flex-1 max-w-xs">
<Input
placeholder="输入分组 ID"
type="number"
min={1}
value={newGroupId}
onChange={(e) => setNewGroupId(e.target.value)}
onKeyDown={(e) => e.key === 'Enter' && handleAddGroupId()}
className="h-10"
/>
</div>
<Button
variant="outline"
onClick={handleAddGroupId}
disabled={!newGroupId}
icon={<Plus className="h-4 w-4" />}
className="h-10 min-w-[100px] px-4"
>
</Button>
</div>
</div>
</CardContent>
</Card>
{/* Proxy Settings */}
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Globe className="h-5 w-5 text-orange-500" />
</CardTitle>
<button onClick={() => setProxyEnabled(!proxyEnabled)} className="flex items-center gap-2 text-sm">
{proxyEnabled ? (
<>
<ToggleRight className="h-6 w-6 text-green-500" />
<span className="text-green-600 dark:text-green-400"></span>
</>
) : (
<>
<ToggleLeft className="h-6 w-6 text-slate-400" />
<span className="text-slate-500"></span>
</>
)}
</button>
</CardHeader>
<CardContent>
<Input
value={proxyAddress}
onChange={(e) => setProxyAddress(e.target.value)}
placeholder="http://127.0.0.1:7890"
disabled={!proxyEnabled}
className={!proxyEnabled ? 'opacity-50' : ''}
/>
<p className="text-xs text-slate-500 mt-2">
</p>
</CardContent>
</Card>
</div>
{/* Right: Saved Profiles Sidebar (col-span-1) */}
<div className="lg:col-span-1">
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Bookmark className="h-5 w-5 text-amber-500" />
</CardTitle>
<span className="text-xs text-slate-400">{profiles.length} </span>
</CardHeader>
<CardContent>
{profiles.length === 0 ? (
<div className="text-center py-8 text-slate-400">
<Bookmark className="h-10 w-10 mx-auto mb-2 opacity-30" />
<p className="text-sm"></p>
<p className="text-xs mt-1"></p>
</div>
) : (
<div className="space-y-2">
{profiles.map(profile => (
<ProfileItem
key={profile.id}
profile={profile}
onLoad={handleLoadProfile}
onDelete={handleDeleteProfile}
/>
))}
</div>
)}
</CardContent>
</Card>
</div>
</div>
</div> </div>
) )
} }
// 预设列表项组件
function ProfileItem({ profile, onLoad, onDelete }: {
profile: S2AProfile
onLoad: (p: S2AProfile) => void
onDelete: (id: number, name: string) => void
}) {
const [confirming, setConfirming] = useState(false)
let parsedGroups: number[] = []
try {
parsedGroups = JSON.parse(profile.group_ids || '[]')
} catch { /* ignore */ }
return (
<div className="group border border-slate-200 dark:border-slate-700 rounded-lg p-3 hover:border-blue-300 dark:hover:border-blue-600 transition-colors">
<div className="flex items-center justify-between mb-1">
<span className="font-medium text-sm text-slate-800 dark:text-slate-200 truncate">{profile.name}</span>
<div className="flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
<button
onClick={() => onLoad(profile)}
className="p-1 rounded hover:bg-blue-100 dark:hover:bg-blue-900/30 text-blue-500"
title="加载此预设"
>
<Download className="h-3.5 w-3.5" />
</button>
{confirming ? (
<button
onClick={() => { onDelete(profile.id, profile.name); setConfirming(false) }}
className="p-1 rounded bg-red-100 dark:bg-red-900/30 text-red-500 text-xs px-1.5"
>
</button>
) : (
<button
onClick={() => setConfirming(true)}
onBlur={() => setTimeout(() => setConfirming(false), 200)}
className="p-1 rounded hover:bg-red-100 dark:hover:bg-red-900/30 text-red-400"
title="删除"
>
<Trash2 className="h-3.5 w-3.5" />
</button>
)}
</div>
</div>
<div className="text-xs text-slate-500 dark:text-slate-400 space-y-0.5">
<p className="truncate">{profile.api_base || '未设置 API'}</p>
<div className="flex gap-2 flex-wrap">
<span>: {profile.concurrency}</span>
<span>: {profile.priority}</span>
{parsedGroups.length > 0 && <span>: {parsedGroups.join(',')}</span>}
{profile.proxy_enabled && <span className="text-orange-500"></span>}
</div>
</div>
</div>
)
}

View File

@@ -72,6 +72,20 @@ export interface S2AAccount {
active_sessions?: number active_sessions?: number
} }
// S2A 配置预设
export interface S2AProfile {
id: number
name: string
api_base: string
admin_key: string
concurrency: number
priority: number
group_ids: string // JSON string from backend
proxy_enabled: boolean
proxy_address: string
created_at: string
}
// 分页响应 // 分页响应
export interface PaginatedResponse<T> { export interface PaginatedResponse<T> {
data: T[] data: T[]