Usenet streaming with a WebDAV server and a SABnzbd-compatible API
C#
Added article-headers to YencHeaderStream.
nzbdav-dev8482b041076a
diff --git a/backend/Clients/Usenet/CachingNntpClient.cs b/backend/Clients/Usenet/CachingNntpClient.csindex 60108e89..36e45c7c 100644--- a/backend/Clients/Usenet/CachingNntpClient.cs+++ b/backend/Clients/Usenet/CachingNntpClient.cs@@ -15,10 +15,15 @@ public class CachingNntpClient(INntpClient client, MemoryCache cache) : WrappingSlidingExpiration = TimeSpan.FromHours(3)};- public override async Task<YencHeaderStream> GetSegmentStreamAsync(string segmentId, CancellationToken ct)+ public override async Task<YencHeaderStream> GetSegmentStreamAsync+ (+ string segmentId,+ bool includeHeaders,+ CancellationToken ct+ ){var cacheKey = segmentId;- var stream = await _client.GetSegmentStreamAsync(segmentId, ct);+ var stream = await _client.GetSegmentStreamAsync(segmentId, includeHeaders, ct);cache.Set(cacheKey, stream.Header, _cacheOptions);return stream;}diff --git a/backend/Clients/Usenet/INntpClient.cs b/backend/Clients/Usenet/INntpClient.csindex 583a39d0..d7b7ff17 100644--- a/backend/Clients/Usenet/INntpClient.cs+++ b/backend/Clients/Usenet/INntpClient.cs@@ -10,7 +10,7 @@ public interface INntpClient: IDisposableTask<bool> ConnectAsync(string host, int port, bool useSsl, CancellationToken cancellationToken);Task<bool> AuthenticateAsync(string user, string pass, CancellationToken cancellationToken);Task<NntpStatResponse> StatAsync(string segmentId, CancellationToken cancellationToken);- Task<YencHeaderStream> GetSegmentStreamAsync(string segmentId, CancellationToken cancellationToken);+ Task<YencHeaderStream> GetSegmentStreamAsync(string segmentId, bool includeHeaders, CancellationToken ct);Task<YencHeader> GetSegmentYencHeaderAsync(string segmentId, CancellationToken cancellationToken);Task<long> GetFileSizeAsync(NzbFile file, CancellationToken cancellationToken);Task<NntpDateResponse> DateAsync(CancellationToken cancellationToken);diff --git a/backend/Clients/Usenet/Models/UsenetArticle.cs b/backend/Clients/Usenet/Models/UsenetArticle.csnew file mode 100644index 00000000..9246484f--- /dev/null+++ b/backend/Clients/Usenet/Models/UsenetArticle.cs@@ -0,0 +1,7 @@+namespace NzbWebDAV.Clients.Usenet.Models;++public class UsenetArticle+{+ public UsenetArticleHeaders? Headers { get; init; }+ public required IEnumerable<string> Body { get; init; }+}\ No newline at end of filediff --git a/backend/Clients/Usenet/Models/UsenetArticleHeaders.cs b/backend/Clients/Usenet/Models/UsenetArticleHeaders.csnew file mode 100644index 00000000..8fa29e41--- /dev/null+++ b/backend/Clients/Usenet/Models/UsenetArticleHeaders.cs@@ -0,0 +1,134 @@+using System.Collections.Immutable;+using System.Globalization;+using System.Text.RegularExpressions;++namespace NzbWebDAV.Clients.Usenet.Models;++public class UsenetArticleHeaders+{+ public DateTimeOffset Date { get; init; }+ public ImmutableHashSet<string> NewsGroups { get; init; }+ public ImmutableHashSet<string> Organization { get; init; }+ public ImmutableHashSet<string> Subject { get; init; }+ public ImmutableHashSet<string> MessageId { get; init; }+ public ImmutableHashSet<string> From { get; init; }++ public UsenetArticleHeaders(ImmutableDictionary<string, ImmutableHashSet<string>> headers)+ {+ Date = GetDate(headers.GetValueOrDefault("Date", []));+ NewsGroups = headers.GetValueOrDefault("Newsgroups", []);+ Organization = headers.GetValueOrDefault("Organization", []);+ Subject = headers.GetValueOrDefault("Subject", []);+ MessageId = headers.GetValueOrDefault("Message-Id", []);+ From = headers.GetValueOrDefault("From", []);+ }++ private static DateTimeOffset GetDate(ImmutableHashSet<string> date)+ {+ return !date.IsEmpty && TryParseDateUtc(date.First(), out var parsedDate)+ ? parsedDate+ : DateTimeOffset.UtcNow;+ }++ // Comprehensive zone map (RFC 822 + common real-world + military)+ private static readonly Dictionary<string, string> TimeZoneOffsets = new(StringComparer.OrdinalIgnoreCase)+ {+ // RFC 822+ ["UT"] = "+0000", ["UTC"] = "+0000", ["GMT"] = "+0000",+ ["EST"] = "-0500", ["EDT"] = "-0400",+ ["CST"] = "-0600", ["CDT"] = "-0500",+ ["MST"] = "-0700", ["MDT"] = "-0600",+ ["PST"] = "-0800", ["PDT"] = "-0700",++ // Common European+ ["BST"] = "+0100", ["CET"] = "+0100", ["CEST"] = "+0200",+ ["EET"] = "+0200", ["EEST"] = "+0300",+ ["WET"] = "+0000", ["WEST"] = "+0100",++ // Asia–Pacific (often seen in NNTP)+ ["IST"] = "+0530", ["JST"] = "+0900", ["KST"] = "+0900",+ ["AEST"] = "+1000", ["AEDT"] = "+1100",+ ["ACST"] = "+0930", ["ACDT"] = "+1030",+ ["AWST"] = "+0800",+ ["NZST"] = "+1200", ["NZDT"] = "+1300",++ // Military letters (A–Z except J)+ ["A"] = "+0100", ["B"] = "+0200", ["C"] = "+0300", ["D"] = "+0400",+ ["E"] = "+0500", ["F"] = "+0600", ["G"] = "+0700", ["H"] = "+0800",+ ["I"] = "+0900", ["K"] = "+1000", ["L"] = "+1100", ["M"] = "+1200",+ ["N"] = "-0100", ["O"] = "-0200", ["P"] = "-0300", ["Q"] = "-0400",+ ["R"] = "-0500", ["S"] = "-0600", ["T"] = "-0700", ["U"] = "-0800",+ ["V"] = "-0900", ["W"] = "-1000", ["X"] = "-1100", ["Y"] = "-1200",+ ["Z"] = "+0000"+ };++ private static readonly string[] DateFormats =+ {+ // RFC 5322-style (preferred)+ "ddd, dd MMM yyyy HH:mm:ss zzz",+ "ddd, dd MMM yyyy HH:mm zzz",+ // Legacy 2-digit year+ "ddd, dd MMM yy HH:mm:ss zzz",+ "ddd, dd MMM yy HH:mm zzz",+ // Missing comma variations+ "dd MMM yyyy HH:mm:ss zzz",+ "dd MMM yy HH:mm:ss zzz",+ // Occasionally missing seconds+ "ddd, dd MMM yyyy HH:mm zzz",+ "ddd, dd MMM yy HH:mm zzz"+ };++ private static bool TryParseDateUtc(string input, out DateTimeOffset dateTimeOffset)+ {+ dateTimeOffset = default;+ if (string.IsNullOrWhiteSpace(input))+ return false;++ // Remove comments like "(UTC)"+ string cleaned = Regex.Replace(input, @"\s*\(.*?\)\s*", " ");++ // Collapse multiple spaces+ cleaned = Regex.Replace(cleaned.Trim(), @"\s+", " ");++ // Normalize known named time zones+ foreach (var kvp in TimeZoneOffsets)+ {+ cleaned = Regex.Replace(+ cleaned,+ $@"\b{Regex.Escape(kvp.Key)}\b",+ kvp.Value,+ RegexOptions.IgnoreCase);+ }++ // Ensure we have something like +0000 at the end if possible+ cleaned = Regex.Replace(cleaned, @"\s([0-9]{4})$", " +$1");++ // Try each explicit format+ foreach (var fmt in DateFormats)+ {+ if (DateTimeOffset.TryParseExact(+ cleaned,+ fmt,+ CultureInfo.InvariantCulture,+ DateTimeStyles.AllowWhiteSpaces | DateTimeStyles.AssumeUniversal,+ out dateTimeOffset))+ {+ dateTimeOffset = dateTimeOffset.ToUniversalTime();+ return true;+ }+ }++ // Fallback flexible parse+ if (DateTimeOffset.TryParse(+ cleaned,+ CultureInfo.InvariantCulture,+ DateTimeStyles.AllowWhiteSpaces | DateTimeStyles.AssumeUniversal,+ out dateTimeOffset))+ {+ dateTimeOffset = dateTimeOffset.ToUniversalTime();+ return true;+ }++ return false;+ }+}\ No newline at end of filediff --git a/backend/Clients/Usenet/MultiConnectionNntpClient.cs b/backend/Clients/Usenet/MultiConnectionNntpClient.csindex 0dc02f86..6e814ac8 100644--- a/backend/Clients/Usenet/MultiConnectionNntpClient.cs+++ b/backend/Clients/Usenet/MultiConnectionNntpClient.cs@@ -31,9 +31,9 @@ public class MultiConnectionNntpClient(ConnectionPool<INntpClient> connectionPooreturn RunWithConnection(connection => connection.DateAsync(cancellationToken), cancellationToken);}- public Task<YencHeaderStream> GetSegmentStreamAsync(string segmentId, CancellationToken cancellationToken)+ public Task<YencHeaderStream> GetSegmentStreamAsync(string segmentId, bool includeHeaders, CancellationToken cancellationToken){- return RunWithConnection(connection => connection.GetSegmentStreamAsync(segmentId, cancellationToken), cancellationToken);+ return RunWithConnection(connection => connection.GetSegmentStreamAsync(segmentId, includeHeaders, cancellationToken), cancellationToken);}public Task<YencHeader> GetSegmentYencHeaderAsync(string segmentId, CancellationToken cancellationToken)diff --git a/backend/Clients/Usenet/ThreadSafeNntpClient.cs b/backend/Clients/Usenet/ThreadSafeNntpClient.csindex 0c6ed3bf..0dd54cb5 100644--- a/backend/Clients/Usenet/ThreadSafeNntpClient.cs+++ b/backend/Clients/Usenet/ThreadSafeNntpClient.cs@@ -1,4 +1,5 @@-using NzbWebDAV.Exceptions;+using NzbWebDAV.Clients.Usenet.Models;+using NzbWebDAV.Exceptions;using NzbWebDAV.Extensions;using NzbWebDAV.Streams;using Usenet.Nntp;@@ -41,7 +42,12 @@ public class ThreadSafeNntpClient : INntpClientreturn Synchronized(() => _client.Date(), cancellationToken);}- public async Task<YencHeaderStream> GetSegmentStreamAsync(string segmentId, CancellationToken cancellationToken)+ public async Task<YencHeaderStream> GetSegmentStreamAsync+ (+ string segmentId,+ bool includeHeaders,+ CancellationToken cancellationToken+ ){await _semaphore.WaitAsync(cancellationToken);return await Task.Run(() =>@@ -49,10 +55,11 @@ public class ThreadSafeNntpClient : INntpClienttry{cancellationToken.ThrowIfCancellationRequested();- var articleBody = GetArticleBody(segmentId);- var stream = YencStreamDecoder.Decode(articleBody);+ var article = GetArticle(segmentId, includeHeaders);+ var stream = YencStreamDecoder.Decode(article.Body);return new YencHeaderStream(stream.Header,+ article.Headers,new BufferToEndStream(stream.OnDispose(OnDispose)));@@ -70,7 +77,7 @@ public class ThreadSafeNntpClient : INntpClientpublic async Task<YencHeader> GetSegmentYencHeaderAsync(string segmentId, CancellationToken cancellationToken){- await using var stream = await GetSegmentStreamAsync(new NntpMessageId(segmentId), cancellationToken);+ await using var stream = await GetSegmentStreamAsync(new NntpMessageId(segmentId), false, cancellationToken);return stream.Header;}@@ -105,10 +112,26 @@ public class ThreadSafeNntpClient : INntpClient}}- private IEnumerable<string> GetArticleBody(string segmentId)+ private UsenetArticle GetArticle(string segmentId, bool includeHeaders){- return _client.Body(new NntpMessageId(segmentId))?.Article?.Body- ?? throw new UsenetArticleNotFoundException(segmentId);+ if (includeHeaders)+ {+ var articleResponse = _client.Article(new NntpMessageId(segmentId));+ if (articleResponse?.Article?.Body == null) throw new UsenetArticleNotFoundException(segmentId);+ return new UsenetArticle()+ {+ Headers = new UsenetArticleHeaders(articleResponse.Article.Headers),+ Body = articleResponse.Article.Body+ };+ }++ var bodyResponse = _client.Body(new NntpMessageId(segmentId));+ if (bodyResponse?.Article?.Body == null) throw new UsenetArticleNotFoundException(segmentId);+ return new UsenetArticle()+ {+ Headers = null,+ Body = bodyResponse.Article.Body+ };}public void Dispose()diff --git a/backend/Clients/Usenet/UsenetStreamingClient.cs b/backend/Clients/Usenet/UsenetStreamingClient.csindex d0a3e5d1..fc21f3ea 100644--- a/backend/Clients/Usenet/UsenetStreamingClient.cs+++ b/backend/Clients/Usenet/UsenetStreamingClient.cs@@ -102,9 +102,9 @@ public class UsenetStreamingClientreturn new NzbFileStream(segmentIds, fileSize, _client, concurrentConnections);}- public Task<YencHeaderStream> GetSegmentStreamAsync(string segmentId, CancellationToken cancellationToken)+ public Task<YencHeaderStream> GetSegmentStreamAsync(string segmentId, bool includeHeaders, CancellationToken ct){- return _client.GetSegmentStreamAsync(segmentId, cancellationToken);+ return _client.GetSegmentStreamAsync(segmentId, includeHeaders, ct);}public Task<long> GetFileSizeAsync(NzbFile file, CancellationToken cancellationToken)diff --git a/backend/Clients/Usenet/WrappingNntpClient.cs b/backend/Clients/Usenet/WrappingNntpClient.csindex 2d5180f6..84c2dd04 100644--- a/backend/Clients/Usenet/WrappingNntpClient.cs+++ b/backend/Clients/Usenet/WrappingNntpClient.cs@@ -27,9 +27,14 @@ public abstract class WrappingNntpClient(INntpClient client) : INntpClientreturn client.DateAsync(cancellationToken);}- public virtual Task<YencHeaderStream> GetSegmentStreamAsync(string segmentId, CancellationToken cancellationToken)- {- return client.GetSegmentStreamAsync(segmentId, cancellationToken);+ public virtual Task<YencHeaderStream> GetSegmentStreamAsync+ (+ string segmentId,+ bool includeHeaders,+ CancellationToken cancellationToken+ )+ {+ return client.GetSegmentStreamAsync(segmentId, includeHeaders, cancellationToken);}public virtual Task<YencHeader> GetSegmentYencHeaderAsync(string segmentId, CancellationToken cancellationToken)diff --git a/backend/Queue/DeobfuscationSteps/1.FetchFirstSegment/FetchFirstSegmentsStep.cs b/backend/Queue/DeobfuscationSteps/1.FetchFirstSegment/FetchFirstSegmentsStep.csindex dbfc1bb4..dc0091e3 100644--- a/backend/Queue/DeobfuscationSteps/1.FetchFirstSegment/FetchFirstSegmentsStep.cs+++ b/backend/Queue/DeobfuscationSteps/1.FetchFirstSegment/FetchFirstSegmentsStep.cs@@ -38,7 +38,7 @@ public static class FetchFirstSegmentsStep{// get the first article streamvar firstSegment = nzbFile.Segments[0].MessageId.Value;- await using var stream = await client.GetSegmentStreamAsync(firstSegment, cancellationToken);+ await using var stream = await client.GetSegmentStreamAsync(firstSegment, true, cancellationToken);// read up to the first 16KB from the streamvar totalRead = 0;diff --git a/backend/Streams/NzbFileStream.cs b/backend/Streams/NzbFileStream.csindex 9b8c5fa3..046cba80 100644--- a/backend/Streams/NzbFileStream.cs+++ b/backend/Streams/NzbFileStream.cs@@ -96,7 +96,7 @@ public class NzbFileStream({return new CombinedStream(fileSegmentIds[firstSegmentIndex..]- .Select(async x => (Stream)await client.GetSegmentStreamAsync(x, ct))+ .Select(async x => (Stream)await client.GetSegmentStreamAsync(x, false, ct)).WithConcurrency(concurrentConnections));}diff --git a/backend/Streams/YencHeaderStream.cs b/backend/Streams/YencHeaderStream.csindex 49d2222f..f2012f12 100644--- a/backend/Streams/YencHeaderStream.cs+++ b/backend/Streams/YencHeaderStream.cs@@ -1,10 +1,12 @@-using Usenet.Yenc;+using NzbWebDAV.Clients.Usenet.Models;+using Usenet.Yenc;namespace NzbWebDAV.Streams;-public class YencHeaderStream(YencHeader header, Stream stream) : Stream+public class YencHeaderStream(YencHeader header, UsenetArticleHeaders? articleHeaders, Stream stream) : Stream{public YencHeader Header => header;+ public UsenetArticleHeaders? ArticleHeaders => articleHeaders;private bool _disposed;public override void Flush() => stream.Flush();