-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathAdmin.tsx
More file actions
916 lines (862 loc) · 55.4 KB
/
Copy pathAdmin.tsx
File metadata and controls
916 lines (862 loc) · 55.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
// @ts-nocheck
import React, { useState, useEffect, useRef } from 'react';
import { Routes, Route, Link, useLocation } from 'react-router-dom';
import { getApiClient, User, EbookSource, Book } from '@bookdock/api-client';
import { getCoverImageUrl } from '../utils/network';
import { Button, Card, CardHeader, CardTitle, CardContent, Input } from '@bookdock/ui';
function BookCover({ book, className = "" }: { book: Book; className?: string }) {
const [coverError, setCoverError] = useState(false);
const coverSrc = getCoverImageUrl(book.coverUrl);
return (
<div className={`bg-gray-100 dark:bg-gray-700 rounded overflow-hidden flex-shrink-0 ${className}`}>
{coverSrc && !coverError ? (
<img
src={coverSrc}
alt={book.title}
className="w-full h-full object-cover"
onError={() => setCoverError(true)}
/>
) : (
<div className="w-full h-full flex items-center justify-center bg-gradient-to-br from-blue-400 to-purple-500">
<span className="text-white font-bold">{book.title.charAt(0)}</span>
</div>
)}
</div>
);
}
import {
BookOpen,
FileText,
Smartphone,
PenLine,
Plus,
Cloud,
Folder,
Globe,
AlertTriangle,
Trash2,
Pencil,
Settings,
ArrowLeft,
Upload,
Inbox,
Search,
Users,
Save,
RefreshCw,
Link as LinkIcon,
Check,
X,
} from 'lucide-react';
import AdminUsers from './AdminUsers';
// ==================== File Upload Section ====================
function FileUpload() {
const [isUploading, setIsUploading] = useState(false);
const [uploadProgress, setUploadProgress] = useState(0);
const [uploadError, setUploadError] = useState<string | null>(null);
const [uploadSuccess, setUploadSuccess] = useState<string | null>(null);
const [dragOver, setDragOver] = useState(false);
const [recentUploads, setRecentUploads] = useState<Book[]>([]);
const fileInputRef = useRef<HTMLInputElement>(null);
const [meta, setMeta] = useState({ title: '', author: '', description: '', language: 'zh' });
const [selectedFile, setSelectedFile] = useState<File | null>(null);
const [showMetaForm, setShowMetaForm] = useState(false);
const formatFileSize = (bytes: number): string => {
if (bytes === 0) return '0 B';
const k = 1024;
const sizes = ['B', 'KB', 'MB', 'GB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i];
};
const handleFileSelect = (files: FileList | null) => {
if (!files || files.length === 0) return;
const file = files[0];
const ext = file.name.split('.').pop()?.toLowerCase() || '';
const supported = ['epub', 'pdf', 'txt', 'mobi'];
if (!supported.includes(ext)) {
setUploadError(`不支持的格式: .${ext}。支持: ${supported.join(', ')}`);
return;
}
setSelectedFile(file);
setUploadError(null);
setUploadSuccess(null);
if (!meta.title) {
setMeta((prev) => ({ ...prev, title: file.name.replace(/\.[^/.]+$/, '') }));
}
setShowMetaForm(true);
};
const handleDrop = (e: React.DragEvent) => {
e.preventDefault();
setDragOver(false);
handleFileSelect(e.dataTransfer.files);
};
const handleUpload = async () => {
if (!selectedFile) return;
setIsUploading(true);
setUploadProgress(0);
setUploadError(null);
setUploadSuccess(null);
try {
const formData = new FormData();
formData.append('file', selectedFile);
formData.append('title', meta.title || selectedFile.name.replace(/\.[^/.]+$/, ''));
formData.append('author', meta.author || '未知作者');
formData.append('description', meta.description);
formData.append('language', meta.language);
await new Promise<void>((resolve) => {
const xhr = new XMLHttpRequest();
const apiBase = (window as unknown as { _bookdock_api_base?: string })._bookdock_api_base || '/api';
xhr.open('POST', `${apiBase}/books/upload`);
xhr.upload.onprogress = (e) => {
if (e.lengthComputable) setUploadProgress(Math.round((e.loaded / e.total) * 100));
};
xhr.onload = () => {
if (xhr.status >= 200 && xhr.status < 300) {
try {
const resp = JSON.parse(xhr.responseText);
if (resp.success && resp.data) {
setRecentUploads((prev) => [resp.data, ...prev.slice(0, 4)]);
setUploadSuccess(`《${resp.data.title}》上传成功!`);
setSelectedFile(null);
setShowMetaForm(false);
setMeta({ title: '', author: '', description: '', language: 'zh' });
if (fileInputRef.current) fileInputRef.current.value = '';
} else {
setUploadError(resp.error || '上传失败');
}
} catch {
setUploadError('解析响应失败');
}
} else {
try {
const resp = JSON.parse(xhr.responseText);
setUploadError(resp.error || `上传失败 (${xhr.status})`);
} catch {
setUploadError(`上传失败 (${xhr.status})`);
}
}
resolve();
};
xhr.onerror = () => { setUploadError('网络错误'); resolve(); };
xhr.send(formData);
});
} catch (err) {
setUploadError((err as Error).message);
} finally {
setIsUploading(false);
setUploadProgress(0);
}
};
const ext = selectedFile ? selectedFile.name.split('.').pop()?.toLowerCase() : '';
const extIcon =
ext === 'epub' ? <BookOpen className="w-6 h-6" /> :
ext === 'pdf' ? <FileText className="w-6 h-6" /> :
ext === 'mobi' ? <Smartphone className="w-6 h-6" /> :
<PenLine className="w-6 h-6" />;
return (
<div className="space-y-6">
<div className="flex items-center justify-between">
<h2 className="text-xl font-semibold text-gray-900 dark:text-white flex items-center gap-2"><Upload className="w-5 h-5" /> 上传书籍</h2>
<span className="text-xs text-gray-400">支持 EPUB, PDF, TXT, MOBI</span>
</div>
{/* Drop zone */}
<div
onDragOver={(e) => { e.preventDefault(); setDragOver(true); }}
onDragLeave={() => setDragOver(false)}
onDrop={handleDrop}
onClick={() => fileInputRef.current?.click()}
className={`border-2 border-dashed rounded-2xl p-12 text-center cursor-pointer transition-all ${
dragOver
? 'border-blue-400 bg-blue-50 dark:bg-blue-900/20'
: 'border-gray-300 dark:border-gray-600 hover:border-blue-400 hover:bg-gray-50 dark:hover:bg-gray-800/50'
}`}
>
<input ref={fileInputRef} type="file" accept=".epub,.pdf,.txt,.mobi" className="hidden" onChange={(e) => handleFileSelect(e.target.files)} />
<div className="text-5xl mb-3 flex justify-center">{dragOver ? <Inbox className="w-12 h-12 text-blue-500" /> : <Folder className="w-12 h-12 text-gray-400" />}</div>
<p className="text-gray-700 dark:text-gray-300 font-medium">
{dragOver ? '松开以上传' : '点击或拖拽文件到此处'}
</p>
<p className="text-sm text-gray-400 mt-1">最大文件大小: 100MB</p>
</div>
{/* Selected file */}
{selectedFile && (
<div className="bg-gray-50 dark:bg-gray-800 rounded-xl p-4">
<div className="flex items-center gap-4">
<div className="w-12 h-12 bg-blue-100 dark:bg-blue-900 rounded-lg flex items-center justify-center text-2xl">{extIcon}</div>
<div className="flex-1 min-w-0">
<p className="font-medium text-gray-900 dark:text-white truncate">{selectedFile.name}</p>
<p className="text-sm text-gray-500">{formatFileSize(selectedFile.size)} · {ext.toUpperCase()}</p>
</div>
<button onClick={() => { setSelectedFile(null); setShowMetaForm(false); if (fileInputRef.current) fileInputRef.current.value = ''; }} className="text-gray-400 hover:text-red-500"><X className="w-4 h-4" /></button>
</div>
</div>
)}
{/* Metadata form */}
{showMetaForm && selectedFile && (
<Card className="border-blue-200 dark:border-blue-800">
<CardHeader><CardTitle className="flex items-center gap-2"><FileText className="w-5 h-5" /> 书籍信息(可选)</CardTitle></CardHeader>
<CardContent className="space-y-4">
<Input label="书名" placeholder="自动从文件名填充" value={meta.title} onChange={(e) => setMeta({ ...meta, title: e.target.value })} />
<Input label="作者" placeholder="未知作者" value={meta.author} onChange={(e) => setMeta({ ...meta, author: e.target.value })} />
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">语言</label>
<select value={meta.language} onChange={(e) => setMeta({ ...meta, language: e.target.value })} className="w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-900 dark:text-white">
<option value="zh">中文</option><option value="en">英文</option><option value="ja">日文</option><option value="ko">韩文</option><option value="other">其他</option>
</select>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">简介</label>
<textarea value={meta.description} onChange={(e) => setMeta({ ...meta, description: e.target.value })} rows={3} placeholder="书籍简介..." className="w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-900 dark:text-white" />
</div>
{isUploading && (
<div>
<div className="flex justify-between text-sm mb-1"><span className="text-blue-500">上传中...</span><span className="text-blue-500">{uploadProgress}%</span></div>
<div className="h-2 bg-gray-200 dark:bg-gray-700 rounded-full overflow-hidden"><div className="h-full bg-blue-500 rounded-full transition-all" style={{ width: `${uploadProgress}%` }} /></div>
</div>
)}
{uploadError && <div className="p-3 bg-red-50 dark:bg-red-900/20 rounded-lg text-red-600 dark:text-red-400 text-sm">{uploadError}</div>}
<Button onClick={handleUpload} disabled={isUploading || !selectedFile} className="w-full flex items-center justify-center gap-2"><Upload className="w-4 h-4" /> 开始上传</Button>
</CardContent>
</Card>
)}
{/* Recent uploads */}
{uploadSuccess && recentUploads.length > 0 && (
<div>
<h3 className="text-sm font-medium text-gray-700 dark:text-gray-300 mb-3">最近上传</h3>
<div className="space-y-2">
{recentUploads.map((book) => (
<div key={book.id} className="flex items-center gap-3 p-3 bg-green-50 dark:bg-green-900/20 rounded-lg">
<span className="text-lg">
{book.fileType === 'epub' ? <BookOpen className="w-5 h-5" /> :
book.fileType === 'pdf' ? <FileText className="w-5 h-5" /> :
book.fileType === 'mobi' ? <Smartphone className="w-5 h-5" /> :
<PenLine className="w-5 h-5" />}
</span>
<div className="flex-1 min-w-0">
<p className="font-medium text-gray-900 dark:text-white truncate">{book.title}</p>
<p className="text-xs text-gray-500">{book.author} · {formatFileSize(book.fileSize)}</p>
</div>
<span className="text-green-500 text-sm flex items-center gap-1"><Check className="w-4 h-4" /> 已上传</span>
</div>
))}
</div>
</div>
)}
</div>
);
}
// ==================== Open Library Search ====================
function OpenLibrarySearch() {
const [query, setQuery] = useState('');
const [results, setResults] = useState<Array<{ key: string; title: string; author_name?: string[]; cover_i?: number; first_publish_year?: number; isbn?: string[]; publisher?: string[] }>>([]);
const [isSearching, setIsSearching] = useState(false);
const [error, setError] = useState<string | null>(null);
const [addingIds, setAddingIds] = useState<Set<string>>(new Set());
const [addedIds, setAddedIds] = useState<Set<string>>(new Set());
const handleSearch = async (e: React.FormEvent) => {
e.preventDefault();
if (!query.trim()) return;
setIsSearching(true);
setError(null);
try {
const response = await fetch(`https://openlibrary.org/search.json?q=${encodeURIComponent(query)}&limit=20&fields=key,title,author_name,cover_i,first_publish_year,isbn,publisher`);
const data = await response.json();
setResults(data.docs || []);
} catch {
setError('搜索失败,请稍后重试');
} finally {
setIsSearching(false);
}
};
const handleAddBook = async (result: typeof results[0]) => {
setAddingIds((prev) => new Set(prev).add(result.key));
try {
const apiClient = getApiClient();
const bookData: Partial<Book> = {
title: result.title,
author: result.author_name?.[0] || '未知作者',
fileType: 'epub',
filePath: `ol://${result.key}`,
fileSize: 0,
language: 'en',
isbn: result.isbn?.[0],
publisher: result.publisher?.[0],
addedAt: new Date().toISOString(),
};
const response = await apiClient.addBook(bookData);
if (response.success) setAddedIds((prev) => new Set(prev).add(result.key));
} catch { /* ignore */ } finally {
setAddingIds((prev) => { const n = new Set(prev); n.delete(result.key); return n; });
}
};
return (
<div className="space-y-6">
<div className="flex items-center justify-between">
<h2 className="text-xl font-semibold text-gray-900 dark:text-white flex items-center gap-2"><Search className="w-5 h-5" /> 搜索公开书籍</h2>
<a href="https://openlibrary.org" target="_blank" rel="noopener noreferrer" className="text-sm text-blue-500 hover:text-blue-600">Open Library ↗</a>
</div>
<form onSubmit={handleSearch} className="flex gap-3">
<input type="text" value={query} onChange={(e) => setQuery(e.target.value)} placeholder="搜索书名、作者、ISBN..." className="flex-1 px-4 py-2.5 rounded-xl border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-blue-500" />
<Button type="submit" disabled={isSearching} className="flex items-center gap-2">{isSearching ? <RefreshCw className="w-4 h-4 animate-spin" /> : <Search className="w-4 h-4" />} 搜索</Button>
</form>
{error && <div className="p-4 bg-red-50 dark:bg-red-900/20 rounded-xl text-red-600 dark:text-red-400">{error}</div>}
{results.length > 0 ? (
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
{results.map((result) => (
<Card key={result.key}>
<CardContent className="flex gap-4">
<div className="w-16 h-20 bg-gray-100 dark:bg-gray-700 rounded overflow-hidden flex-shrink-0">
{result.cover_i ? (
<img src={`https://covers.openlibrary.org/b/id/${result.cover_i}-M.jpg`} alt={result.title} className="w-full h-full object-cover" onError={(e) => { (e.target as HTMLImageElement).style.display = 'none'; }} />
) : (
<div className="w-full h-full flex items-center justify-center bg-gray-200 dark:bg-gray-600"><BookOpen className="w-6 h-6 text-gray-400" /></div>
)}
</div>
<div className="flex-1 min-w-0">
<h3 className="font-semibold text-gray-900 dark:text-white truncate">{result.title}</h3>
<p className="text-sm text-gray-500 dark:text-gray-400 truncate">{result.author_name?.[0] || '未知作者'}</p>
<div className="flex flex-wrap gap-2 mt-2">
{result.first_publish_year && <span className="px-2 py-0.5 bg-gray-100 dark:bg-gray-700 rounded text-xs">{result.first_publish_year}</span>}
{result.isbn?.[0] && <span className="px-2 py-0.5 bg-gray-100 dark:bg-gray-700 rounded text-xs">ISBN: {result.isbn[0]}</span>}
</div>
</div>
<div className="flex-shrink-0">
{addedIds.has(result.key) ? (
<span className="text-green-500 text-sm flex items-center gap-1"><Check className="w-4 h-4" /> 已添加</span>
) : (
<Button size="sm" onClick={() => handleAddBook(result)} disabled={addingIds.has(result.key)} className="flex items-center gap-1">
{addingIds.has(result.key) ? '添加中...' : <><Plus className="w-4 h-4" /> 添加</>}
</Button>
)}
</div>
</CardContent>
</Card>
))}
</div>
) : query && !isSearching ? (
<div className="text-center py-12 text-gray-500 dark:text-gray-400"><div className="text-5xl mb-4 flex justify-center"><Search className="w-12 h-12" /></div><p>未找到相关书籍</p></div>
) : null}
</div>
);
}
// ==================== Ebook Sources Management ====================
function EbookSources() {
const [sources, setSources] = useState<EbookSource[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [showAddForm, setShowAddForm] = useState(false);
const [syncingId, setSyncingId] = useState<string | null>(null);
const [expandedSource, setExpandedSource] = useState<string | null>(null);
const [testingId, setTestingId] = useState<string | null>(null);
const [testingConfig, setTestingConfig] = useState<{ testing: boolean; result?: { success: boolean; error?: string; serverInfo?: string } }>({ testing: false });
type SourceType = 'webdav' | 'smb' | 'ftp';
const [newSource, setNewSource] = useState({
name: '',
type: 'webdav' as SourceType,
// WebDAV
webdavUrl: '',
webdavUsername: '',
webdavPassword: '',
webdavBasePath: '/',
webdavRejectUnauthorized: false,
// SMB
smbShare: '',
smbUsername: '',
smbPassword: '',
smbDomain: 'WORKGROUP',
smbBasePath: '/',
// FTP
ftpHost: '',
ftpPort: 21,
ftpUsername: '',
ftpPassword: '',
ftpSecure: false,
ftpBasePath: '/',
// Options
formats: 'epub,pdf,mobi,txt',
autoSync: true,
syncIntervalSecs: 3600,
});
useEffect(() => { fetchSources(); }, []);
const fetchSources = async () => {
setIsLoading(true);
try {
const apiClient = getApiClient();
const response = await apiClient.getSources();
if (response.success && response.data) setSources(response.data);
} catch { /* ignore */ } finally { setIsLoading(false); }
};
const buildSourcePayload = () => {
const { name, type, formats, autoSync, syncIntervalSecs,
webdavUrl, webdavUsername, webdavPassword, webdavBasePath, webdavRejectUnauthorized,
smbShare, smbUsername, smbPassword, smbDomain, smbBasePath,
ftpHost, ftpPort, ftpUsername, ftpPassword, ftpSecure, ftpBasePath } = newSource;
return {
name,
type,
formats: formats.split(',').map((f) => f.trim()).filter(Boolean),
autoSync,
syncIntervalSecs,
webdavConfig: type === 'webdav' ? {
url: webdavUrl,
username: webdavUsername || undefined,
password: webdavPassword || undefined,
basePath: webdavBasePath || '/',
rejectUnauthorized: webdavRejectUnauthorized,
} : undefined,
smbConfig: type === 'smb' ? {
share: smbShare,
username: smbUsername || undefined,
password: smbPassword || undefined,
domain: smbDomain || 'WORKGROUP',
basePath: smbBasePath || '/',
} : undefined,
ftpConfig: type === 'ftp' ? {
host: ftpHost,
port: ftpPort,
username: ftpUsername || undefined,
password: ftpPassword || undefined,
secure: ftpSecure,
basePath: ftpBasePath || '/',
} : undefined,
};
};
const handleAddSource = async () => {
if (!newSource.name) return;
try {
const apiClient = getApiClient();
const response = await apiClient.createSource(buildSourcePayload());
if (response.success && response.data) {
setSources([...sources, response.data]);
setShowAddForm(false);
resetForm();
}
} catch { /* ignore */ }
};
const handleTestConfig = async () => {
setTestingConfig({ testing: true });
try {
const apiClient = getApiClient();
const response = await apiClient.testSourceConfig(buildSourcePayload());
setTestingConfig({ testing: false, result: response.data as { success: boolean; error?: string; serverInfo?: string } });
} catch (err) {
setTestingConfig({ testing: false, result: { success: false, error: String(err) } });
}
};
const handleSync = async (id: string) => {
setSyncingId(id);
try {
const apiClient = getApiClient();
await apiClient.syncSource(id);
await fetchSources();
} catch { /* ignore */ } finally { setSyncingId(null); }
};
const handleDelete = async (id: string) => {
if (!window.confirm('确定要删除此书源吗?')) return;
try {
const apiClient = getApiClient();
await apiClient.deleteSource(id);
setSources(sources.filter((s) => s.id !== id));
} catch { /* ignore */ }
};
const handleToggleEnabled = async (id: string, enabled: boolean) => {
try {
const apiClient = getApiClient();
await apiClient.updateSource(id, { enabled: !enabled });
setSources(sources.map((s) => s.id === id ? { ...s, enabled: !enabled } : s));
} catch { /* ignore */ }
};
const resetForm = () => {
setNewSource({
name: '', type: 'webdav',
webdavUrl: '', webdavUsername: '', webdavPassword: '', webdavBasePath: '/', webdavRejectUnauthorized: false,
smbShare: '', smbUsername: '', smbPassword: '', smbDomain: 'WORKGROUP', smbBasePath: '/',
ftpHost: '', ftpPort: 21, ftpUsername: '', ftpPassword: '', ftpSecure: false, ftpBasePath: '/',
formats: 'epub,pdf,mobi,txt', autoSync: true, syncIntervalSecs: 3600,
});
setTestingConfig({ testing: false });
};
const sourceTypeIcon: Record<string, React.ReactNode> = { webdav: <Cloud className="w-5 h-5" />, smb: <Folder className="w-5 h-5" />, ftp: <Globe className="w-5 h-5" /> };
const typeLabels: Record<string, string> = { webdav: 'WebDAV', smb: 'SMB/共享', ftp: 'FTP' };
return (
<div className="space-y-6">
<div className="flex items-center justify-between">
<h2 className="text-xl font-semibold text-gray-900 dark:text-white flex items-center gap-2"><BookOpen className="w-5 h-5" /> 电子书源管理</h2>
<Button onClick={() => { setShowAddForm(true); resetForm(); }} className="flex items-center gap-1"><Plus className="w-4 h-4" /> 添加书源</Button>
</div>
{/* Add Form */}
{showAddForm && (
<Card className="border-blue-200 dark:border-blue-800">
<CardHeader><CardTitle>添加新书源</CardTitle></CardHeader>
<CardContent>
{/* Basic Info */}
<div className="grid grid-cols-1 md:grid-cols-2 gap-4 mb-6">
<Input label="名称" placeholder="我的NAS书库" value={newSource.name} onChange={(e) => setNewSource({ ...newSource, name: e.target.value })} />
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">类型</label>
<select value={newSource.type} onChange={(e) => setNewSource({ ...newSource, type: e.target.value as SourceType })} className="w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-900 dark:text-white">
<option value="webdav">WebDAV (Nextcloud, Synology等)</option>
<option value="smb">SMB/共享 (Windows, QNAP等)</option>
<option value="ftp">FTP/FTPS</option>
</select>
</div>
</div>
{/* WebDAV Config */}
{newSource.type === 'webdav' && (
<div className="space-y-4 p-4 bg-blue-50/50 dark:bg-blue-900/10 rounded-xl mb-4">
<h4 className="font-medium text-blue-700 dark:text-blue-300">WebDAV 配置</h4>
<Input label="服务器地址" placeholder="https://nas.example.com/dav" value={newSource.webdavUrl} onChange={(e) => setNewSource({ ...newSource, webdavUrl: e.target.value })} />
<div className="grid grid-cols-2 gap-4">
<Input label="用户名" placeholder="admin" value={newSource.webdavUsername} onChange={(e) => setNewSource({ ...newSource, webdavUsername: e.target.value })} />
<Input label="密码" type="password" placeholder="••••••••" value={newSource.webdavPassword} onChange={(e) => setNewSource({ ...newSource, webdavPassword: e.target.value })} />
</div>
<div className="grid grid-cols-2 gap-4">
<Input label="书籍目录" placeholder="/" value={newSource.webdavBasePath} onChange={(e) => setNewSource({ ...newSource, webdavBasePath: e.target.value })} />
<div className="flex items-center gap-2 pt-6">
<input type="checkbox" id="wd-reject" checked={newSource.webdavRejectUnauthorized} onChange={(e) => setNewSource({ ...newSource, webdavRejectUnauthorized: e.target.checked })} className="w-4 h-4" />
<label htmlFor="wd-reject" className="text-sm text-gray-600 dark:text-gray-400">忽略 SSL 证书错误(自签名)</label>
</div>
</div>
</div>
)}
{/* SMB Config */}
{newSource.type === 'smb' && (
<div className="space-y-4 p-4 bg-green-50/50 dark:bg-green-900/10 rounded-xl mb-4">
<h4 className="font-medium text-green-700 dark:text-green-300">SMB 配置</h4>
<Input label="共享路径" placeholder="smb://192.168.1.100/library" value={newSource.smbShare} onChange={(e) => setNewSource({ ...newSource, smbShare: e.target.value })} />
<div className="grid grid-cols-2 gap-4">
<Input label="用户名" placeholder="admin" value={newSource.smbUsername} onChange={(e) => setNewSource({ ...newSource, smbUsername: e.target.value })} />
<Input label="密码" type="password" placeholder="••••••••" value={newSource.smbPassword} onChange={(e) => setNewSource({ ...newSource, smbPassword: e.target.value })} />
</div>
<div className="grid grid-cols-2 gap-4">
<Input label="域 (可选)" placeholder="WORKGROUP" value={newSource.smbDomain} onChange={(e) => setNewSource({ ...newSource, smbDomain: e.target.value })} />
<Input label="书籍目录" placeholder="/" value={newSource.smbBasePath} onChange={(e) => setNewSource({ ...newSource, smbBasePath: e.target.value })} />
</div>
</div>
)}
{/* FTP Config */}
{newSource.type === 'ftp' && (
<div className="space-y-4 p-4 bg-orange-50/50 dark:bg-orange-900/10 rounded-xl mb-4">
<h4 className="font-medium text-orange-700 dark:text-orange-300">FTP 配置</h4>
<div className="grid grid-cols-3 gap-4">
<div className="md:col-span-2">
<Input label="主机" placeholder="192.168.1.100" value={newSource.ftpHost} onChange={(e) => setNewSource({ ...newSource, ftpHost: e.target.value })} />
</div>
<Input label="端口" placeholder="21" value={String(newSource.ftpPort)} onChange={(e) => setNewSource({ ...newSource, ftpPort: parseInt(e.target.value) || 21 })} />
</div>
<div className="grid grid-cols-2 gap-4">
<Input label="用户名" placeholder="ftpuser" value={newSource.ftpUsername} onChange={(e) => setNewSource({ ...newSource, ftpUsername: e.target.value })} />
<Input label="密码" type="password" placeholder="••••••••" value={newSource.ftpPassword} onChange={(e) => setNewSource({ ...newSource, ftpPassword: e.target.value })} />
</div>
<div className="grid grid-cols-2 gap-4">
<Input label="书籍目录" placeholder="/" value={newSource.ftpBasePath} onChange={(e) => setNewSource({ ...newSource, ftpBasePath: e.target.value })} />
<div className="flex items-center gap-2 pt-6">
<input type="checkbox" id="ftp-secure" checked={newSource.ftpSecure} onChange={(e) => setNewSource({ ...newSource, ftpSecure: e.target.checked })} className="w-4 h-4" />
<label htmlFor="ftp-secure" className="text-sm text-gray-600 dark:text-gray-400">使用 FTPS (TLS)</label>
</div>
</div>
</div>
)}
{/* Common Options */}
<div className="grid grid-cols-1 md:grid-cols-3 gap-4 mb-4">
<Input label="支持格式" placeholder="epub,pdf,mobi,txt" value={newSource.formats} onChange={(e) => setNewSource({ ...newSource, formats: e.target.value })} />
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">同步间隔</label>
<select value={newSource.syncIntervalSecs} onChange={(e) => setNewSource({ ...newSource, syncIntervalSecs: parseInt(e.target.value) })} className="w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-900 dark:text-white">
<option value={3600}>1 小时</option>
<option value={7200}>2 小时</option>
<option value={14400}>4 小时</option>
<option value={86400}>每天</option>
</select>
</div>
<div className="flex items-center gap-2 pt-6">
<input type="checkbox" id="auto-sync" checked={newSource.autoSync} onChange={(e) => setNewSource({ ...newSource, autoSync: e.target.checked })} className="w-4 h-4" />
<label htmlFor="auto-sync" className="text-sm text-gray-600 dark:text-gray-400">自动同步新书</label>
</div>
</div>
{/* Test Result */}
{testingConfig.result && (
<div className={`p-3 rounded-lg mb-4 text-sm ${testingConfig.result.success ? 'bg-green-50 dark:bg-green-900/20 text-green-700 dark:text-green-300' : 'bg-red-50 dark:bg-red-900/20 text-red-600 dark:text-red-400'}`}>
{testingConfig.result.success
? `连接成功!${testingConfig.result.serverInfo ? `服务器: ${testingConfig.result.serverInfo}` : ''}`
: `连接失败: ${testingConfig.result.error}`}
</div>
)}
<div className="flex gap-3 mt-4">
<Button onClick={handleAddSource} disabled={!newSource.name} className="flex items-center gap-1"><Save className="w-4 h-4" /> 保存</Button>
<Button variant="secondary" onClick={handleTestConfig} disabled={testingConfig.testing || !newSource.name} className="flex items-center gap-1">
{testingConfig.testing ? <RefreshCw className="w-4 h-4 animate-spin" /> : <LinkIcon className="w-4 h-4" />} 测试连接
</Button>
<Button variant="ghost" onClick={() => { setShowAddForm(false); resetForm(); }}>取消</Button>
</div>
</CardContent>
</Card>
)}
{/* Source List */}
{isLoading ? (
<div className="flex items-center justify-center py-12"><div className="animate-spin rounded-full h-8 w-8 border-4 border-blue-500 border-t-transparent"></div></div>
) : sources.length === 0 ? (
<Card><CardContent className="text-center py-12"><div className="text-5xl mb-4 flex justify-center"><Folder className="w-12 h-12 text-gray-400" /></div><p className="text-gray-500 dark:text-gray-400">暂无电子书源</p><p className="text-sm text-gray-400 mt-1">点击上方按钮添加 NAS/远程书源</p></CardContent></Card>
) : (
<div className="space-y-3">
{sources.map((source) => (
<Card key={source.id} className="overflow-hidden">
<CardContent className="p-0">
<div className="flex items-start justify-between p-4 cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-800/50 transition-colors" onClick={() => setExpandedSource(expandedSource === source.id ? null : source.id)}>
<div className="flex items-start gap-3">
<span className="text-2xl mt-0.5">{sourceTypeIcon[source.type] || <Folder className="w-5 h-5" />}</span>
<div>
<div className="flex items-center gap-2">
<h3 className="font-semibold text-gray-900 dark:text-white">{source.name}</h3>
<span className="px-2 py-0.5 bg-gray-100 dark:bg-gray-700 rounded text-xs uppercase">{typeLabels[source.type] || source.type}</span>
{source.lastError && <span className="px-2 py-0.5 bg-red-100 dark:bg-red-900/30 text-red-600 dark:text-red-400 rounded text-xs flex items-center gap-1"><AlertTriangle className="w-3 h-3" /> 错误</span>}
</div>
<p className="text-sm text-gray-500 dark:text-gray-400 mt-1 truncate max-w-md">
{source.host ? `${source.host} ` : ''}{source.basePath || source.url || '-'}
</p>
<div className="flex gap-4 mt-1 text-xs text-gray-400">
{source.lastSyncAt && <span>最后同步: {new Date(source.lastSyncAt).toLocaleDateString('zh-CN')}</span>}
{source.bookCount > 0 && <span>{source.bookCount} 本书</span>}
</div>
</div>
</div>
<div className="flex items-center gap-3">
<label className="relative inline-flex items-center cursor-pointer" onClick={(e) => e.stopPropagation()}>
<input type="checkbox" checked={source.enabled} onChange={() => handleToggleEnabled(source.id, source.enabled)} className="sr-only peer" />
<div className="w-11 h-6 bg-gray-200 peer-focus:outline-none rounded-full peer dark:bg-gray-700 peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all dark:border-gray-600 peer-checked:bg-blue-600"></div>
</label>
<span className="text-gray-400">{expandedSource === source.id ? '▲' : '▼'}</span>
</div>
</div>
{expandedSource === source.id && (
<div className="border-t border-gray-100 dark:border-gray-700 p-4 bg-gray-50 dark:bg-gray-800/50">
<div className="grid grid-cols-2 md:grid-cols-4 gap-4 text-sm">
<div><span className="text-gray-500">类型</span><p className="font-medium text-gray-900 dark:text-white">{typeLabels[source.type] || source.type}</p></div>
<div><span className="text-gray-500">用户名</span><p className="font-medium text-gray-900 dark:text-white">{source.username || '-'}</p></div>
<div><span className="text-gray-500">自动同步</span><p className="font-medium text-gray-900 dark:text-white">{source.autoSync ? '是' : '否'}</p></div>
<div><span className="text-gray-500">同步间隔</span><p className="font-medium text-gray-900 dark:text-white">{source.syncIntervalSecs >= 3600 ? `${source.syncIntervalSecs / 3600}h` : `${source.syncIntervalSecs / 60}m`}</p></div>
</div>
{source.lastError && (
<div className="mt-3 p-2 bg-red-50 dark:bg-red-900/20 rounded text-xs text-red-600 dark:text-red-400">错误: {source.lastError}</div>
)}
<div className="flex gap-2 mt-4">
<Button size="sm" onClick={() => handleSync(source.id)} disabled={syncingId === source.id || !source.enabled} className="flex items-center gap-1">
{syncingId === source.id ? <RefreshCw className="w-4 h-4 animate-spin" /> : <RefreshCw className="w-4 h-4" />} 同步书籍
</Button>
<Button size="sm" variant="danger" onClick={() => handleDelete(source.id)} className="flex items-center gap-1"><Trash2 className="w-4 h-4" /> 删除</Button>
</div>
</div>
)}
</CardContent>
</Card>
))}
</div>
)}
</div>
);
}
// ==================== User Management ====================
function UserManagement() {
const [users, setUsers] = useState<User[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [editingUser, setEditingUser] = useState<User | null>(null);
useEffect(() => { fetchUsers(); }, []);
const fetchUsers = async () => { setIsLoading(true); try { const apiClient = getApiClient(); const response = await apiClient.getUsers(); if (response.success && response.data) setUsers(response.data.users); } catch { /* ignore */ } finally { setIsLoading(false); } };
const handleUpdateUser = async (userId: string, updates: Partial<User>) => { try { const apiClient = getApiClient(); const response = await apiClient.updateUser(userId, updates); if (response.success && response.data) setUsers(users.map((u) => u.id === userId ? response.data! : u)); setEditingUser(null); } catch { /* ignore */ } };
const handleDeleteUser = async (userId: string) => { if (!window.confirm('确定要删除此用户吗?')) return; try { const apiClient = getApiClient(); await apiClient.deleteUser(userId); setUsers(users.filter((u) => u.id !== userId)); } catch { /* ignore */ } };
const formatDate = (d?: string) => d ? new Date(d).toLocaleDateString('zh-CN', { year: 'numeric', month: 'short', day: 'numeric' }) : '-';
return (
<div className="space-y-6">
<h2 className="text-xl font-semibold text-gray-900 dark:text-white flex items-center gap-2"><Users className="w-5 h-5" /> 用户管理</h2>
{isLoading ? (
<div className="flex items-center justify-center py-12"><div className="animate-spin rounded-full h-8 w-8 border-4 border-blue-500 border-t-transparent"></div></div>
) : (
<Card>
<CardContent className="p-0">
<div className="overflow-x-auto">
<table className="w-full">
<thead className="bg-gray-50 dark:bg-gray-800">
<tr><th className="px-4 py-3 text-left text-sm font-medium text-gray-500 dark:text-gray-400">用户名</th><th className="px-4 py-3 text-left text-sm font-medium text-gray-500 dark:text-gray-400">邮箱</th><th className="px-4 py-3 text-left text-sm font-medium text-gray-500 dark:text-gray-400">角色</th><th className="px-4 py-3 text-left text-sm font-medium text-gray-500 dark:text-gray-400">会员</th><th className="px-4 py-3 text-left text-sm font-medium text-gray-500 dark:text-gray-400">注册时间</th><th className="px-4 py-3 text-right text-sm font-medium text-gray-500 dark:text-gray-400">操作</th></tr>
</thead>
<tbody className="divide-y divide-gray-200 dark:divide-gray-700">
{users.map((user) => (
<tr key={user.id} className="hover:bg-gray-50 dark:hover:bg-gray-800/50">
<td className="px-4 py-3"><div className="flex items-center gap-3"><div className="w-8 h-8 bg-blue-100 dark:bg-blue-900 rounded-full flex items-center justify-center"><span className="text-blue-600 dark:text-blue-400 font-medium">{user.username.charAt(0).toUpperCase()}</span></div><span className="font-medium text-gray-900 dark:text-white">{user.username}</span></div></td>
<td className="px-4 py-3 text-sm text-gray-500 dark:text-gray-400">{user.email || '-'}</td>
<td className="px-4 py-3"><span className={`px-2 py-0.5 rounded-full text-xs ${user.role === 'admin' ? 'bg-purple-100 dark:bg-purple-900 text-purple-700 dark:text-purple-300' : 'bg-gray-100 dark:bg-gray-700 text-gray-600 dark:text-gray-400'}`}>{user.role === 'admin' ? '管理员' : '用户'}</span></td>
<td className="px-4 py-3"><span className={`px-2 py-0.5 rounded-full text-xs ${user.membership === 'premium' ? 'bg-amber-100 dark:bg-amber-900 text-amber-700 dark:text-amber-300' : 'bg-gray-100 dark:bg-gray-700 text-gray-500'}`}>{user.membership === 'premium' ? 'Premium' : '免费'}</span></td>
<td className="px-4 py-3 text-sm text-gray-500 dark:text-gray-400">{formatDate(user.createdAt)}</td>
<td className="px-4 py-3 text-right"><div className="flex items-center justify-end gap-2"><Button size="sm" variant="ghost" onClick={() => setEditingUser(user)}><Pencil className="w-4 h-4" /></Button><Button size="sm" variant="danger" onClick={() => handleDeleteUser(user.id)}><Trash2 className="w-4 h-4" /></Button></div></td>
</tr>
))}
</tbody>
</table>
</div>
</CardContent>
</Card>
)}
{editingUser && (
<div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50">
<div className="bg-white dark:bg-gray-800 rounded-2xl shadow-2xl w-full max-w-md p-6">
<h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-4">编辑用户: {editingUser.username}</h3>
<div className="space-y-4">
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">角色</label>
<select id="edit-role" defaultValue={editingUser.role} className="w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-900 dark:text-white">
<option value="user">用户</option><option value="admin">管理员</option>
</select>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">会员</label>
<select id="edit-membership" defaultValue={editingUser.membership} className="w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-900 dark:text-white">
<option value="free">免费</option><option value="premium">Premium</option>
</select>
</div>
</div>
<div className="flex gap-3 mt-6">
<Button onClick={() => { const role = (document.getElementById('edit-role') as HTMLSelectElement).value as 'admin' | 'user'; const membership = (document.getElementById('edit-membership') as HTMLSelectElement).value as 'free' | 'premium'; handleUpdateUser(editingUser.id, { role, membership }); }}>保存</Button>
<Button variant="secondary" onClick={() => setEditingUser(null)}>取消</Button>
</div>
</div>
</div>
)}
</div>
);
}
// ==================== Books Management ====================
function BooksManagement() {
const [books, setBooks] = useState<Book[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [filter, setFilter] = useState<'all' | 'epub' | 'pdf' | 'txt' | 'mobi'>('all');
useEffect(() => { fetchBooks(); }, []);
const fetchBooks = async () => { setIsLoading(true); try { const apiClient = getApiClient(); const response = await apiClient.getBooks({ limit: 100 }); if (response.success && response.data) setBooks(response.data.books); } catch { /* ignore */ } finally { setIsLoading(false); } };
const handleDeleteBook = async (bookId: string) => { if (!window.confirm('确定要删除此书籍吗?')) return; try { const apiClient = getApiClient(); await apiClient.deleteBook(bookId); setBooks(books.filter((b) => b.id !== bookId)); } catch { /* ignore */ } };
const formatFileSize = (bytes: number): string => { if (bytes === 0) return '0 B'; const k = 1024; const sizes = ['B', 'KB', 'MB', 'GB']; const i = Math.floor(Math.log(bytes) / Math.log(k)); return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i]; };
const filteredBooks = filter === 'all' ? books : books.filter((b) => b.fileType === filter);
return (
<div className="space-y-6">
<h2 className="text-xl font-semibold text-gray-900 dark:text-white flex items-center gap-2"><BookOpen className="w-5 h-5" /> 书籍管理</h2>
<div className="flex gap-2 flex-wrap">
{(['all', 'epub', 'pdf', 'txt', 'mobi'] as const).map((f) => (
<button key={f} onClick={() => setFilter(f)} className={`px-4 py-2 rounded-lg text-sm font-medium transition-colors ${filter === f ? 'bg-blue-500 text-white' : 'bg-gray-100 dark:bg-gray-800 text-gray-600 dark:text-gray-400 hover:bg-gray-200 dark:hover:bg-gray-700'}`}>
{f === 'all' ? '全部' : f.toUpperCase()}
</button>
))}
</div>
{isLoading ? (
<div className="flex items-center justify-center py-12"><div className="animate-spin rounded-full h-8 w-8 border-4 border-blue-500 border-t-transparent"></div></div>
) : filteredBooks.length === 0 ? (
<Card><CardContent className="text-center py-12"><div className="text-5xl mb-4 flex justify-center"><BookOpen className="w-12 h-12 text-gray-400" /></div><p className="text-gray-500 dark:text-gray-400">{filter === 'all' ? '暂无书籍' : `暂无${filter.toUpperCase()}格式的书籍`}</p></CardContent></Card>
) : (
<Card>
<CardContent className="p-0">
<div className="overflow-x-auto">
<table className="w-full">
<thead className="bg-gray-50 dark:bg-gray-800">
<tr><th className="px-4 py-3 text-left text-sm font-medium text-gray-500 dark:text-gray-400">书籍</th><th className="px-4 py-3 text-left text-sm font-medium text-gray-500 dark:text-gray-400">作者</th><th className="px-4 py-3 text-left text-sm font-medium text-gray-500 dark:text-gray-400">格式</th><th className="px-4 py-3 text-left text-sm font-medium text-gray-500 dark:text-gray-400">大小</th><th className="px-4 py-3 text-left text-sm font-medium text-gray-500 dark:text-gray-400">进度</th><th className="px-4 py-3 text-right text-sm font-medium text-gray-500 dark:text-gray-400">操作</th></tr>
</thead>
<tbody className="divide-y divide-gray-200 dark:divide-gray-700">
{filteredBooks.map((book) => (
<tr key={book.id} className="hover:bg-gray-50 dark:hover:bg-gray-800/50">
<td className="px-4 py-3">
<div className="flex items-center gap-3">
<BookCover book={book} className="w-10 h-14" />
<span className="font-medium text-gray-900 dark:text-white truncate max-w-[200px]">{book.title}</span>
</div>
</td>
<td className="px-4 py-3 text-sm text-gray-500 dark:text-gray-400">{book.author || '-'}</td>
<td className="px-4 py-3"><span className="px-2 py-0.5 bg-gray-100 dark:bg-gray-700 rounded text-xs uppercase">{book.fileType}</span></td>
<td className="px-4 py-3 text-sm text-gray-500 dark:text-gray-400">{formatFileSize(book.fileSize)}</td>
<td className="px-4 py-3">
{book.readingProgress !== undefined && book.readingProgress > 0 ? (
<div className="flex items-center gap-2"><div className="w-16 h-2 bg-gray-200 dark:bg-gray-700 rounded-full"><div className="h-full bg-blue-500 rounded-full" style={{ width: `${book.readingProgress}%` }} /></div><span className="text-xs text-gray-500">{book.readingProgress}%</span></div>
) : <span className="text-gray-400">-</span>}
</td>
<td className="px-4 py-3 text-right"><Button size="sm" variant="danger" onClick={() => handleDeleteBook(book.id)}><Trash2 className="w-4 h-4" /></Button></td>
</tr>
))}
</tbody>
</table>
</div>
</CardContent>
</Card>
)}
</div>
);
}
// ==================== System Settings ====================
function SystemSettings() {
const [settings, setSettings] = useState({ siteName: '书仓', siteDescription: '您的私人电子书库', allowPublicRegistration: true, defaultMembership: 'free' as 'free' | 'premium', enableTTS: true, ttsProvider: 'browser' as 'browser' | 'server' });
const [isSaving, setIsSaving] = useState(false);
const [saveMessage, setSaveMessage] = useState<string | null>(null);
const handleSave = async () => { setIsSaving(true); setSaveMessage(null); await new Promise((r) => setTimeout(r, 1000)); localStorage.setItem('bookdock_system_settings', JSON.stringify(settings)); setSaveMessage('设置已保存'); setIsSaving(false); setTimeout(() => setSaveMessage(null), 3000); };
return (
<div className="space-y-6">
<h2 className="text-xl font-semibold text-gray-900 dark:text-white flex items-center gap-2"><Settings className="w-5 h-5" /> 系统设置</h2>
<Card>
<CardHeader><CardTitle>基本信息</CardTitle></CardHeader>
<CardContent className="space-y-4">
<div><label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">网站名称</label><input type="text" value={settings.siteName} onChange={(e) => setSettings({ ...settings, siteName: e.target.value })} className="w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-900 dark:text-white" /></div>
<div><label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">网站描述</label><textarea value={settings.siteDescription} onChange={(e) => setSettings({ ...settings, siteDescription: e.target.value })} rows={3} className="w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-900 dark:text-white" /></div>
</CardContent>
</Card>
<Card>
<CardHeader><CardTitle>用户设置</CardTitle></CardHeader>
<CardContent className="space-y-4">
<div className="flex items-center justify-between">
<div><p className="font-medium text-gray-900 dark:text-white">允许公开注册</p><p className="text-sm text-gray-500">允许新用户自行注册账户</p></div>
<label className="relative inline-flex items-center cursor-pointer"><input type="checkbox" checked={settings.allowPublicRegistration} onChange={(e) => setSettings({ ...settings, allowPublicRegistration: e.target.checked })} className="sr-only peer" /><div className="w-11 h-6 bg-gray-200 rounded-full peer dark:bg-gray-700 peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all dark:border-gray-600 peer-checked:bg-blue-600"></div></label>
</div>
<div><label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">默认会员类型</label><select value={settings.defaultMembership} onChange={(e) => setSettings({ ...settings, defaultMembership: e.target.value as 'free' | 'premium' })} className="w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-900 dark:text-white"><option value="free">免费</option><option value="premium">Premium</option></select></div>
</CardContent>
</Card>
<Card>
<CardHeader><CardTitle>TTS 设置</CardTitle></CardHeader>
<CardContent className="space-y-4">
<div className="flex items-center justify-between">
<div><p className="font-medium text-gray-900 dark:text-white">启用语音朗读</p><p className="text-sm text-gray-500">允许用户使用文字转语音功能</p></div>
<label className="relative inline-flex items-center cursor-pointer"><input type="checkbox" checked={settings.enableTTS} onChange={(e) => setSettings({ ...settings, enableTTS: e.target.checked })} className="sr-only peer" /><div className="w-11 h-6 bg-gray-200 rounded-full peer dark:bg-gray-700 peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all dark:border-gray-600 peer-checked:bg-blue-600"></div></label>
</div>
<div><label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">TTS 提供商</label><select value={settings.ttsProvider} onChange={(e) => setSettings({ ...settings, ttsProvider: e.target.value as 'browser' | 'server' })} className="w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-900 dark:text-white"><option value="browser">浏览器 TTS</option><option value="server">服务器 TTS</option></select></div>
</CardContent>
</Card>
{saveMessage && <div className="p-4 bg-green-50 dark:bg-green-900/20 rounded-xl text-green-600 dark:text-green-400 text-center">{saveMessage}</div>}
<Button onClick={handleSave} disabled={isSaving} className="w-full flex items-center justify-center gap-2">{isSaving ? '保存中...' : <><Save className="w-4 h-4" /> 保存设置</>}</Button>
</div>
);
}
// ==================== Main Admin Component ====================
export default function Admin() {
const location = useLocation();
const currentPath = location.pathname.replace('/admin', '') || '/';
const tabs = [
{ path: '/admin', label: '上传', icon: Upload, exact: true },
{ path: '/admin/sources', label: '书源管理', icon: BookOpen },
{ path: '/admin/users', label: '用户管理', icon: Users },
{ path: '/admin/books', label: '书籍管理', icon: BookOpen },
{ path: '/admin/search', label: '公开搜索', icon: Search },
{ path: '/admin/settings', label: '系统设置', icon: Settings },
];
return (
<div className="space-y-6">
<h1 className="text-3xl font-bold text-gray-900 dark:text-white">管理面板</h1>
<div className="flex gap-1 border-b border-gray-200 dark:border-gray-700 overflow-x-auto">
{tabs.map((tab) => {
const Icon = tab.icon;
return (
<Link key={tab.path} to={tab.path} className={`px-4 py-3 text-sm font-medium border-b-2 transition-colors whitespace-nowrap flex items-center gap-1 ${currentPath === tab.path ? 'border-blue-500 text-blue-600 dark:text-blue-400' : 'border-transparent text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-300'}`}>
<Icon className="w-4 h-4" /> {tab.label}
</Link>
);
})}
</div>
<Routes>
<Route path="/" element={<FileUpload />} />
<Route path="/sources" element={<EbookSources />} />
<Route path="/users" element={<AdminUsers />} />
<Route path="/books" element={<BooksManagement />} />
<Route path="/search" element={<OpenLibrarySearch />} />
<Route path="/settings" element={<SystemSettings />} />
</Routes>
</div>
);
}