60 lines
2.0 KiB
TypeScript
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,
|
|
}
|
|
}
|