Skip to content

Usenet streaming with a WebDAV server and a SABnzbd-compatible API

C#

Added better progress tracking for 7z nzbs.

nzbdav-dev20b69b0ace12
diff --git a/backend/Extensions/ProgressExtensions.cs b/backend/Extensions/ProgressExtensions.cs
index 54bd984a..3d6e1e02 100644
--- a/backend/Extensions/ProgressExtensions.cs
+++ b/backend/Extensions/ProgressExtensions.cs
@@ -2,18 +2,51 @@
public static class ProgressExtensions
{
- public static Progress<int>? ToPercentage(this IProgress<int>? progress, int total)
+ public static Progress<int> ToPercentage(this IProgress<int>? progress, int total)
{
return new Progress<int>(x => progress?.Report(x * 100 / total));
}
- public static Progress<int>? Scale(this IProgress<int>? progress, int numerator, int denominator)
+ public static Progress<int> Scale(this IProgress<int>? progress, int numerator, int denominator)
{
return new Progress<int>(x => progress?.Report(x * numerator / denominator));
}
- public static Progress<int>? Offset(this IProgress<int>? progress, int offset)
+ public static Progress<int> Offset(this IProgress<int>? progress, int offset)
{
return new Progress<int>(x => progress?.Report(x + offset));
}
+
+ public static MultiProgress ToMultiProgress(this IProgress<int>? progress, int total)
+ {
+ return new MultiProgress(progress, total);
+ }
+
+ public class MultiProgress(IProgress<int>? progress, int total)
+ {
+ private int _numerator;
+ private readonly int _denominator = 100 * total;
+ private readonly Lock _lock = new();
+
+ public Progress<int> SubProgress
+ {
+ get
+ {
+ var previous = 0;
+ return new Progress<int>(x =>
+ {
+ int? current;
+ lock (_lock)
+ {
+ _numerator -= previous;
+ _numerator += x;
+ current = _numerator;
+ }
+
+ previous = x;
+ progress?.Report(current!.Value * 100 / _denominator);
+ });
+ }
+ }
+ }
}
\ No newline at end of file
diff --git a/backend/Queue/DeobfuscationSteps/3.GetFileInfos/GetFileInfosStep.cs b/backend/Queue/DeobfuscationSteps/3.GetFileInfos/GetFileInfosStep.cs
index 90f099da..2a7db55d 100644
--- a/backend/Queue/DeobfuscationSteps/3.GetFileInfos/GetFileInfosStep.cs
+++ b/backend/Queue/DeobfuscationSteps/3.GetFileInfos/GetFileInfosStep.cs
@@ -95,7 +95,7 @@ public static class GetFileInfosStep
return range.Contains(fileSize);
}
- public class FileInfo
+ public record FileInfo
{
public required NzbFile NzbFile { get; init; }
public required string FileName { get; init; }
diff --git a/backend/Queue/FileProcessors/BaseProcessor.cs b/backend/Queue/FileProcessors/BaseProcessor.cs
index d7f4634b..2e0a0510 100644
--- a/backend/Queue/FileProcessors/BaseProcessor.cs
+++ b/backend/Queue/FileProcessors/BaseProcessor.cs
@@ -1,7 +1,27 @@
namespace NzbWebDAV.Queue.FileProcessors;
+/// <summary>
+/// The base processor for all child processors.
+/// Children must override either of the two `ProcessAsync` method overloads, but not both.
+/// </summary>
public abstract class BaseProcessor
{
- public abstract Task<Result?> ProcessAsync();
- public class Result { }
+ public class Result;
+
+ public virtual Task<Result?> ProcessAsync()
+ {
+ return Task.FromResult<Result?>(null);
+ }
+
+ public virtual async Task<Result?> ProcessAsync(IProgress<int> progress)
+ {
+ try
+ {
+ return await ProcessAsync();
+ }
+ finally
+ {
+ progress.Report(100);
+ }
+ }
}
\ No newline at end of file
diff --git a/backend/Queue/FileProcessors/SevenZipProcessor.cs b/backend/Queue/FileProcessors/SevenZipProcessor.cs
index 895e1b1d..a7a7b1b5 100644
--- a/backend/Queue/FileProcessors/SevenZipProcessor.cs
+++ b/backend/Queue/FileProcessors/SevenZipProcessor.cs
@@ -1,5 +1,6 @@
using System.Text.RegularExpressions;
using NzbWebDAV.Clients.Usenet;
+using NzbWebDAV.Config;
using NzbWebDAV.Database.Models;
using NzbWebDAV.Exceptions;
using NzbWebDAV.Extensions;
@@ -15,6 +16,7 @@ public class SevenZipProcessor : BaseProcessor
{
private readonly List<GetFileInfosStep.FileInfo> _fileInfos;
private readonly INntpClient _usenetClient;
+ private readonly ConfigManager _configManager;
private readonly string? _archivePassword;
private readonly CancellationToken _ct;
@@ -22,51 +24,62 @@ public class SevenZipProcessor : BaseProcessor
(
List<GetFileInfosStep.FileInfo> fileInfos,
INntpClient usenetClient,
+ ConfigManager configManager,
string? archivePassword,
CancellationToken ct
)
{
_fileInfos = fileInfos;
_usenetClient = usenetClient;
+ _configManager = configManager;
_archivePassword = archivePassword;
_ct = ct;
}
- public override async Task<BaseProcessor.Result?> ProcessAsync()
+ public override async Task<BaseProcessor.Result?> ProcessAsync(IProgress<int> progress)
{
- var multipartFile = await GetMultipartFile().ConfigureAwait(false);
- await using var stream = new MultipartFileStream(multipartFile, _usenetClient);
- var sevenZipEntries = await SevenZipUtil
- .GetSevenZipEntriesAsync(stream, _archivePassword, _ct)
- .ConfigureAwait(false);
-
- if (sevenZipEntries.Any(x => x.CompressionType != CompressionType.None))
+ try
{
- const string message = "Only uncompressed 7z files are supported.";
- throw new Unsupported7zCompressionMethodException(message);
- }
+ var progress95 = progress.Scale(95, 100);
+ var multipartFile = await GetMultipartFile(progress95).ConfigureAwait(false);
+ await using var stream = new MultipartFileStream(multipartFile, _usenetClient);
+ var sevenZipEntries = await SevenZipUtil
+ .GetSevenZipEntriesAsync(stream, _archivePassword, _ct)
+ .ConfigureAwait(false);
- if (sevenZipEntries.Any(x => x.IsEncrypted && x.IsSolid))
- {
- // TODO: Add support for solid 7z archives
- const string message = "Password-protected 7z archives cannot be solid.";
- throw new NonRetryableDownloadException(message);
- }
+ if (sevenZipEntries.Any(x => x.CompressionType != CompressionType.None))
+ {
+ const string message = "Only uncompressed 7z files are supported.";
+ throw new Unsupported7zCompressionMethodException(message);
+ }
- return new Result()
- {
- SevenZipFiles = sevenZipEntries.Select(x => new SevenZipFile()
+ if (sevenZipEntries.Any(x => x.IsEncrypted && x.IsSolid))
{
- PathWithinArchive = x.PathWithinArchive,
- DavMultipartFileMeta = GetDavMultipartFileMeta(x, multipartFile),
- ReleaseDate = _fileInfos.First().ReleaseDate,
- }).ToList(),
- };
+ // TODO: Add support for solid 7z archives
+ const string message = "Password-protected 7z archives cannot be solid.";
+ throw new NonRetryableDownloadException(message);
+ }
+
+ return new Result()
+ {
+ SevenZipFiles = sevenZipEntries.Select(x => new SevenZipFile()
+ {
+ PathWithinArchive = x.PathWithinArchive,
+ DavMultipartFileMeta = GetDavMultipartFileMeta(x, multipartFile),
+ ReleaseDate = _fileInfos.First().ReleaseDate,
+ }).ToList(),
+ };
+ }
+ finally
+ {
+ progress.Report(100);
+ }
}
- private async Task<MultipartFile> GetMultipartFile()
+ private async Task<MultipartFile> GetMultipartFile(IProgress<int> progress)
{
- var sortedFileInfos = _fileInfos.OrderBy(f => GetPartNumber(f.FileName)).ToList();
+ var fileInfos = await PopulateMissingFileSizes(_fileInfos, progress).ConfigureAwait(false);
+ var sortedFileInfos = fileInfos.OrderBy(f => GetPartNumber(f.FileName)).ToList();
var fileParts = new List<MultipartFile.FilePart>();
long startInclusive = 0;
foreach (var fileInfo in sortedFileInfos)
@@ -87,6 +100,49 @@ public class SevenZipProcessor : BaseProcessor
return new MultipartFile() { FileParts = fileParts };
}
+ private async Task<List<GetFileInfosStep.FileInfo>> PopulateMissingFileSizes
+ (
+ List<GetFileInfosStep.FileInfo> fileInfos,
+ IProgress<int> progress
+ )
+ {
+ var missingFileSizes = new List<GetFileInfosStep.FileInfo>();
+ var withFileSizes = new List<GetFileInfosStep.FileInfo>();
+ foreach (var fileInfo in fileInfos)
+ {
+ if (fileInfo.FileSize == null) missingFileSizes.Add(fileInfo);
+ else withFileSizes.Add(fileInfo);
+ }
+
+ // if all files already have file sizes,
+ // then we can return immediately.
+ if (missingFileSizes.Count == 0)
+ {
+ progress.Report(100);
+ return withFileSizes;
+ }
+
+ // otherwise, let's populate the missing file sizes.
+ var progressPercentage = progress.ToPercentage(missingFileSizes.Count);
+ var populatedFileSizes = await missingFileSizes
+ .Select(PopulateMissingFileSize)
+ .WithConcurrencyAsync(_configManager.GetMaxDownloadConnections())
+ .GetAllAsync(_ct, progressPercentage)
+ .ConfigureAwait(false);
+ progress.Report(100);
+ return withFileSizes.Concat(populatedFileSizes).ToList();
+ }
+
+ private async Task<GetFileInfosStep.FileInfo> PopulateMissingFileSize(GetFileInfosStep.FileInfo fileInfo)
+ {
+ return fileInfo with
+ {
+ FileSize = await _usenetClient
+ .GetFileSizeAsync(fileInfo.NzbFile, _ct)
+ .ConfigureAwait(false)
+ };
+ }
+
private static int GetPartNumber(string filename)
{
var match = Regex.Match(filename, @"\.7z(\.(\d+))?$", RegexOptions.IgnoreCase);
diff --git a/backend/Queue/QueueItemProcessor.cs b/backend/Queue/QueueItemProcessor.cs
index ed6a6039..c9610686 100644
--- a/backend/Queue/QueueItemProcessor.cs
+++ b/backend/Queue/QueueItemProcessor.cs
@@ -135,11 +135,11 @@ public class QueueItemProcessor(
var part2Progress = progress
.Offset(50)
.Scale(50, 100)
- .ToPercentage(fileProcessors.Count);
+ .ToMultiProgress(fileProcessors.Count);
var fileProcessingResultsAll = await fileProcessors
- .Select(x => x!.ProcessAsync())
+ .Select(x => x!.ProcessAsync(part2Progress.SubProgress))
.WithConcurrencyAsync(configManager.GetMaxDownloadConnections() + 5)
- .GetAllAsync(ct, part2Progress).ConfigureAwait(false);
+ .GetAllAsync(ct).ConfigureAwait(false);
var fileProcessingResults = fileProcessingResultsAll
.Where(x => x is not null)
.Select(x => x!)
@@ -206,7 +206,7 @@ public class QueueItemProcessor(
foreach (var group in groups)
{
if (group.Key == "7z")
- yield return new SevenZipProcessor(group.ToList(), usenetClient, archivePassword, ct);
+ yield return new SevenZipProcessor(group.ToList(), usenetClient, configManager, archivePassword, ct);
else if (group.Key == "rar")
foreach (var fileInfo in group)
diff --git a/backend/Streams/MultiSegmentStream.cs b/backend/Streams/MultiSegmentStream.cs
index 4ca706c3..cdcb655d 100644
--- a/backend/Streams/MultiSegmentStream.cs
+++ b/backend/Streams/MultiSegmentStream.cs
@@ -1,5 +1,4 @@
-using System.Linq.Expressions;
-using System.Threading.Channels;
+using System.Threading.Channels;
using NzbWebDAV.Clients.Usenet;
using NzbWebDAV.Clients.Usenet.Models;
using UsenetSharp.Streams;
diff --git a/backend/Streams/UnbufferedMultiSegmentStream.cs b/backend/Streams/UnbufferedMultiSegmentStream.cs
index 74fdcee0..6f2fbb43 100644
--- a/backend/Streams/UnbufferedMultiSegmentStream.cs
+++ b/backend/Streams/UnbufferedMultiSegmentStream.cs
@@ -1,6 +1,4 @@
-using System.Threading.Channels;
-using NzbWebDAV.Clients.Usenet;
-using NzbWebDAV.Clients.Usenet.Models;
+using NzbWebDAV.Clients.Usenet;
using UsenetSharp.Streams;
namespace NzbWebDAV.Streams;
diff --git a/backend/Utils/RarUtil.cs b/backend/Utils/RarUtil.cs
index 1275850c..718a06ee 100644
--- a/backend/Utils/RarUtil.cs
+++ b/backend/Utils/RarUtil.cs
@@ -1,7 +1,6 @@
using NzbWebDAV.Exceptions;
using NzbWebDAV.Extensions;
using NzbWebDAV.Streams;
-using Serilog;
using SharpCompress.Common.Rar.Headers;
using SharpCompress.IO;
using SharpCompress.Readers;