Files
usenet-indexer/lib/headers/subject.ts
T
Daan MeijerandClaude Opus 5.5 d773c91ad0
Test and deploy / test (push) Successful in 29s
Test and deploy / deploy (push) Skipped
Rebuild: phase 1 modules from the current app, ordered by pipeline stage
lib/nntp (XOVER client, Xref, GROUP), lib/headers (subjects, file keys,
segments from overview lines; the yEnc path stays behind for phase 2),
lib/release (identity, random names, now in lib), lib/files (aggregator,
volume names), lib/rules (posting tools, owner by priority, release
verdicts), lib/chunks (release chunk codec). Their unit tests came along;
new ones for codec, rules and volumes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 00:08:44 +02:00

60 lines
2.0 KiB
TypeScript

export interface ParsedSubject {
/** Filename from the quoted part of the subject. */
name: string
/** Segment number `k` from `(k/N)`. */
segment: number
/** Segment count `N` from `(k/N)`. */
totalSegments: number
/** File counter `[i/M]`, when present. */
fileIndex?: number
fileTotal?: number
/**
* The subject with the segment counter removed. Identical for every segment
* of one uploaded file, so it is part of the file identity (see fileKey).
*/
base: string
}
const SEGMENT_COUNTER = /\((\d+)\/(\d+)\)/g
const FILE_COUNTER = /\[(\d+)\/(\d+)\]/
/**
* Parses a binary post subject such as
* `[07/45] - "Some.Release.part06.rar" yEnc (12/137) 51315352`.
*
* Returns null for subjects without a quoted filename and segment counter
* (obfuscated posts), which need their yEnc header read from the body instead.
*/
export function parseSubject(subject: string): ParsedSubject | null {
const nameEnd = subject.lastIndexOf('"')
const nameStart = nameEnd > 0 ? subject.lastIndexOf('"', nameEnd - 1) : -1
if (nameStart === -1) return null
const name = subject.slice(nameStart + 1, nameEnd)
if (!name) return null
// The segment counter is the last "(k/N)" after the filename; a file size may follow it.
let counter: RegExpExecArray | undefined
for (const match of subject.matchAll(SEGMENT_COUNTER)) {
if (match.index > nameEnd) counter = match
}
if (!counter) return null
const segment = Number.parseInt(counter[1], 10)
const totalSegments = Number.parseInt(counter[2], 10)
if (totalSegments < 1 || segment < 1 || segment > totalSegments) return null
const base = (subject.slice(0, counter.index) + subject.slice(counter.index + counter[0].length))
.replace(/\s+/g, ' ')
.trim()
const fileCounter = FILE_COUNTER.exec(subject.slice(0, nameStart))
return {
name,
segment,
totalSegments,
fileIndex: fileCounter ? Number.parseInt(fileCounter[1], 10) : undefined,
fileTotal: fileCounter ? Number.parseInt(fileCounter[2], 10) : undefined,
base,
}
}