forked from jordanlambrecht/tracker-tracker
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDownloadClients.tsx
More file actions
708 lines (658 loc) · 22 KB
/
Copy pathDownloadClients.tsx
File metadata and controls
708 lines (658 loc) · 22 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
// src/components/DownloadClients.tsx
"use client"
import { useQuery, useQueryClient } from "@tanstack/react-query"
import { H2, H3, Paragraph, Subheader, Subtext } from "@typography"
import { useCallback, useState } from "react"
import {
Badge,
Button,
Card,
CardListSkeleton,
CollapsibleCard,
ConfirmRemove,
Input,
MaskedSecret,
Notice,
NumberInput,
SaveDiscardBar,
Select,
Toggle,
UptimeBar,
} from "@/components/ui"
import { useActionStatus } from "@/hooks/useActionStatus"
import { useCrudCard } from "@/hooks/useCrudCard"
import { formatTimeAgo } from "@/lib/formatters"
import { PORT_MAX, PORT_MIN } from "@/lib/limits"
import { clientQueryOptions } from "@/lib/query-options"
import type { SafeDownloadClient } from "@/types/api"
// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------
type ClientType = "qbittorrent" | "deluge" | "transmission" | "rtorrent"
type DownloadClient = SafeDownloadClient
const EMPTY_TRACKERS: string[] = []
const CLIENT_TYPE_OPTIONS: { value: ClientType; label: string; disabled?: boolean }[] = [
{ value: "qbittorrent", label: "qBittorrent" },
{ value: "deluge", label: "Deluge (coming soon)", disabled: true },
{ value: "transmission", label: "Transmission (coming soon)", disabled: true },
{ value: "rtorrent", label: "rTorrent (coming soon)", disabled: true },
]
// ---------------------------------------------------------------------------
// ClientCard
// ---------------------------------------------------------------------------
interface ClientCardProps {
client: DownloadClient
linkedTrackers: string[]
onSaved: (id: number, updated: DownloadClient) => void
onRemove: (id: number) => void
onSetDefault: (id: number) => void
}
/** Fields tracked for dirty detection (excludes transient fields like lastPolledAt). */
const DRAFT_KEYS: (keyof DownloadClient)[] = [
"name",
"type",
"enabled",
"host",
"port",
"useSsl",
"pollIntervalSeconds",
"crossSeedTags",
]
function buildPatch(draft: DownloadClient, saved: DownloadClient): Record<string, unknown> | null {
const patch: Record<string, unknown> = {}
for (const key of DRAFT_KEYS) {
const a = draft[key]
const b = saved[key]
if (Array.isArray(a) && Array.isArray(b)) {
if (a.length !== b.length || a.some((v, i) => v !== b[i])) patch[key] = a
} else if (a !== b) patch[key] = a
}
return Object.keys(patch).length > 0 ? patch : null
}
function ClientCard({ client, linkedTrackers, onSaved, onRemove, onSetDefault }: ClientCardProps) {
const {
draft,
updateDraft,
dirty,
saving,
saveError,
expanded,
toggleExpand,
handleSave,
handleDiscard,
} = useCrudCard({
item: client,
apiEndpoint: "/api/clients",
buildPatch,
onSaved,
})
const {
status: connectionStatus,
error: connectionError,
execute: executeTest,
} = useActionStatus()
const [tagInput, setTagInput] = useState("")
// Credential change state — show inputs for new clients (no creds yet) or after "Change"
const [changingCredentials, setChangingCredentials] = useState(!client.hasCredentials)
const [newUsername, setNewUsername] = useState("")
const [newPassword, setNewPassword] = useState("")
const [credError, setCredError] = useState<string | null>(null)
const { data: uptimeData = null } = useQuery({
queryKey: ["client-uptime", client.id],
queryFn: async ({ signal }) => {
const res = await fetch(`/api/clients/${client.id}/uptime`, { signal })
if (!res.ok) return null
return res.json() as Promise<{
buckets: { bucketTs: string; ok: number; fail: number }[]
uptimePercent: number | null
}>
},
refetchInterval: 5 * 60 * 1000,
})
const handleTestConnection = () =>
executeTest(async () => {
const res = await fetch(`/api/clients/${client.id}/test`, { method: "POST" })
if (!res.ok) {
const data = await res.json().catch(() => ({}))
throw new Error(data.error || "Connection failed")
}
})
async function handleSaveCredentials() {
if (!newUsername.trim() || !newPassword.trim()) return
setCredError(null)
try {
const res = await fetch(`/api/clients/${client.id}`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ username: newUsername, password: newPassword }),
})
if (!res.ok) {
const data = await res.json().catch(() => ({}))
setCredError(data.error || "Failed to save credentials")
return
}
onSaved(client.id, { ...client, hasCredentials: true })
setChangingCredentials(false)
setNewUsername("")
setNewPassword("")
} catch {
setCredError("Network error — could not save credentials")
}
}
const statusBadge = client.enabled ? (
<Badge variant="success">Active</Badge>
) : (
<Badge variant="default">Disabled</Badge>
)
return (
<CollapsibleCard
expanded={expanded}
onToggle={toggleExpand}
header={
<div className="flex flex-col gap-0.5">
<div className="flex items-center gap-3">
<H3 className="truncate">{client.name || "Untitled Client"}</H3>
{statusBadge}
{client.isDefault && <Badge variant="accent">Default</Badge>}
</div>
<div className="flex items-center gap-3 flex-wrap">
<span className="text-3xs font-mono text-tertiary">
{client.lastPolledAt
? `Last seen: ${formatTimeAgo(client.lastPolledAt)}`
: "Last seen: Never"}
</span>
{client.errorSince && (
<span className="text-3xs font-mono text-danger">
Down since {formatTimeAgo(client.errorSince)}
</span>
)}
{client.lastError && !client.errorSince && (
<span className="text-3xs font-mono text-danger">{client.lastError}</span>
)}
</div>
</div>
}
trailing={CLIENT_TYPE_OPTIONS.find((o) => o.value === client.type)?.label}
subheader={
uptimeData ? (
<div className="px-5 pb-3">
<UptimeBar buckets={uptimeData.buckets} uptimePercent={uptimeData.uptimePercent} />
</div>
) : undefined
}
>
{/* Row 1: Name + Type + Enabled */}
<div className="form-responsive-row pt-5">
<div className="flex-1">
<Input
label="Name"
value={draft.name}
onChange={(e) => updateDraft({ name: e.target.value })}
placeholder="My qBittorrent"
/>
</div>
<div className="w-full sm:w-40">
<Select
label="Type"
value={draft.type}
onChange={(v) => updateDraft({ type: v as ClientType })}
ariaLabel="Client type"
size="md"
options={CLIENT_TYPE_OPTIONS}
/>
</div>
</div>
<Toggle
label="Enabled"
checked={draft.enabled}
onChange={(v) => updateDraft({ enabled: v })}
description="Disabled clients are not polled and their stats are excluded from dashboard totals."
/>
<div className="border-t border-border" />
{/* Row 2: Host + Port + SSL */}
<div className="form-responsive-row">
<div className="flex-1">
<Input
label="Host"
value={draft.host}
onChange={(e) => updateDraft({ host: e.target.value })}
placeholder="localhost or 192.168.1.100"
/>
</div>
<NumberInput
label="Port"
value={draft.port}
onChange={(v) => updateDraft({ port: v })}
min={PORT_MIN}
max={PORT_MAX}
/>
</div>
<Toggle
label="Use SSL"
checked={draft.useSsl}
onChange={(v) => updateDraft({ useSsl: v })}
description={`Connect via ${draft.useSsl ? "https" : "http"}://${draft.host}:${draft.port}`}
/>
{draft.useSsl && draft.port === 80 && (
<Notice
variant="warn"
message="SSL is enabled but port is 80 (standard HTTP). Did you mean port 443?"
/>
)}
{!draft.useSsl && draft.port === 443 && (
<Notice
variant="warn"
message="Port 443 is typically used with SSL. Did you mean to enable SSL?"
/>
)}
<div className="border-t border-border" />
{/* Row 3: Auth */}
<div className="flex flex-col gap-2">
<H2 className="uppercase tracking-wider">Credentials</H2>
{changingCredentials ? (
<div className="flex flex-col gap-3">
<div className="flex flex-col sm:flex-row gap-4">
<div className="flex-1">
<Input
label="Username"
value={newUsername}
onChange={(e) => setNewUsername(e.target.value)}
placeholder="admin"
name="client-username"
autoComplete="off"
data-1p-ignore
/>
</div>
<div className="flex-1">
<Input
type="password"
label="Password"
value={newPassword}
onChange={(e) => setNewPassword(e.target.value)}
placeholder="••••••••"
name="client-password"
autoComplete="off"
data-1p-ignore
/>
</div>
</div>
<div className="flex items-center gap-2">
<Button
size="sm"
variant="primary"
onClick={handleSaveCredentials}
disabled={!newUsername.trim() || !newPassword.trim()}
text="Save Credentials"
/>
{client.hasCredentials && (
<button
type="button"
onClick={() => {
setChangingCredentials(false)
setNewUsername("")
setNewPassword("")
setCredError(null)
}}
className="ghost-link"
>
Cancel
</button>
)}
</div>
<Notice message={credError} />
</div>
) : (
<MaskedSecret onChangeClick={() => setChangingCredentials(true)} />
)}
</div>
<div className="border-t border-border" />
{/* Row 4: Polling */}
<div className="flex items-end gap-4">
<div className="w-48">
<Select
label="Poll Frequency"
value={String(draft.pollIntervalSeconds)}
onChange={(v) => updateDraft({ pollIntervalSeconds: parseInt(v, 10) })}
ariaLabel="Polling frequency"
size="md"
options={[
{ value: "60", label: "Every minute" },
{ value: "120", label: "Every 2 minutes" },
{ value: "300", label: "Every 5 minutes" },
{ value: "600", label: "Every 10 minutes" },
]}
/>
</div>
</div>
<div className="border-t border-border" />
{/* Cross-seed tags */}
<div className="flex flex-col gap-3">
<H3>Cross-Seed Tags</H3>
<div className="flex flex-col gap-2">
<div className="flex gap-2">
<div className="flex-1">
<Input
value={tagInput}
onChange={(e) => setTagInput(e.target.value)}
placeholder="i.e cross-seed"
onKeyDown={(e) => {
if ((e.key === "Enter" || e.key === ",") && tagInput.trim()) {
e.preventDefault()
const tag = tagInput.trim().replace(/,/g, "")
if (tag && !draft.crossSeedTags.includes(tag)) {
updateDraft({ crossSeedTags: [...draft.crossSeedTags, tag] })
}
setTagInput("")
}
}}
/>
</div>
<Button
size="sm"
variant="secondary"
disabled={!tagInput.trim()}
onClick={() => {
const tag = tagInput.trim()
if (tag && !draft.crossSeedTags.includes(tag)) {
updateDraft({ crossSeedTags: [...draft.crossSeedTags, tag] })
}
setTagInput("")
}}
text="Add"
/>
</div>
{draft.crossSeedTags.length > 0 && (
<div className="flex gap-2 flex-wrap">
{draft.crossSeedTags.map((tag) => (
<span
key={tag}
className="inline-flex items-center gap-2 font-mono text-xs text-primary bg-control-bg nm-inset-sm px-2.5 py-1 rounded-nm-sm"
>
{tag}
<button
type="button"
onClick={() =>
updateDraft({
crossSeedTags: draft.crossSeedTags.filter((t) => t !== tag),
})
}
className="text-tertiary hover:text-danger transition-colors cursor-pointer text-xs leading-none"
aria-label={`Remove tag ${tag}`}
>
✕
</button>
</span>
))}
</div>
)}
</div>
<Subtext>
Torrents with these tags are counted as cross-seeded and tracked separately from direct
seeding stats on the dashboard.
</Subtext>
</div>
{/* Linked trackers */}
{linkedTrackers.length > 0 && (
<div className="flex items-center gap-2">
<Subheader className="uppercase tracking-wider shrink-0">Linked Trackers</Subheader>
<div className="flex gap-2 flex-wrap">
{linkedTrackers.map((name) => (
<Badge key={name} variant="default">
{name}
</Badge>
))}
</div>
</div>
)}
<Subtext>
Trackers are linked to this client via their qBittorrent Tag field in individual tracker
settings.
</Subtext>
<SaveDiscardBar
dirty={dirty}
saving={saving}
onSave={handleSave}
onDiscard={handleDiscard}
error={saveError}
/>
<div className="border-t border-border" />
{/* Actions */}
<div className="flex items-center gap-3 flex-wrap">
<Button
size="sm"
variant="secondary"
onClick={handleTestConnection}
disabled={connectionStatus === "pending"}
>
{connectionStatus === "pending"
? "Testing..."
: connectionStatus === "success"
? "Connected"
: connectionStatus === "failed"
? "Failed — Retry"
: "Test Connection"}
</Button>
{connectionStatus === "success" && <Badge variant="success">Connection OK</Badge>}
{connectionStatus === "failed" && <Badge variant="danger">Failed</Badge>}
<div className="flex-1" />
{!client.isDefault && (
<Button
size="sm"
variant="ghost"
onClick={() => onSetDefault(client.id)}
text="Set as Default"
/>
)}
<ConfirmRemove onConfirm={() => onRemove(client.id)} />
</div>
{connectionStatus === "failed" && connectionError && <Notice message={connectionError} />}
</CollapsibleCard>
)
}
// ---------------------------------------------------------------------------
// DownloadClients
// ---------------------------------------------------------------------------
function AddClientForm({
onCreated,
onCancel,
isFirst,
}: {
onCreated: () => void
onCancel: () => void
isFirst: boolean
}) {
const [name, setName] = useState("New Client")
const [host, setHost] = useState("localhost")
const [port, setPort] = useState(8080)
const [username, setUsername] = useState("")
const [password, setPassword] = useState("")
const [error, setError] = useState<string | null>(null)
const [saving, setSaving] = useState(false)
const canSubmit = name.trim() && host.trim() && username.trim() && password.trim()
async function handleSubmit() {
if (!canSubmit) return
setSaving(true)
setError(null)
try {
const res = await fetch("/api/clients", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
name: name.trim(),
host: host.trim(),
port,
username: username.trim(),
password,
isDefault: isFirst,
}),
})
if (!res.ok) {
const data = await res.json().catch(() => ({}))
setError(data.error || "Failed to create client")
return
}
onCreated()
} catch {
setError("Network error")
} finally {
setSaving(false)
}
}
return (
<Card elevation="raised" className="flex flex-col gap-4">
<H3>Add Download Client</H3>
<div className="form-responsive-row">
<div className="flex-1">
<Input
label="Name"
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="My qBittorrent"
/>
</div>
<div className="flex flex-row gap-4 items-end">
<div className="flex-1 sm:flex-none sm:w-40">
<Input
label="Host"
value={host}
onChange={(e) => setHost(e.target.value)}
placeholder="localhost"
/>
</div>
<NumberInput label="Port" value={port} onChange={setPort} min={PORT_MIN} max={PORT_MAX} />
</div>
</div>
<div className="flex flex-col sm:flex-row gap-4">
<div className="flex-1">
<Input
label="Username"
value={username}
onChange={(e) => setUsername(e.target.value)}
placeholder="admin"
name="client-username"
autoComplete="off"
data-1p-ignore
/>
</div>
<div className="flex-1">
<Input
type="password"
label="Password"
value={password}
onChange={(e) => setPassword(e.target.value)}
placeholder="••••••••"
name="client-password"
autoComplete="off"
data-1p-ignore
/>
</div>
</div>
<Notice message={error} />
<div className="flex items-center gap-3">
<Button
size="sm"
onClick={handleSubmit}
disabled={!canSubmit || saving}
text={saving ? "Creating..." : "Create Client"}
/>
<Button size="sm" variant="ghost" onClick={onCancel} text="Cancel" />
</div>
</Card>
)
}
function DownloadClients() {
const queryClient = useQueryClient()
const [showAddForm, setShowAddForm] = useState(false)
const { data: clients = [], isLoading: loading } = useQuery({
...clientQueryOptions,
})
const handleSaved = useCallback(
(id: number, updated: DownloadClient) => {
queryClient.setQueryData<DownloadClient[]>(clientQueryOptions.queryKey, (prev) =>
prev?.map((c) => (c.id === id ? updated : c))
)
},
[queryClient]
)
const handleRemove = useCallback(
async (id: number) => {
await fetch(`/api/clients/${id}`, { method: "DELETE" })
queryClient.setQueryData<DownloadClient[]>(clientQueryOptions.queryKey, (prev) => {
if (!prev) return prev
const next = prev.filter((c) => c.id !== id)
if (next.length > 0 && !next.some((c) => c.isDefault)) {
next[0] = { ...next[0], isDefault: true }
}
return next
})
},
[queryClient]
)
const handleSetDefault = useCallback(
(id: number) => {
queryClient.setQueryData<DownloadClient[]>(clientQueryOptions.queryKey, (prev) =>
prev?.map((c) => ({ ...c, isDefault: c.id === id }))
)
fetch(`/api/clients/${id}`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ isDefault: true }),
}).catch(() => {})
},
[queryClient]
)
if (loading) {
return <CardListSkeleton count={2} />
}
return (
<div className="flex flex-col gap-6">
{clients.length === 0 && !showAddForm ? (
<Card elevation="raised" className="flex flex-col items-center gap-4 py-10">
<span className="text-2xl" aria-hidden="true">
📡
</span>
<div className="text-center flex flex-col gap-2">
<H3>No download clients configured</H3>
<Paragraph>
Add a download client to track seeding stats, active torrents, and per-tracker
download activity.
</Paragraph>
</div>
<Button size="sm" onClick={() => setShowAddForm(true)} text="Add Download Client" />
</Card>
) : (
<>
{clients.map((client) => (
<ClientCard
key={client.id}
client={client}
linkedTrackers={EMPTY_TRACKERS}
onSaved={handleSaved}
onRemove={handleRemove}
onSetDefault={handleSetDefault}
/>
))}
{showAddForm ? (
<AddClientForm
isFirst={clients.length === 0}
onCreated={() => {
setShowAddForm(false)
queryClient.invalidateQueries({ queryKey: clientQueryOptions.queryKey })
}}
onCancel={() => setShowAddForm(false)}
/>
) : (
<Button
size="sm"
variant="secondary"
className="self-start"
onClick={() => setShowAddForm(true)}
text="+ Add Client"
/>
)}
</>
)}
</div>
)
}
export { DownloadClients }