订阅式legado

This commit is contained in:
mtvpls
2026-05-19 21:03:11 +08:00
parent da1be9a07c
commit 79fe582f17
8 changed files with 550 additions and 1071 deletions
+189 -1056
View File
@@ -12217,217 +12217,102 @@ const OPDSConfigComponent = ({
const [cacheTTL, setCacheTTL] = useState(10 * 60 * 1000);
const [sources, setSources] = useState<BookSource[]>([]);
const [editingIndex, setEditingIndex] = useState<number | null>(null);
const [legadoImportText, setLegadoImportText] = useState('');
const [legadoRuleDrafts, setLegadoRuleDrafts] = useState<Record<number, string>>({});
const [legadoSubscriptionName, setLegadoSubscriptionName] = useState('');
const [legadoSubscriptionUrl, setLegadoSubscriptionUrl] = useState('');
const [legadoSubscriptions, setLegadoSubscriptions] = useState<NonNullable<AdminConfig['OPDSConfig']>['LegadoSubscriptions']>([]);
useEffect(() => {
if (config?.OPDSConfig) {
setEnabled(config.OPDSConfig.Enabled || false);
setCacheTTL(config.OPDSConfig.CacheTTL || 10 * 60 * 1000);
setSources(
(config.OPDSConfig.Sources || []).map((item, index) => ({
id: item.id || `source_${index + 1}`,
name: item.name || `书源 ${index + 1}`,
type: item.type || 'opds',
url: item.url || '',
enabled: item.enabled !== false,
authMode: item.authMode || 'none',
username: item.username || '',
password: item.password || '',
headerName: item.headerName || '',
headerValue: item.headerValue || '',
searchTemplate: item.searchTemplate || '',
preferFormat: item.preferFormat || ['epub', 'pdf'],
language: item.language || '',
legado: item.legado,
}))
);
setEditingIndex(null);
setLegadoRuleDrafts({});
}
if (!config?.OPDSConfig) return;
setEnabled(config.OPDSConfig.Enabled || false);
setCacheTTL(config.OPDSConfig.CacheTTL || 10 * 60 * 1000);
setSources((config.OPDSConfig.Sources || []).map((item, index) => ({
id: item.id || `source_${index + 1}`,
name: item.name || `书源 ${index + 1}`,
type: 'opds' as const,
url: item.url || '',
enabled: item.enabled !== false,
authMode: item.authMode || 'none',
username: item.username || '',
password: item.password || '',
headerName: item.headerName || '',
headerValue: item.headerValue || '',
searchTemplate: item.searchTemplate || '',
preferFormat: item.preferFormat || ['epub', 'pdf'],
language: item.language || '',
})));
setLegadoSubscriptions(config.OPDSConfig.LegadoSubscriptions || []);
setEditingIndex(null);
}, [config]);
useEffect(() => {
setEditingIndex((prev) => {
if (prev === null) return prev;
return prev >= sources.length ? null : prev;
});
}, [sources.length]);
const updateSource = (index: number, patch: Partial<BookSource>) => {
setSources((prev) =>
prev.map((item, idx) => (idx === index ? { ...item, ...patch } : item))
);
setSources((prev) => prev.map((item, idx) => idx === index ? { ...item, ...patch } : item));
};
const addSource = () => {
setSources((prev) => {
const nextIndex = prev.length;
setEditingIndex(nextIndex);
return [
...prev,
{
id: `source_${prev.length + 1}`,
name: `书源 ${prev.length + 1}`,
type: 'opds',
url: '',
enabled: true,
authMode: 'none',
username: '',
password: '',
headerName: '',
headerValue: '',
searchTemplate: '',
preferFormat: ['epub', 'pdf'],
language: '',
legado: undefined,
},
];
return [...prev, {
id: `source_${nextIndex + 1}`,
name: `书源 ${nextIndex + 1}`,
type: 'opds' as const,
url: '',
enabled: true,
authMode: 'none' as const,
username: '',
password: '',
headerName: '',
headerValue: '',
searchTemplate: '',
preferFormat: ['epub' as const, 'pdf' as const],
language: '',
}];
});
};
const makeLegadoSourceId = (name: string, url: string, index: number) => {
const raw = `${name}|${url}|${index}`;
let hash = 0;
for (let i = 0; i < raw.length; i += 1) {
hash = ((hash << 5) - hash + raw.charCodeAt(i)) | 0;
}
return `legado_${Math.abs(hash).toString(36)}`;
};
const importLegadoSources = () => {
try {
const parsed = JSON.parse(legadoImportText);
const list = Array.isArray(parsed) ? parsed : [parsed];
const imported = list
.filter((item) => item && typeof item === 'object')
.map((rule: any, index) => {
const name = rule.bookSourceName || `Legado 书源 ${index + 1}`;
const url = rule.bookSourceUrl || '';
return {
id: makeLegadoSourceId(name, url, index),
name,
type: 'legado' as const,
url,
enabled: rule.enabled !== false,
authMode: 'none' as const,
username: '',
password: '',
headerName: '',
headerValue: '',
searchTemplate: '',
preferFormat: ['epub' as const],
language: '',
legado: rule,
} satisfies BookSource;
})
.filter((source) => !!source.url);
if (imported.length === 0) {
throw new Error('没有识别到有效 Legado 书源,请确认 JSON 内含 bookSourceUrl');
}
setSources((prev) => {
const existed = new Set(prev.map((item) => `${item.type || 'opds'}|${item.url}|${item.name}`));
const next = imported.filter((item) => !existed.has(`${item.type}|${item.url}|${item.name}`));
return [...prev, ...next];
});
setLegadoImportText('');
showSuccess(`已导入 ${imported.length} 个 Legado 书源`, showAlert);
} catch (error) {
showError(error instanceof Error ? error.message : 'Legado JSON 解析失败', showAlert);
}
};
const removeSource = (index: number) => {
setSources((prev) => prev.filter((_, idx) => idx !== index));
setLegadoRuleDrafts((prev) => {
const next: Record<number, string> = {};
Object.entries(prev).forEach(([key, value]) => {
const numericKey = Number(key);
if (numericKey < index) next[numericKey] = value;
if (numericKey > index) next[numericKey - 1] = value;
});
return next;
});
setEditingIndex((prev) => {
if (prev === null) return prev;
if (prev === index) return null;
return prev > index ? prev - 1 : prev;
});
setEditingIndex((prev) => prev === index ? null : prev !== null && prev > index ? prev - 1 : prev);
};
const normalizeSource = (source: BookSource, index: number) => ({
id: source.id?.trim() || `source_${index + 1}`,
name: source.name?.trim() || `书源 ${index + 1}`,
type: source.type || 'opds',
type: 'opds' as const,
url: source.url?.trim() || '',
enabled: source.enabled !== false,
authMode: source.authMode || 'none',
username: source.authMode === 'none' ? '' : source.username?.trim() || '',
password: source.authMode === 'none' ? '' : source.password || '',
headerName:
source.authMode === 'header' ? source.headerName?.trim() || '' : '',
headerName: source.authMode === 'header' ? source.headerName?.trim() || '' : '',
headerValue: source.authMode === 'header' ? source.headerValue || '' : '',
searchTemplate: source.type === 'legado' ? '' : source.searchTemplate?.trim() || '',
preferFormat: source.preferFormat?.length
? source.preferFormat
: ['epub', 'pdf'],
searchTemplate: source.searchTemplate?.trim() || '',
preferFormat: source.preferFormat?.length ? source.preferFormat : ['epub', 'pdf'],
language: source.language?.trim() || '',
legado: source.type === 'legado' ? source.legado : undefined,
});
const updateLegadoRuleJson = (index: number, value: string) => {
setLegadoRuleDrafts((prev) => ({ ...prev, [index]: value }));
try {
const rule = JSON.parse(value);
updateSource(index, {
legado: rule,
name: rule.bookSourceName || sources[index]?.name,
url: rule.bookSourceUrl || sources[index]?.url,
});
} catch {
// 允许用户继续编辑尚未完成的 JSON,保存前需修正为合法 JSON
}
};
const buildConfig = () => ({
Enabled: enabled,
CacheTTL: Math.max(60_000, cacheTTL || 10 * 60 * 1000),
Sources: sources.map(normalizeSource).filter((source) => !!source.url),
LegadoSubscriptions: legadoSubscriptions || [],
});
const handleSave = async () => {
await withLoading('saveOPDSConfig', async () => {
try {
if (!config) throw new Error('配置未加载');
for (const [index, draft] of Object.entries(legadoRuleDrafts)) {
if (!draft.trim()) continue;
try {
JSON.parse(draft);
} catch {
throw new Error(`${Number(index) + 1} 个 Legado 书源 JSON 格式不正确`);
}
}
const response = await fetch('/api/admin/config', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
...config,
OPDSConfig: buildConfig(),
}),
body: JSON.stringify({ ...config, OPDSConfig: buildConfig() }),
});
if (!response.ok) {
const data = await response.json();
throw new Error(data.error || '保存失败');
}
showSuccess('电子书 OPDS 配置已保存', showAlert);
const data = await response.json().catch(() => ({}));
if (!response.ok) throw new Error(data.error || '保存失败');
showSuccess('电子书源配置已保存', showAlert);
await refreshConfig();
} catch (error) {
showError(
error instanceof Error ? error.message : '保存失败',
showAlert
);
showError(error instanceof Error ? error.message : '保存失败', showAlert);
throw error;
}
});
@@ -12437,38 +12322,69 @@ const OPDSConfigComponent = ({
await withLoading(`testOPDSConfig-${index}`, async () => {
try {
const source = normalizeSource(sources[index], index);
if (!source?.url) {
throw new Error('请先填写书源地址');
}
if (!source.url) throw new Error('请先填写书源地址');
const response = await fetch('/api/admin/opds', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
Enabled: true,
CacheTTL: Math.max(60_000, cacheTTL || 10 * 60 * 1000),
Sources: [source],
}),
body: JSON.stringify({ Enabled: true, CacheTTL: Math.max(60_000, cacheTTL || 10 * 60 * 1000), Sources: [source] }),
});
const data = await response.json();
if (!response.ok || !data.success) {
throw new Error(data.message || data.error || '测试连接失败');
}
if (!response.ok || !data.success) throw new Error(data.message || data.error || '测试连接失败');
const result = Array.isArray(data.results) ? data.results[0] : null;
const summary = result
? `${result.name}: 分类${
result.capability.catalogSupported ? '√' : '×'
} / ${result.capability.searchSupported ? '√' : '×'}${
result.capability.lastError
? ` (${result.capability.lastError})`
: ''
}`
: data.message || '测试成功';
showSuccess(summary, showAlert);
showSuccess(result ? `${result.name}: 分类${result.capability.catalogSupported ? '√' : '×'} / 搜索${result.capability.searchSupported ? '√' : '×'}` : '测试成功', showAlert);
} catch (error) {
showError(
error instanceof Error ? error.message : '测试连接失败',
showAlert
);
showError(error instanceof Error ? error.message : '测试连接失败', showAlert);
throw error;
}
});
};
const importLegadoSubscription = async () => {
await withLoading('importLegadoSubscription', async () => {
try {
const response = await fetch('/api/admin/legado-subscriptions/import', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: legadoSubscriptionName, url: legadoSubscriptionUrl }),
});
const data = await response.json();
if (!response.ok || !data.success) throw new Error(data.error || '导入 Legado 订阅失败');
setLegadoSubscriptionName('');
setLegadoSubscriptionUrl('');
showSuccess(`已导入 ${data.subscription?.sourceCount || 0} 个 Legado 书源`, showAlert);
await refreshConfig();
} catch (error) {
showError(error instanceof Error ? error.message : '导入 Legado 订阅失败', showAlert);
throw error;
}
});
};
const refreshLegadoSubscription = async (id: string) => {
await withLoading(`refreshLegadoSubscription-${id}`, async () => {
try {
const response = await fetch(`/api/admin/legado-subscriptions/${encodeURIComponent(id)}/refresh`, { method: 'POST' });
const data = await response.json();
if (!response.ok || !data.success) throw new Error(data.error || '刷新 Legado 订阅失败');
showSuccess(`已同步 ${data.subscription?.sourceCount || 0} 个 Legado 书源`, showAlert);
await refreshConfig();
} catch (error) {
showError(error instanceof Error ? error.message : '刷新 Legado 订阅失败', showAlert);
throw error;
}
});
};
const deleteLegadoSubscription = async (id: string) => {
await withLoading(`deleteLegadoSubscription-${id}`, async () => {
try {
const response = await fetch(`/api/admin/legado-subscriptions/${encodeURIComponent(id)}`, { method: 'DELETE' });
const data = await response.json();
if (!response.ok || !data.success) throw new Error(data.error || '删除 Legado 订阅失败');
showSuccess('Legado 订阅已删除', showAlert);
await refreshConfig();
} catch (error) {
showError(error instanceof Error ? error.message : '删除 Legado 订阅失败', showAlert);
throw error;
}
});
@@ -12476,893 +12392,110 @@ const OPDSConfigComponent = ({
return (
<div className='space-y-6'>
<div className='bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800 rounded-lg p-4'>
<h3 className='text-sm font-medium text-amber-900 dark:text-amber-100 mb-2'>
/ OPDS / Legado
</h3>
<div className='text-sm text-amber-800 dark:text-amber-200 space-y-1'>
<p> OPDS Legado</p>
<p>
</p>
<p> EPUB 线PDF </p>
<div className='rounded-lg border border-amber-200 bg-amber-50 p-4 dark:border-amber-800 dark:bg-amber-900/20'>
<h3 className='mb-2 text-sm font-medium text-amber-900 dark:text-amber-100'> / OPDS / Legado</h3>
<div className='space-y-1 text-sm text-amber-800 dark:text-amber-200'>
<p> OPDS </p>
<p> Legado URL admin_config</p>
</div>
</div>
<div className='flex items-center justify-between py-3 border-b border-gray-200 dark:border-gray-700'>
<div className='flex items-center justify-between border-b border-gray-200 py-3 dark:border-gray-700'>
<div>
<h3 className='text-sm font-medium text-gray-900 dark:text-white'>
</h3>
<p className='text-xs text-gray-500 dark:text-gray-400 mt-1'>
OPDS
</p>
<h3 className='text-sm font-medium text-gray-900 dark:text-white'></h3>
<p className='mt-1 text-xs text-gray-500 dark:text-gray-400'></p>
</div>
<button
onClick={() => setEnabled(!enabled)}
className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${
enabled ? 'bg-amber-600' : 'bg-gray-200 dark:bg-gray-700'
}`}
>
<span
className={`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${
enabled ? 'translate-x-6' : 'translate-x-1'
}`}
/>
<button onClick={() => setEnabled(!enabled)} className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${enabled ? 'bg-amber-600' : 'bg-gray-200 dark:bg-gray-700'}`}>
<span className={`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${enabled ? 'translate-x-6' : 'translate-x-1'}`} />
</button>
</div>
<div>
<label className='block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2'>
Feed
</label>
<input
type='number'
min='60000'
value={cacheTTL}
onChange={(e) =>
setCacheTTL(parseInt(e.target.value) || 10 * 60 * 1000)
}
className='w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100'
/>
<label className='mb-2 block text-sm font-medium text-gray-700 dark:text-gray-300'>Feed </label>
<input type='number' min='60000' value={cacheTTL} onChange={(e) => setCacheTTL(parseInt(e.target.value) || 10 * 60 * 1000)} className='w-full rounded-lg border border-gray-300 bg-white px-3 py-2 text-gray-900 dark:border-gray-600 dark:bg-gray-800 dark:text-gray-100' />
</div>
<div className='rounded-xl border border-amber-200 bg-amber-50 p-4 dark:border-amber-800 dark:bg-amber-900/20'>
<div className='mb-3 flex items-center justify-between gap-3'>
<div>
<h4 className='text-sm font-medium text-amber-900 dark:text-amber-100'>Legado </h4>
<p className='mt-1 text-xs text-amber-800 dark:text-amber-200'> URL </p>
</div>
<button type='button' onClick={importLegadoSubscription} disabled={!legadoSubscriptionUrl.trim() || isLoading('importLegadoSubscription')} className={buttonStyles.primarySmall}>{isLoading('importLegadoSubscription') ? '导入中...' : '导入订阅'}</button>
</div>
<div className='grid grid-cols-1 gap-3 md:grid-cols-2'>
<input type='text' value={legadoSubscriptionName} onChange={(e) => setLegadoSubscriptionName(e.target.value)} placeholder='订阅名称(可选)' className='rounded-lg border border-amber-200 bg-white px-3 py-2 text-sm text-gray-900 dark:border-amber-800 dark:bg-gray-900 dark:text-gray-100' />
<input type='text' value={legadoSubscriptionUrl} onChange={(e) => setLegadoSubscriptionUrl(e.target.value)} placeholder='https://example.com/bookSource.json' className='rounded-lg border border-amber-200 bg-white px-3 py-2 text-sm text-gray-900 dark:border-amber-800 dark:bg-gray-900 dark:text-gray-100' />
</div>
<div className='mt-4 space-y-2'>
{(legadoSubscriptions || []).length === 0 ? <div className='text-xs text-amber-800 dark:text-amber-200'> Legado </div> : (legadoSubscriptions || []).map((sub) => (
<div key={sub.id} className='rounded-lg border border-amber-200 bg-white p-3 text-sm dark:border-amber-800 dark:bg-gray-900'>
<div className='flex flex-wrap items-start justify-between gap-3'>
<div className='min-w-0 flex-1'>
<div className='font-medium text-gray-900 dark:text-gray-100'>{sub.name}</div>
<div className='mt-1 break-all text-xs text-gray-500 dark:text-gray-400'>{sub.url}</div>
<div className='mt-1 text-xs text-gray-500 dark:text-gray-400'>{sub.sourceCount || 0} · {sub.lastSuccessAt ? new Date(sub.lastSuccessAt).toLocaleString() : '-'}</div>
{sub.lastError ? <div className='mt-1 text-xs text-red-500'>{sub.lastError}</div> : null}
</div>
<div className='flex items-center gap-2'>
<button type='button' onClick={() => setLegadoSubscriptions((prev) => (prev || []).map((item) => item.id === sub.id ? { ...item, enabled: item.enabled === false } : item))} className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${sub.enabled !== false ? 'bg-green-600' : 'bg-gray-200 dark:bg-gray-700'}`}><span className={`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${sub.enabled !== false ? 'translate-x-6' : 'translate-x-1'}`} /></button>
<button type='button' onClick={() => refreshLegadoSubscription(sub.id)} disabled={isLoading(`refreshLegadoSubscription-${sub.id}`)} className={buttonStyles.secondarySmall}>{isLoading(`refreshLegadoSubscription-${sub.id}`) ? '同步中...' : '同步'}</button>
<button type='button' onClick={() => deleteLegadoSubscription(sub.id)} disabled={isLoading(`deleteLegadoSubscription-${sub.id}`)} className={buttonStyles.dangerSmall}></button>
</div>
</div>
</div>
))}
</div>
</div>
<div className='space-y-4'>
<div className='flex items-center justify-between'>
<h3 className='text-sm font-medium text-gray-900 dark:text-white'>
</h3>
<button
type='button'
onClick={addSource}
className={buttonStyles.primary}
>
<Plus size={16} className='inline mr-1' />
</button>
<h3 className='text-sm font-medium text-gray-900 dark:text-white'>OPDS </h3>
<button type='button' onClick={addSource} className={buttonStyles.primary}><Plus size={16} className='mr-1 inline' /> OPDS</button>
</div>
<div className='rounded-xl border border-amber-200 bg-amber-50 p-4 dark:border-amber-800 dark:bg-amber-900/20'>
<div className='mb-2 flex items-center justify-between gap-3'>
<div>
<h4 className='text-sm font-medium text-amber-900 dark:text-amber-100'>
Legado
</h4>
<p className='mt-1 text-xs text-amber-800 dark:text-amber-200'>
/Legado JSON
</p>
</div>
<button
type='button'
onClick={importLegadoSources}
disabled={!legadoImportText.trim()}
className={buttonStyles.primarySmall}
>
Legado
</button>
</div>
<textarea
value={legadoImportText}
onChange={(e) => setLegadoImportText(e.target.value)}
placeholder='[{ "bookSourceName": "...", "bookSourceUrl": "...", "searchUrl": "...", "ruleSearch": { ... } }]'
rows={5}
className='w-full rounded-lg border border-amber-200 bg-white px-3 py-2 font-mono text-xs text-gray-900 dark:border-amber-800 dark:bg-gray-900 dark:text-gray-100'
/>
</div>
{sources.length === 0 && (
<div className='rounded-lg border border-dashed border-gray-300 dark:border-gray-600 p-4 text-sm text-gray-500 dark:text-gray-400'>
OPDS
</div>
)}
{sources.length > 0 && (
<>
<div className='space-y-3 md:hidden'>
{sources.map((source, index) => {
const isEditing = editingIndex === index;
return (
<div
key={`opds-source-${index}`}
className='overflow-hidden rounded-xl border border-gray-200 bg-white dark:border-gray-700 dark:bg-gray-900'
>
<div className='space-y-3 p-4'>
<div className='flex items-start justify-between gap-3'>
<div className='min-w-0 flex-1'>
<div className='text-sm font-medium text-gray-900 dark:text-gray-100'>
{source.name || `书源 ${index + 1}`}
</div>
<div className='mt-1 text-xs text-gray-500 dark:text-gray-400'>
{source.id || '未设置 ID'}
</div>
</div>
<button
type='button'
onClick={() =>
updateSource(index, {
enabled: source.enabled === false,
})
}
className={`relative inline-flex h-6 w-11 shrink-0 items-center rounded-full transition-colors ${
source.enabled !== false
? 'bg-green-600'
: 'bg-gray-200 dark:bg-gray-700'
}`}
>
<span
className={`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${
source.enabled !== false
? 'translate-x-6'
: 'translate-x-1'
}`}
/>
</button>
</div>
<div className='space-y-2 text-xs text-gray-600 dark:text-gray-300'>
<div className='flex items-start justify-between gap-3'>
<span className='shrink-0 text-gray-500 dark:text-gray-400'>
</span>
<span className='min-w-0 text-right'>
{source.type === 'legado' ? 'Legado' : 'OPDS'}
</span>
</div>
<div className='flex items-start justify-between gap-3'>
<span className='shrink-0 text-gray-500 dark:text-gray-400'>
</span>
<span className='min-w-0 text-right break-all'>
{source.url || '-'}
</span>
</div>
<div className='flex items-center justify-between gap-3'>
<span className='text-gray-500 dark:text-gray-400'>
</span>
<span>
{source.authMode === 'none'
? '无认证'
: source.authMode === 'basic'
? 'Basic Auth'
: '自定义 Header'}
</span>
</div>
<div className='flex items-center justify-between gap-3'>
<span className='text-gray-500 dark:text-gray-400'>
</span>
<span>
{source.type === 'legado'
? source.legado?.searchUrl
? '已配置'
: '未配置'
: source.searchTemplate?.trim()
? '已配置'
: '未配置'}
</span>
</div>
<div className='flex items-center justify-between gap-3'>
<span className='text-gray-500 dark:text-gray-400'>
</span>
<span>{source.preferFormat?.join(', ') || '-'}</span>
</div>
</div>
<div className='flex flex-wrap items-center justify-end gap-2'>
<button
type='button'
onClick={() => handleTest(index)}
disabled={isLoading(`testOPDSConfig-${index}`)}
className={buttonStyles.primarySmall}
>
{isLoading(`testOPDSConfig-${index}`)
? '测试中...'
: '测试'}
</button>
<button
type='button'
onClick={() =>
setEditingIndex(isEditing ? null : index)
}
className={buttonStyles.secondarySmall}
>
{isEditing ? (
<>
<ChevronUp size={14} className='inline mr-1' />
</>
) : (
<>
<Settings size={14} className='inline mr-1' />
</>
)}
</button>
<button
type='button'
onClick={() => removeSource(index)}
className={buttonStyles.dangerSmall}
>
<Trash2 size={14} className='inline mr-1' />
</button>
</div>
</div>
{isEditing && (
<div className='space-y-4 border-t border-gray-200 bg-gray-50 p-4 dark:border-gray-700 dark:bg-gray-800/40'>
<div className='text-sm font-medium text-gray-900 dark:text-white'>
#{index + 1}
</div>
<div className='grid grid-cols-1 gap-4'>
<div>
<label className='mb-2 block text-sm font-medium text-gray-700 dark:text-gray-300'>
</label>
<select
value={source.type || 'opds'}
onChange={(e) => {
const nextType = e.target.value as BookSource['type'];
updateSource(index, {
type: nextType,
legado: nextType === 'legado'
? source.legado || { bookSourceName: source.name, bookSourceUrl: source.url }
: undefined,
});
}}
className='w-full rounded-lg border border-gray-300 bg-white px-3 py-2 text-gray-900 dark:border-gray-600 dark:bg-gray-800 dark:text-gray-100'
>
<option value='opds'>OPDS</option>
<option value='legado'>Legado</option>
</select>
</div>
<div>
<label className='mb-2 block text-sm font-medium text-gray-700 dark:text-gray-300'>
ID
</label>
<input
type='text'
value={source.id}
onChange={(e) =>
updateSource(index, { id: e.target.value })
}
className='w-full rounded-lg border border-gray-300 bg-white px-3 py-2 text-gray-900 dark:border-gray-600 dark:bg-gray-800 dark:text-gray-100'
/>
</div>
<div>
<label className='mb-2 block text-sm font-medium text-gray-700 dark:text-gray-300'>
</label>
<input
type='text'
value={source.name}
onChange={(e) =>
updateSource(index, { name: e.target.value })
}
className='w-full rounded-lg border border-gray-300 bg-white px-3 py-2 text-gray-900 dark:border-gray-600 dark:bg-gray-800 dark:text-gray-100'
/>
</div>
</div>
<div>
<label className='mb-2 block text-sm font-medium text-gray-700 dark:text-gray-300'>
</label>
<input
type='text'
value={source.url}
onChange={(e) => {
const url = e.target.value;
updateSource(index, {
url,
legado: source.type === 'legado' ? { ...(source.legado || {}), bookSourceUrl: url } : source.legado,
});
}}
placeholder={source.type === 'legado' ? 'https://example.com' : 'https://example.com/opds'}
className='w-full rounded-lg border border-gray-300 bg-white px-3 py-2 text-gray-900 dark:border-gray-600 dark:bg-gray-800 dark:text-gray-100'
/>
</div>
{source.type === 'legado' ? (
<div>
<label className='mb-2 block text-sm font-medium text-gray-700 dark:text-gray-300'>
Legado JSON
</label>
<textarea
value={legadoRuleDrafts[index] ?? JSON.stringify(source.legado || {}, null, 2)}
onChange={(e) => updateLegadoRuleJson(index, e.target.value)}
rows={10}
className='w-full rounded-lg border border-gray-300 bg-white px-3 py-2 font-mono text-xs text-gray-900 dark:border-gray-600 dark:bg-gray-800 dark:text-gray-100'
/>
<p className='mt-1 text-xs text-gray-500 dark:text-gray-400'>
JSON/
</p>
</div>
) : (
<>
<div className='grid grid-cols-1 gap-4'>
<div>
<label className='mb-2 block text-sm font-medium text-gray-700 dark:text-gray-300'>
</label>
<select
value={source.authMode || 'none'}
onChange={(e) =>
updateSource(index, {
authMode: e.target
.value as BookSource['authMode'],
})
}
className='w-full rounded-lg border border-gray-300 bg-white px-3 py-2 text-gray-900 dark:border-gray-600 dark:bg-gray-800 dark:text-gray-100'
>
<option value='none'></option>
<option value='basic'>Basic Auth</option>
<option value='header'> Header</option>
</select>
</div>
<div>
<label className='mb-2 block text-sm font-medium text-gray-700 dark:text-gray-300'>
</label>
<input
type='text'
value={source.language || ''}
onChange={(e) =>
updateSource(index, {
language: e.target.value,
})
}
placeholder='zh / en'
className='w-full rounded-lg border border-gray-300 bg-white px-3 py-2 text-gray-900 dark:border-gray-600 dark:bg-gray-800 dark:text-gray-100'
/>
</div>
<div>
<label className='mb-2 block text-sm font-medium text-gray-700 dark:text-gray-300'>
</label>
<input
type='text'
value={source.searchTemplate || ''}
onChange={(e) =>
updateSource(index, {
searchTemplate: e.target.value,
})
}
placeholder='https://...{searchTerms}'
className='w-full rounded-lg border border-gray-300 bg-white px-3 py-2 text-gray-900 dark:border-gray-600 dark:bg-gray-800 dark:text-gray-100'
/>
</div>
</div>
{source.authMode === 'basic' && (
<div className='grid grid-cols-1 gap-4'>
<div>
<label className='mb-2 block text-sm font-medium text-gray-700 dark:text-gray-300'>
</label>
<input
type='text'
value={source.username || ''}
onChange={(e) =>
updateSource(index, {
username: e.target.value,
})
}
className='w-full rounded-lg border border-gray-300 bg-white px-3 py-2 text-gray-900 dark:border-gray-600 dark:bg-gray-800 dark:text-gray-100'
/>
</div>
<div>
<label className='mb-2 block text-sm font-medium text-gray-700 dark:text-gray-300'>
</label>
<input
type='password'
value={source.password || ''}
onChange={(e) =>
updateSource(index, {
password: e.target.value,
})
}
className='w-full rounded-lg border border-gray-300 bg-white px-3 py-2 text-gray-900 dark:border-gray-600 dark:bg-gray-800 dark:text-gray-100'
/>
</div>
</div>
)}
{source.authMode === 'header' && (
<div className='grid grid-cols-1 gap-4'>
<div>
<label className='mb-2 block text-sm font-medium text-gray-700 dark:text-gray-300'>
Header
</label>
<input
type='text'
value={source.headerName || ''}
onChange={(e) =>
updateSource(index, {
headerName: e.target.value,
})
}
className='w-full rounded-lg border border-gray-300 bg-white px-3 py-2 text-gray-900 dark:border-gray-600 dark:bg-gray-800 dark:text-gray-100'
/>
</div>
<div>
<label className='mb-2 block text-sm font-medium text-gray-700 dark:text-gray-300'>
Header
</label>
<input
type='password'
value={source.headerValue || ''}
onChange={(e) =>
updateSource(index, {
headerValue: e.target.value,
})
}
className='w-full rounded-lg border border-gray-300 bg-white px-3 py-2 text-gray-900 dark:border-gray-600 dark:bg-gray-800 dark:text-gray-100'
/>
</div>
</div>
)}
</>
)}
</div>
)}
{sources.length === 0 ? <div className='rounded-lg border border-dashed border-gray-300 p-4 text-sm text-gray-500 dark:border-gray-600 dark:text-gray-400'> OPDS </div> : null}
<div className='space-y-3'>
{sources.map((source, index) => {
const isEditing = editingIndex === index;
return (
<div key={`opds-source-${index}`} className='rounded-xl border border-gray-200 bg-white p-4 dark:border-gray-700 dark:bg-gray-900'>
<div className='flex flex-wrap items-start justify-between gap-3'>
<div className='min-w-0 flex-1'>
<div className='font-medium text-gray-900 dark:text-gray-100'>{source.name || `书源 ${index + 1}`}</div>
<div className='mt-1 break-all text-xs text-gray-500 dark:text-gray-400'>{source.url || '-'}</div>
</div>
);
})}
</div>
<div className='hidden overflow-hidden rounded-xl border border-gray-200 dark:border-gray-700 md:block'>
<div className='overflow-x-auto'>
<table className='min-w-full divide-y divide-gray-200 dark:divide-gray-700'>
<thead className='bg-gray-50 dark:bg-gray-800/70'>
<tr>
<th className='px-4 py-3 text-left text-xs font-medium uppercase tracking-wide text-gray-500 dark:text-gray-400'>
</th>
<th className='px-4 py-3 text-left text-xs font-medium uppercase tracking-wide text-gray-500 dark:text-gray-400'>
</th>
<th className='px-4 py-3 text-left text-xs font-medium uppercase tracking-wide text-gray-500 dark:text-gray-400'>
ID
</th>
<th className='px-4 py-3 text-left text-xs font-medium uppercase tracking-wide text-gray-500 dark:text-gray-400'>
</th>
<th className='px-4 py-3 text-left text-xs font-medium uppercase tracking-wide text-gray-500 dark:text-gray-400'>
</th>
<th className='px-4 py-3 text-left text-xs font-medium uppercase tracking-wide text-gray-500 dark:text-gray-400'>
</th>
<th className='px-4 py-3 text-left text-xs font-medium uppercase tracking-wide text-gray-500 dark:text-gray-400'>
</th>
<th className='px-4 py-3 text-right text-xs font-medium uppercase tracking-wide text-gray-500 dark:text-gray-400'>
</th>
</tr>
</thead>
<tbody className='divide-y divide-gray-200 bg-white dark:divide-gray-700 dark:bg-gray-900'>
{sources.map((source, index) => {
const isEditing = editingIndex === index;
return (
<Fragment key={`opds-source-${index}`}>
<tr className='align-top'>
<td className='px-4 py-3'>
<button
type='button'
onClick={() =>
updateSource(index, {
enabled: source.enabled === false,
})
}
className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${
source.enabled !== false
? 'bg-green-600'
: 'bg-gray-200 dark:bg-gray-700'
}`}
>
<span
className={`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${
source.enabled !== false
? 'translate-x-6'
: 'translate-x-1'
}`}
/>
</button>
</td>
<td className='px-4 py-3 text-sm text-gray-900 dark:text-gray-100'>
<div className='font-medium'>
{source.name || `书源 ${index + 1}`}
</div>
<div className='mt-1 text-xs text-gray-500 dark:text-gray-400'>
{source.type === 'legado' ? 'Legado' : 'OPDS'} · {source.language || '未设置语言'}
</div>
</td>
<td className='px-4 py-3 text-sm text-gray-600 dark:text-gray-300'>
{source.id || '-'}
</td>
<td className='px-4 py-3 text-sm text-gray-600 dark:text-gray-300'>
<div
className='max-w-[320px] truncate'
title={source.url || ''}
>
{source.url || '-'}
</div>
</td>
<td className='px-4 py-3 text-sm text-gray-600 dark:text-gray-300'>
{source.authMode === 'none'
? '无认证'
: source.authMode === 'basic'
? 'Basic Auth'
: '自定义 Header'}
</td>
<td className='px-4 py-3 text-sm text-gray-600 dark:text-gray-300'>
{source.type === 'legado'
? source.legado?.searchUrl
? '已配置'
: '未配置'
: source.searchTemplate?.trim()
? '已配置'
: '未配置'}
</td>
<td className='px-4 py-3 text-sm text-gray-600 dark:text-gray-300'>
{source.preferFormat?.join(', ') || '-'}
</td>
<td className='px-4 py-3'>
<div className='flex flex-wrap items-center justify-end gap-2'>
<button
type='button'
onClick={() => handleTest(index)}
disabled={isLoading(
`testOPDSConfig-${index}`
)}
className={buttonStyles.primarySmall}
>
{isLoading(`testOPDSConfig-${index}`)
? '测试中...'
: '测试'}
</button>
<button
type='button'
onClick={() =>
setEditingIndex(isEditing ? null : index)
}
className={buttonStyles.secondarySmall}
>
{isEditing ? (
<>
<ChevronUp
size={14}
className='inline mr-1'
/>
</>
) : (
<>
<Settings
size={14}
className='inline mr-1'
/>
</>
)}
</button>
<button
type='button'
onClick={() => removeSource(index)}
className={buttonStyles.dangerSmall}
>
<Trash2 size={14} className='inline mr-1' />
</button>
</div>
</td>
</tr>
{isEditing && (
<tr>
<td
colSpan={8}
className='bg-gray-50 px-4 py-4 dark:bg-gray-800/40'
>
<div className='space-y-4'>
<div className='flex items-center justify-between gap-3'>
<div>
<div className='text-sm font-medium text-gray-900 dark:text-white'>
#{index + 1}
</div>
<div className='mt-1 text-xs text-gray-500 dark:text-gray-400'>
</div>
</div>
<button
type='button'
onClick={() => setEditingIndex(null)}
className={buttonStyles.secondarySmall}
>
<ChevronUp
size={14}
className='inline mr-1'
/>
</button>
</div>
<div className='grid grid-cols-1 gap-4 md:grid-cols-2'>
<div>
<label className='mb-2 block text-sm font-medium text-gray-700 dark:text-gray-300'>
</label>
<select
value={source.type || 'opds'}
onChange={(e) => {
const nextType = e.target.value as BookSource['type'];
updateSource(index, {
type: nextType,
legado: nextType === 'legado'
? source.legado || { bookSourceName: source.name, bookSourceUrl: source.url }
: undefined,
});
}}
className='w-full rounded-lg border border-gray-300 bg-white px-3 py-2 text-gray-900 dark:border-gray-600 dark:bg-gray-800 dark:text-gray-100'
>
<option value='opds'>OPDS</option>
<option value='legado'>Legado</option>
</select>
</div>
<div>
<label className='mb-2 block text-sm font-medium text-gray-700 dark:text-gray-300'>
ID
</label>
<input
type='text'
value={source.id}
onChange={(e) =>
updateSource(index, {
id: e.target.value,
})
}
className='w-full rounded-lg border border-gray-300 bg-white px-3 py-2 text-gray-900 dark:border-gray-600 dark:bg-gray-800 dark:text-gray-100'
/>
</div>
<div>
<label className='mb-2 block text-sm font-medium text-gray-700 dark:text-gray-300'>
</label>
<input
type='text'
value={source.name}
onChange={(e) =>
updateSource(index, {
name: e.target.value,
})
}
className='w-full rounded-lg border border-gray-300 bg-white px-3 py-2 text-gray-900 dark:border-gray-600 dark:bg-gray-800 dark:text-gray-100'
/>
</div>
</div>
<div>
<label className='mb-2 block text-sm font-medium text-gray-700 dark:text-gray-300'>
</label>
<input
type='text'
value={source.url}
onChange={(e) => {
const url = e.target.value;
updateSource(index, {
url,
legado: source.type === 'legado' ? { ...(source.legado || {}), bookSourceUrl: url } : source.legado,
});
}}
placeholder={source.type === 'legado' ? 'https://example.com' : 'https://example.com/opds'}
className='w-full rounded-lg border border-gray-300 bg-white px-3 py-2 text-gray-900 dark:border-gray-600 dark:bg-gray-800 dark:text-gray-100'
/>
</div>
{source.type === 'legado' ? (
<div>
<label className='mb-2 block text-sm font-medium text-gray-700 dark:text-gray-300'>
Legado JSON
</label>
<textarea
value={legadoRuleDrafts[index] ?? JSON.stringify(source.legado || {}, null, 2)}
onChange={(e) => updateLegadoRuleJson(index, e.target.value)}
rows={12}
className='w-full rounded-lg border border-gray-300 bg-white px-3 py-2 font-mono text-xs text-gray-900 dark:border-gray-600 dark:bg-gray-800 dark:text-gray-100'
/>
</div>
) : (
<>
<div className='grid grid-cols-1 gap-4 md:grid-cols-3'>
<div>
<label className='mb-2 block text-sm font-medium text-gray-700 dark:text-gray-300'>
</label>
<select
value={source.authMode || 'none'}
onChange={(e) =>
updateSource(index, {
authMode: e.target
.value as BookSource['authMode'],
})
}
className='w-full rounded-lg border border-gray-300 bg-white px-3 py-2 text-gray-900 dark:border-gray-600 dark:bg-gray-800 dark:text-gray-100'
>
<option value='none'></option>
<option value='basic'>
Basic Auth
</option>
<option value='header'>
Header
</option>
</select>
</div>
<div>
<label className='mb-2 block text-sm font-medium text-gray-700 dark:text-gray-300'>
</label>
<input
type='text'
value={source.language || ''}
onChange={(e) =>
updateSource(index, {
language: e.target.value,
})
}
placeholder='zh / en'
className='w-full rounded-lg border border-gray-300 bg-white px-3 py-2 text-gray-900 dark:border-gray-600 dark:bg-gray-800 dark:text-gray-100'
/>
</div>
<div>
<label className='mb-2 block text-sm font-medium text-gray-700 dark:text-gray-300'>
</label>
<input
type='text'
value={source.searchTemplate || ''}
onChange={(e) =>
updateSource(index, {
searchTemplate: e.target.value,
})
}
placeholder='https://...{searchTerms}'
className='w-full rounded-lg border border-gray-300 bg-white px-3 py-2 text-gray-900 dark:border-gray-600 dark:bg-gray-800 dark:text-gray-100'
/>
</div>
</div>
{source.authMode === 'basic' && (
<div className='grid grid-cols-1 gap-4 md:grid-cols-2'>
<div>
<label className='mb-2 block text-sm font-medium text-gray-700 dark:text-gray-300'>
</label>
<input
type='text'
value={source.username || ''}
onChange={(e) =>
updateSource(index, {
username: e.target.value,
})
}
className='w-full rounded-lg border border-gray-300 bg-white px-3 py-2 text-gray-900 dark:border-gray-600 dark:bg-gray-800 dark:text-gray-100'
/>
</div>
<div>
<label className='mb-2 block text-sm font-medium text-gray-700 dark:text-gray-300'>
</label>
<input
type='password'
value={source.password || ''}
onChange={(e) =>
updateSource(index, {
password: e.target.value,
})
}
className='w-full rounded-lg border border-gray-300 bg-white px-3 py-2 text-gray-900 dark:border-gray-600 dark:bg-gray-800 dark:text-gray-100'
/>
</div>
</div>
)}
{source.authMode === 'header' && (
<div className='grid grid-cols-1 gap-4 md:grid-cols-2'>
<div>
<label className='mb-2 block text-sm font-medium text-gray-700 dark:text-gray-300'>
Header
</label>
<input
type='text'
value={source.headerName || ''}
onChange={(e) =>
updateSource(index, {
headerName: e.target.value,
})
}
className='w-full rounded-lg border border-gray-300 bg-white px-3 py-2 text-gray-900 dark:border-gray-600 dark:bg-gray-800 dark:text-gray-100'
/>
</div>
<div>
<label className='mb-2 block text-sm font-medium text-gray-700 dark:text-gray-300'>
Header
</label>
<input
type='password'
value={source.headerValue || ''}
onChange={(e) =>
updateSource(index, {
headerValue: e.target.value,
})
}
className='w-full rounded-lg border border-gray-300 bg-white px-3 py-2 text-gray-900 dark:border-gray-600 dark:bg-gray-800 dark:text-gray-100'
/>
</div>
</div>
)}
</>
)}
</div>
</td>
</tr>
)}
</Fragment>
);
})}
</tbody>
</table>
<div className='flex items-center gap-2'>
<button type='button' onClick={() => updateSource(index, { enabled: source.enabled === false })} className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${source.enabled !== false ? 'bg-green-600' : 'bg-gray-200 dark:bg-gray-700'}`}><span className={`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${source.enabled !== false ? 'translate-x-6' : 'translate-x-1'}`} /></button>
<button type='button' onClick={() => handleTest(index)} disabled={isLoading(`testOPDSConfig-${index}`)} className={buttonStyles.primarySmall}>{isLoading(`testOPDSConfig-${index}`) ? '测试中...' : '测试'}</button>
<button type='button' onClick={() => setEditingIndex(isEditing ? null : index)} className={buttonStyles.secondarySmall}>{isEditing ? '收起' : '编辑'}</button>
<button type='button' onClick={() => removeSource(index)} className={buttonStyles.dangerSmall}></button>
</div>
</div>
{isEditing ? (
<div className='mt-4 grid grid-cols-1 gap-4 border-t border-gray-200 pt-4 dark:border-gray-700 md:grid-cols-2'>
<input type='text' value={source.id} onChange={(e) => updateSource(index, { id: e.target.value })} placeholder='书源 ID' className='rounded-lg border border-gray-300 bg-white px-3 py-2 text-gray-900 dark:border-gray-600 dark:bg-gray-800 dark:text-gray-100' />
<input type='text' value={source.name} onChange={(e) => updateSource(index, { name: e.target.value })} placeholder='书源名称' className='rounded-lg border border-gray-300 bg-white px-3 py-2 text-gray-900 dark:border-gray-600 dark:bg-gray-800 dark:text-gray-100' />
<input type='text' value={source.url} onChange={(e) => updateSource(index, { url: e.target.value })} placeholder='https://example.com/opds' className='rounded-lg border border-gray-300 bg-white px-3 py-2 text-gray-900 dark:border-gray-600 dark:bg-gray-800 dark:text-gray-100 md:col-span-2' />
<select value={source.authMode || 'none'} onChange={(e) => updateSource(index, { authMode: e.target.value as BookSource['authMode'] })} className='rounded-lg border border-gray-300 bg-white px-3 py-2 text-gray-900 dark:border-gray-600 dark:bg-gray-800 dark:text-gray-100'>
<option value='none'></option><option value='basic'>Basic Auth</option><option value='header'> Header</option>
</select>
<input type='text' value={source.language || ''} onChange={(e) => updateSource(index, { language: e.target.value })} placeholder='语言 zh / en' className='rounded-lg border border-gray-300 bg-white px-3 py-2 text-gray-900 dark:border-gray-600 dark:bg-gray-800 dark:text-gray-100' />
<input type='text' value={source.searchTemplate || ''} onChange={(e) => updateSource(index, { searchTemplate: e.target.value })} placeholder='搜索模板 https://...{searchTerms}' className='rounded-lg border border-gray-300 bg-white px-3 py-2 text-gray-900 dark:border-gray-600 dark:bg-gray-800 dark:text-gray-100 md:col-span-2' />
{source.authMode === 'basic' ? <><input type='text' value={source.username || ''} onChange={(e) => updateSource(index, { username: e.target.value })} placeholder='用户名' className='rounded-lg border border-gray-300 bg-white px-3 py-2 text-gray-900 dark:border-gray-600 dark:bg-gray-800 dark:text-gray-100' /><input type='password' value={source.password || ''} onChange={(e) => updateSource(index, { password: e.target.value })} placeholder='密码' className='rounded-lg border border-gray-300 bg-white px-3 py-2 text-gray-900 dark:border-gray-600 dark:bg-gray-800 dark:text-gray-100' /></> : null}
{source.authMode === 'header' ? <><input type='text' value={source.headerName || ''} onChange={(e) => updateSource(index, { headerName: e.target.value })} placeholder='Header 名称' className='rounded-lg border border-gray-300 bg-white px-3 py-2 text-gray-900 dark:border-gray-600 dark:bg-gray-800 dark:text-gray-100' /><input type='password' value={source.headerValue || ''} onChange={(e) => updateSource(index, { headerValue: e.target.value })} placeholder='Header 值' className='rounded-lg border border-gray-300 bg-white px-3 py-2 text-gray-900 dark:border-gray-600 dark:bg-gray-800 dark:text-gray-100' /></> : null}
</div>
) : null}
</div>
</div>
</>
)}
);
})}
</div>
</div>
<div className='flex gap-3'>
<button
onClick={handleSave}
disabled={isLoading('saveOPDSConfig')}
className={buttonStyles.success}
>
{isLoading('saveOPDSConfig') ? '保存中...' : '保存电子书源配置'}
</button>
<button onClick={handleSave} disabled={isLoading('saveOPDSConfig')} className={buttonStyles.success}>{isLoading('saveOPDSConfig') ? '保存中...' : '保存电子书源配置'}</button>
</div>
<AlertModal
isOpen={alertModal.isOpen}
onClose={hideAlert}
type={alertModal.type}
title={alertModal.title}
message={alertModal.message}
timer={alertModal.timer}
showConfirm={alertModal.showConfirm}
/>
<AlertModal isOpen={alertModal.isOpen} onClose={hideAlert} type={alertModal.type} title={alertModal.title} message={alertModal.message} timer={alertModal.timer} showConfirm={alertModal.showConfirm} />
</div>
);
};