forked from jordanlambrecht/tracker-tracker
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTrackerSettingsSheet.tsx
More file actions
550 lines (503 loc) · 18.3 KB
/
Copy pathTrackerSettingsSheet.tsx
File metadata and controls
550 lines (503 loc) · 18.3 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
// src/components/TrackerSettingsSheet.tsx
"use client"
import { H2 } from "@typography"
import clsx from "clsx"
import { useRouter } from "next/navigation"
import { type SyntheticEvent, useCallback, useEffect, useState } from "react"
import {
Button,
ConfirmRemove,
InfoTip,
Input,
MaskedSecret,
Notice,
QbtTagWarning,
Sheet,
Toggle,
} from "@/components/ui"
import { ColorPicker } from "@/components/ui/ColorPicker"
import { findRegistryEntry } from "@/data/tracker-registry"
import { DOCS } from "@/lib/constants"
import { localDateStr } from "@/lib/formatters"
import type { TrackerSummary } from "@/types/api"
interface TrackerSettingsSheetProps {
open: boolean
tracker: TrackerSummary
onClose: () => void
onUpdated: () => void
}
interface FormState {
name: string
color: string
qbtTag: string
joinedAt: string
baseUrl: string
useProxy: boolean
countCrossSeedUnsatisfied: boolean
hideUnreadBadges: boolean
mouseholeUrl: string
}
function formStateFromTracker(t: TrackerSummary): FormState {
return {
name: t.name,
color: t.color,
qbtTag: t.qbtTag ?? "",
joinedAt: t.joinedAt ?? "",
baseUrl: t.baseUrl,
useProxy: t.useProxy ?? false,
countCrossSeedUnsatisfied: t.countCrossSeedUnsatisfied ?? false,
hideUnreadBadges: t.hideUnreadBadges ?? false,
mouseholeUrl: t.mouseholeUrl ?? "",
}
}
function TrackerSettingsSheet({ open, tracker, onClose, onUpdated }: TrackerSettingsSheetProps) {
const router = useRouter()
const [form, setForm] = useState<FormState>(() => formStateFromTracker(tracker))
const updateField = useCallback(<K extends keyof FormState>(key: K, value: FormState[K]) => {
setForm((prev) => ({ ...prev, [key]: value }))
}, [])
useEffect(() => {
setForm(formStateFromTracker(tracker))
}, [tracker])
const registryEntry = findRegistryEntry(tracker.baseUrl)
const [proxyAvailable, setProxyAvailable] = useState<boolean | null>(null)
useEffect(() => {
if (!open || proxyAvailable !== null) return
fetch("/api/settings")
.then((r) => (r.ok ? r.json() : null))
.then((data) => {
setProxyAvailable(data ? !!data.proxyEnabled : false)
})
.catch(() => setProxyAvailable(false))
}, [open, proxyAvailable])
const [changingKey, setChangingKey] = useState(false)
const [newApiToken, setNewApiToken] = useState("")
const [editAvistazUsername, setEditAvistazUsername] = useState("")
const [editAvistazCookies, setEditAvistazCookies] = useState("")
const [editDcCookies, setEditDcCookies] = useState("")
const [errors, setErrors] = useState<Record<string, string>>({})
const [saving, setSaving] = useState(false)
const [deleting, setDeleting] = useState(false)
const resetTransientState = useCallback(() => {
setChangingKey(false)
setNewApiToken("")
setEditAvistazUsername("")
setEditAvistazCookies("")
setEditDcCookies("")
setErrors({})
setSaving(false)
setDeleting(false)
}, [])
function handleClose() {
resetTransientState()
onClose()
}
async function handleSave(e: SyntheticEvent) {
e.preventDefault()
const validationErrors: Record<string, string> = {}
if (!form.name.trim()) validationErrors.name = "Name is required"
if (!form.baseUrl.trim()) {
validationErrors.baseUrl = "Base URL is required"
} else {
try {
new URL(form.baseUrl)
} catch {
validationErrors.baseUrl = "Invalid URL"
}
}
if (changingKey && tracker.platformType === "digitalcore") {
const trimmed = editDcCookies.trim()
if (!trimmed) {
validationErrors.apiToken = "Session cookies are required"
} else {
const hasUid = /(?:^|;\s*)uid=([^;]+)/.test(trimmed)
const hasPass = /(?:^|;\s*)pass=([^;]+)/.test(trimmed)
if (!hasUid || !hasPass) {
validationErrors.apiToken = "Cookie string must contain both uid and pass values"
}
}
} else if (changingKey && tracker.platformType !== "avistaz" && !newApiToken.trim()) {
validationErrors.apiToken = "API token cannot be empty"
}
if (Object.keys(validationErrors).length > 0) {
setErrors(validationErrors)
return
}
setErrors({})
setSaving(true)
let trimmedToken = newApiToken.trim()
if (changingKey && tracker.platformType === "avistaz") {
if (!editAvistazUsername.trim() || !editAvistazCookies.trim()) {
setErrors({ apiToken: "Username and cookies are required" })
setSaving(false)
return
}
trimmedToken = JSON.stringify({
cookies: editAvistazCookies.trim(),
userAgent: navigator.userAgent,
username: editAvistazUsername.trim(),
})
} else if (changingKey && tracker.platformType === "digitalcore") {
const trimmed = editDcCookies.trim()
const uidMatch = trimmed.match(/(?:^|;\s*)uid=([^;]+)/)
const passMatch = trimmed.match(/(?:^|;\s*)pass=([^;]+)/)
if (!uidMatch || !passMatch) {
setErrors({ apiToken: "Cookie string must contain both uid and pass values" })
setSaving(false)
return
}
trimmedToken = JSON.stringify({
uid: uidMatch[1].trim(),
pass: passMatch[1].trim(),
})
}
// Test the new API key before saving
if (changingKey && trimmedToken) {
try {
const testRes = await fetch("/api/trackers/test-connection", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
baseUrl: form.baseUrl.trim(),
apiToken: trimmedToken,
platformType: tracker.platformType,
}),
})
if (!testRes.ok) {
const testData = await testRes.json().catch(() => ({ error: "Connection failed" }))
setErrors({ apiToken: (testData as { error?: string }).error ?? "Connection failed" })
setSaving(false)
return
}
if (tracker.platformType === "avistaz") {
const testJson = await testRes.json().catch(() => ({}))
if ((testJson as Record<string, unknown>).capturedUserAgent) {
trimmedToken = JSON.stringify({
cookies: editAvistazCookies.trim(),
userAgent: (testJson as Record<string, string>).capturedUserAgent,
username: editAvistazUsername.trim(),
})
}
}
} catch {
setErrors({ apiToken: "Could not verify API key — check your connection" })
setSaving(false)
return
}
}
const payload: Record<string, unknown> = {
name: form.name.trim(),
color: form.color,
baseUrl: form.baseUrl.trim(),
qbtTag: form.qbtTag.trim(),
joinedAt: form.joinedAt || null,
useProxy: form.useProxy,
countCrossSeedUnsatisfied: form.countCrossSeedUnsatisfied,
hideUnreadBadges: form.hideUnreadBadges,
mouseholeUrl: form.mouseholeUrl.trim() || null,
}
if (changingKey && trimmedToken) {
payload.apiToken = trimmedToken
}
try {
const res = await fetch(`/api/trackers/${tracker.id}`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(payload),
})
if (!res.ok) {
const data = await res.json().catch(() => ({ error: "Save failed" }))
setErrors({ form: (data as { error?: string }).error ?? "Save failed" })
setSaving(false)
return
}
resetTransientState()
onUpdated()
onClose()
} catch {
setErrors({ form: "Network error — please try again" })
setSaving(false)
}
}
async function handleArchive() {
setSaving(true)
try {
const res = await fetch(`/api/trackers/${tracker.id}`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ isActive: !tracker.isActive }),
})
if (res.ok) {
onUpdated()
onClose()
}
} catch {
setErrors({ form: "Failed to update archive status" })
} finally {
setSaving(false)
}
}
async function handleDelete() {
setDeleting(true)
try {
const res = await fetch(`/api/trackers/${tracker.id}`, {
method: "DELETE",
})
if (res.ok) {
onClose()
router.push("/")
} else {
setErrors({ form: "Failed to delete tracker" })
setDeleting(false)
}
} catch {
setErrors({ form: "Network error during delete" })
setDeleting(false)
}
}
return (
<Sheet open={open} onClose={handleClose} title="Tracker Settings" busy={saving || deleting}>
<div className="flex flex-col p-6 pb-8 gap-5">
{/* Form */}
<form onSubmit={handleSave} className="flex flex-col gap-4">
<Input
label="Nickname"
value={form.name}
onChange={(e) => updateField("name", e.target.value)}
placeholder="Display name for this tracker"
error={errors.name}
/>
<Input
label="Base URL"
value={form.baseUrl}
onChange={(e) => updateField("baseUrl", e.target.value)}
placeholder="https://aither.cc"
error={errors.baseUrl}
/>
{/* API Key — show status or change input */}
<div className="flex flex-col gap-1">
<H2 className="uppercase tracking-wider">API Key</H2>
{changingKey && tracker.platformType === "avistaz" ? (
<div className="flex flex-col gap-2">
<Input
label="Username"
autoComplete="off"
data-1p-ignore
value={editAvistazUsername}
onChange={(e) => setEditAvistazUsername(e.target.value)}
placeholder="Your username on this tracker"
/>
<div className="flex flex-col gap-1">
<label
htmlFor="edit-avistaz-cookies"
className="text-xs uppercase tracking-wider text-secondary font-mono"
>
Browser Cookies
</label>
<textarea
id="edit-avistaz-cookies"
autoComplete="off"
data-1p-ignore
value={editAvistazCookies}
onChange={(e) => setEditAvistazCookies(e.target.value)}
placeholder="Paste Cookie header from DevTools"
rows={3}
className="w-full rounded-nm-sm bg-control-bg px-3 py-2 text-sm text-primary border border-transparent focus:border-accent focus:outline-none font-mono resize-y"
/>
</div>
<Notice message={errors.apiToken} />
<Button
variant="minimal"
size="sm"
text="Cancel"
className="self-start"
onClick={() => {
setChangingKey(false)
setEditAvistazUsername("")
setEditAvistazCookies("")
setErrors({})
}}
/>
</div>
) : changingKey && tracker.platformType === "digitalcore" ? (
<div className="flex flex-col gap-2">
<div className="flex items-center gap-1">
<label
htmlFor="edit-dc-cookies"
className="text-xs uppercase tracking-wider text-secondary font-sans font-medium"
>
Session Cookies
</label>
<InfoTip
content="Open DevTools (F12) → Network → any request → copy the Cookie header value."
size="sm"
docs={DOCS.ADDING_A_TRACKER}
/>
</div>
<textarea
id="edit-dc-cookies"
autoComplete="off"
data-1p-ignore
value={editDcCookies}
onChange={(e) => setEditDcCookies(e.target.value)}
placeholder="uid=56954; pass=abc123def456..."
rows={2}
className="w-full font-mono text-sm text-primary bg-control-bg rounded-nm-md px-4 py-3 placeholder:text-muted nm-inset focus:outline-none focus:nm-inset border-0 resize-y"
/>
<Notice message={errors.apiToken} />
<Button
variant="minimal"
size="sm"
text="Cancel"
className="self-start"
onClick={() => {
setChangingKey(false)
setEditDcCookies("")
setErrors({})
}}
/>
</div>
) : changingKey ? (
<div className="flex flex-col gap-2">
<Input
type="password"
autoComplete="off"
data-1p-ignore
value={newApiToken}
onChange={(e) => setNewApiToken(e.target.value)}
placeholder="Paste API token"
error={errors.apiToken}
/>
<Button
variant="minimal"
size="sm"
text="Cancel"
className="self-start"
onClick={() => {
setChangingKey(false)
setNewApiToken("")
setEditAvistazUsername("")
setEditAvistazCookies("")
setErrors({})
}}
/>
</div>
) : (
<MaskedSecret onChangeClick={() => setChangingKey(true)} />
)}
</div>
<div className="flex flex-col gap-1">
<Input
label="qBittorrent Tag"
value={form.qbtTag}
onChange={(e) => updateField("qbtTag", e.target.value)}
placeholder="i.e, aither"
/>
<QbtTagWarning tag={form.qbtTag} />
</div>
{tracker.platformType === "mam" && (
<div className="flex items-center gap-1">
<Input
label="Mousehole URL (optional)"
value={form.mouseholeUrl}
onChange={(e) => updateField("mouseholeUrl", e.target.value)}
placeholder="http://localhost:7001"
/>
<InfoTip
content="If you run Mousehole to manage your MAM seedbox IP, enter its URL here to see status and trigger updates from Tracker Tracker."
size="sm"
docs={{
href: "https://github.com/t-mart/mousehole",
description: "Mousehole on GitHub",
}}
/>
</div>
)}
<ColorPicker label="Color" value={form.color} onChange={(v) => updateField("color", v)} />
{!(
registryEntry?.gazelleEnrich ||
tracker.platformType === "ggn" ||
tracker.platformType === "avistaz" ||
tracker.platformType === "digitalcore"
) && (
<div>
<label
htmlFor="settings-joined-at"
className="text-xs font-sans font-medium text-secondary uppercase tracking-wider mb-1 block"
>
Join Date
</label>
<input
id="settings-joined-at"
type="date"
value={form.joinedAt}
max={localDateStr()}
onChange={(e) => updateField("joinedAt", e.target.value)}
className={clsx(
"w-full font-mono text-sm text-primary cursor-pointer border-0",
"bg-control-bg px-4 py-3 nm-inset focus:outline-none rounded-nm-md",
!form.joinedAt && "text-muted"
)}
style={{ colorScheme: "dark" }}
/>
</div>
)}
<Toggle
label="Use proxy"
checked={form.useProxy}
onChange={(v) => updateField("useProxy", v)}
disabled={!proxyAvailable || proxyAvailable === null}
description={
proxyAvailable
? "Route API requests for this tracker through the global proxy configured in Settings."
: "No proxy configured. Enable a proxy in Settings first."
}
/>
<Toggle
label="Count cross-seed towards unsatisfieds"
checked={form.countCrossSeedUnsatisfied}
onChange={(v) => updateField("countCrossSeedUnsatisfied", v)}
description="Include cross-seeded torrents when calculating unsatisfied download requirements."
/>
{(tracker.platformType === "mam" || tracker.platformType === "gazelle") && (
<Toggle
checked={form.hideUnreadBadges}
onChange={(v) => updateField("hideUnreadBadges", v)}
label="Hide unread badges"
description="Don't show inbox/notification counts on this tracker's detail page"
/>
)}
<Notice message={errors.form} />
{/* Save / Cancel */}
<div className="flex gap-3 pt-1 justify-end">
<Button variant="ghost" onClick={handleClose} text="Cancel" />
<Button type="submit" disabled={saving} text={saving ? "Saving..." : "Save Changes"} />
</div>
</form>
{/* Danger zone */}
<div className="border-t border-border pt-5 mt-1 flex flex-col gap-3">
<span className="text-xs font-sans font-medium text-danger uppercase tracking-wider">
Danger Zone
</span>
<div className="flex items-center gap-3">
<Button
variant="secondary"
size="sm"
onClick={handleArchive}
disabled={saving}
text={tracker.isActive ? "Archive" : "Reactivate"}
/>
<ConfirmRemove
label="Delete"
confirmLabel="Confirm Delete"
busyLabel="Deleting..."
busy={deleting}
onConfirm={handleDelete}
/>
</div>
</div>
</div>
</Sheet>
)
}
export { TrackerSettingsSheet }