forked from jordanlambrecht/tracker-tracker
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseTrackerTorrents.ts
More file actions
363 lines (327 loc) · 11.8 KB
/
Copy pathuseTrackerTorrents.ts
File metadata and controls
363 lines (327 loc) · 11.8 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
// src/hooks/useTrackerTorrents.ts
"use client"
import { useQuery } from "@tanstack/react-query"
import { useMemo } from "react"
import type { TrackerRules } from "@/data/tracker-registry"
import { usePollingIntervals } from "@/hooks/usePollingIntervals"
import type { TorrentRaw } from "@/lib/fleet"
import {
type AggregatedTorrentsResponse,
type CategoryStats,
LEECHING_STATES,
parseTorrentTags,
SEEDING_STATES,
} from "@/lib/torrent-utils"
import type { QbitmanageTagConfig, TagGroup } from "@/types/api"
// ---------------------------------------------------------------------------
// Type defs
// ---------------------------------------------------------------------------
interface UseTrackerTorrentsParams {
trackerId: number
qbtTag: string | null
rules?: TrackerRules
tagGroups?: TagGroup[]
trackerSeedingCount?: number | null
qbitmanageConfig?: {
enabled: boolean
tags: QbitmanageTagConfig
} | null
/** When false, disables the 5s active torrent poll (i.e. tab not visible). */
isActive?: boolean
}
interface TagGroupBreakdown {
group: TagGroup
memberCounts: { label: string; count: number; color: string | null }[]
unmatchedCount: number
}
interface QbitmanageBreakdownItem {
label: string
count: number
color: null
}
interface TrackerTorrentsData {
torrents: TorrentRaw[]
crossSeedTags: string[]
loading: boolean
torrentError: string | null
noClients: boolean
clientCount: number
stale: boolean
cachedAt: string | null
seedingTorrents: TorrentRaw[]
leechingTorrents: TorrentRaw[]
activelySeedingTorrents: TorrentRaw[]
activelyDownloading: TorrentRaw[]
totalUpSpeed: number
totalSize: number
crossSeeded: TorrentRaw[]
requiredSeedSeconds: number | null
unsatisfiedTorrents: TorrentRaw[]
unsatisfiedSorted: TorrentRaw[]
unsatisfiedCount: number | null
hnrRiskCount: number | null
deadCount: number | null
categoryStats: CategoryStats[]
topBySeeding: TorrentRaw[]
elderTorrents: TorrentRaw[]
tagGroupBreakdowns: TagGroupBreakdown[]
qbitmanageBreakdown: QbitmanageBreakdownItem[]
}
// ---------------------------------------------------------------------------
// SessionStorage cache (Phase 0 — instant restore on page refresh)
// ---------------------------------------------------------------------------
function loadSessionCache(trackerId: number): AggregatedTorrentsResponse | undefined {
try {
const raw = sessionStorage.getItem(`torrent-cache-${trackerId}`)
if (!raw) return undefined
return JSON.parse(raw) as AggregatedTorrentsResponse
} catch {
return undefined
}
}
function saveSessionCache(trackerId: number, data: AggregatedTorrentsResponse) {
try {
sessionStorage.setItem(`torrent-cache-${trackerId}`, JSON.stringify(data))
} catch {
// sessionStorage full or unavailable
}
}
// ---------------------------------------------------------------------------
// Hook
// ---------------------------------------------------------------------------
function useTrackerTorrents({
trackerId,
qbtTag,
rules,
tagGroups,
trackerSeedingCount,
qbitmanageConfig,
isActive = true,
}: UseTrackerTorrentsParams): TrackerTorrentsData {
const enabled = !!qbtTag
const intervals = usePollingIntervals()
// forces an immediate background refetch from the DB cache endpoint
const cachedQuery = useQuery({
queryKey: ["tracker-torrents-cached", trackerId] as const,
queryFn: async ({ signal }) => {
const res = await fetch(`/api/trackers/${trackerId}/torrents/cached`, { signal })
if (!res.ok) return null
const data = (await res.json()) as AggregatedTorrentsResponse
if (data.torrents.length > 0) {
saveSessionCache(trackerId, data)
return data
}
return null
},
enabled,
staleTime: intervals.trackerRefetchMs,
initialData: loadSessionCache(trackerId) ?? undefined,
initialDataUpdatedAt: 0,
})
// Phase 2: Live qBT torrent data (slow — overrides cached when ready)
const liveQuery = useQuery({
queryKey: ["tracker-torrents", trackerId] as const,
queryFn: async ({ signal }) => {
const res = await fetch(`/api/trackers/${trackerId}/torrents`, { signal })
if (!res.ok) throw new Error(`Torrent fetch failed: ${res.status}`)
const data = (await res.json()) as AggregatedTorrentsResponse
saveSessionCache(trackerId, data)
return data
},
enabled,
staleTime: intervals.trackerRefetchMs,
})
// Active torrent poll. Only starts after live data has resolved
const activeQuery = useQuery({
queryKey: ["tracker-torrents-active", trackerId] as const,
queryFn: async ({ signal }) => {
const res = await fetch(`/api/trackers/${trackerId}/torrents?active=true`, { signal })
if (!res.ok) return null
return res.json() as Promise<AggregatedTorrentsResponse>
},
enabled: enabled && liveQuery.isSuccess,
refetchInterval: isActive ? 5_000 : false,
})
// Resolve the best available data source: live > cached > sessionStorage placeholder
const baseData = liveQuery.data ?? cachedQuery.data ?? null
const stale = !liveQuery.data && !!cachedQuery.data
const cachedAt = stale ? (cachedQuery.data?.cachedAt ?? null) : null
const loading = enabled && !baseData && (cachedQuery.isLoading || liveQuery.isLoading)
// Merge active speeds into the base torrent list
const torrents = useMemo(() => {
if (!baseData) return []
const base: TorrentRaw[] = baseData.torrents
if (!activeQuery.data) return base
const activeMap = new Map(activeQuery.data.torrents.map((t) => [t.hash, t] as const))
return base.map((t) => {
const active = activeMap.get(t.hash)
if (active) {
return {
...t,
uploadSpeed: active.uploadSpeed,
downloadSpeed: active.downloadSpeed,
state: active.state,
progress: active.progress,
}
}
if (
t.uploadSpeed > 0 ||
t.downloadSpeed > 0 ||
t.state === "uploading" ||
t.state === "downloading"
) {
return {
...t,
uploadSpeed: 0,
downloadSpeed: 0,
state: t.state === "downloading" ? ("stalledDL" as const) : ("stalledUP" as const),
}
}
return t
})
}, [baseData, activeQuery.data])
const crossSeedTags = useMemo(() => baseData?.crossSeedTags ?? [], [baseData?.crossSeedTags])
const clientCount = baseData?.clientCount ?? 0
const noClients = clientCount === 0
const torrentError = useMemo(() => {
if (liveQuery.data?.clientErrors?.length) {
return `Partial data — some clients failed: ${liveQuery.data.clientErrors.join("; ")}`
}
if (liveQuery.error && !cachedQuery.data) {
return "Client offline — no cached data available"
}
return null
}, [liveQuery.data, liveQuery.error, cachedQuery.data])
const derived = useMemo(() => {
const seedingTorrents = torrents.filter((t) => SEEDING_STATES.has(t.state))
const leechingTorrents = torrents.filter((t) => LEECHING_STATES.has(t.state))
const activelySeedingTorrents = torrents.filter((t) => t.state === "uploading")
const activelyDownloading = torrents.filter(
(t) => LEECHING_STATES.has(t.state) && t.downloadSpeed > 0
)
const totalUpSpeed = torrents.reduce((sum, t) => sum + t.uploadSpeed, 0)
const totalSize = torrents.reduce((sum, t) => sum + t.size, 0)
const csTagSet = new Set(crossSeedTags.map((t) => t.toLowerCase()))
const crossSeeded = torrents.filter((t) => {
const tags = t.tags
.split(",")
.map((s) => s.trim().toLowerCase())
.filter(Boolean)
return tags.some((tag) => csTagSet.has(tag))
})
const requiredSeedSeconds =
rules?.seedTimeHours != null && rules.seedTimeHours > 0 ? rules.seedTimeHours * 3600 : null
const unsatisfiedTorrents = requiredSeedSeconds
? torrents.filter((t) => t.seedingTime < requiredSeedSeconds)
: []
const unsatisfiedCount = requiredSeedSeconds ? unsatisfiedTorrents.length : null
const hnrRiskCount = requiredSeedSeconds
? unsatisfiedTorrents.filter(
(t) => !SEEDING_STATES.has(t.state) && !LEECHING_STATES.has(t.state)
).length
: null
const deadCount =
trackerSeedingCount != null ? Math.max(0, seedingTorrents.length - trackerSeedingCount) : null
const categoryMap = new Map<string, TorrentRaw[]>()
for (const t of torrents) {
const cat = t.category || "Uncategorized"
const arr = categoryMap.get(cat) ?? []
arr.push(t)
categoryMap.set(cat, arr)
}
const categoryStats: CategoryStats[] = [...categoryMap.entries()]
.map(([name, items]) => ({
name,
count: items.length,
totalSize: items.reduce((s, t) => s + t.size, 0),
avgRatio: items.reduce((s, t) => s + t.ratio, 0) / items.length,
avgSeedTime: items.reduce((s, t) => s + t.seedingTime, 0) / items.length,
avgSwarmSeeds: items.reduce((s, t) => s + t.swarmSeeders, 0) / items.length,
}))
.sort((a, b) => b.count - a.count)
const topBySeeding = [...seedingTorrents]
.sort((a, b) => b.seedingTime - a.seedingTime)
.slice(0, 10)
const elderTorrents = [...torrents]
.filter((t) => t.addedAt > 0)
.sort((a, b) => a.addedAt - b.addedAt)
.slice(0, 10)
const unsatisfiedSorted = requiredSeedSeconds
? [...unsatisfiedTorrents].sort((a, b) => b.seedingTime - a.seedingTime)
: []
const torrentTagSets = torrents.map((t) => new Set(parseTorrentTags(t.tags, false)))
const tagGroupBreakdowns: TagGroupBreakdown[] = (tagGroups ?? [])
.map((group) => {
const allGroupTagSet = new Set(group.members.map((m) => m.tag))
const memberCounts = group.members
.map((member) => {
const count = torrentTagSets.filter((tags) => tags.has(member.tag)).length
return { label: member.label, count, color: member.color }
})
.filter((m) => m.count > 0)
const unmatchedCount = torrentTagSets.filter((tags) => {
for (const tag of tags) {
if (allGroupTagSet.has(tag)) return false
}
return true
}).length
return { group, memberCounts, unmatchedCount }
})
.filter((g) => g.memberCounts.length > 0 || (g.group.countUnmatched && g.unmatchedCount > 0))
const qbitmanageBreakdown: QbitmanageBreakdownItem[] = qbitmanageConfig?.enabled
? Object.entries(qbitmanageConfig.tags)
.filter(([, entry]) => entry.enabled)
.map(([key, entry]) => {
const count = torrentTagSets.filter((tags) => tags.has(entry.tag)).length
const labelMap: Record<string, string> = {
issue: "Issue",
minTimeNotReached: "Min Time Not Reached",
noHardlinks: "No Hardlinks",
minSeedsNotMet: "Min Seeds Not Met",
lastActiveLimitNotReached: "Last Active Limit",
lastActiveNotReached: "Last Active Not Reached",
}
return { label: labelMap[key] ?? key, count, color: null }
})
.filter((m) => m.count > 0)
: []
return {
seedingTorrents,
leechingTorrents,
activelySeedingTorrents,
activelyDownloading,
totalUpSpeed,
totalSize,
crossSeeded,
requiredSeedSeconds,
unsatisfiedTorrents,
unsatisfiedSorted,
unsatisfiedCount,
hnrRiskCount,
deadCount,
categoryStats,
topBySeeding,
elderTorrents,
tagGroupBreakdowns,
qbitmanageBreakdown,
}
}, [torrents, crossSeedTags, rules, tagGroups, trackerSeedingCount, qbitmanageConfig])
return {
torrents,
crossSeedTags,
loading,
torrentError,
noClients,
clientCount,
stale,
cachedAt,
...derived,
}
}
export type {
QbitmanageBreakdownItem,
TagGroupBreakdown,
TrackerTorrentsData,
UseTrackerTorrentsParams,
}
export { useTrackerTorrents }