Usenet streaming with a WebDAV server and a SABnzbd-compatible API
C#
Added support for multiple providers.
nzbdav-devb963ae17456c
diff --git a/.github/workflows/docker-publish.yml b/.github/workflows/docker-publish.ymlindex 6a1278e5..caaec6c5 100644--- a/.github/workflows/docker-publish.yml+++ b/.github/workflows/docker-publish.yml@@ -42,8 +42,8 @@ jobs:id: set_varsrun: |MAJOR=0- MINOR=4- PATCH=$(( ${{ github.run_number }} - 73 ))+ MINOR=5+ PATCH=$(( ${{ github.run_number }} - 115 ))if [[ "${{ github.ref_name }}" == "main" ]]; thenecho "NZBDAV_VERSION=${MAJOR}.${MINOR}.${PATCH}" >> $GITHUB_OUTPUTdiff --git a/backend/Api/Controllers/Authenticate/AuthenticateController.cs b/backend/Api/Controllers/Authenticate/AuthenticateController.csindex 2cbebc89..34798b37 100644--- a/backend/Api/Controllers/Authenticate/AuthenticateController.cs+++ b/backend/Api/Controllers/Authenticate/AuthenticateController.cs@@ -13,7 +13,7 @@ public class AuthenticateController(DavDatabaseClient dbClient) : BaseApiControl{var account = await dbClient.Ctx.Accounts.Where(a => a.Type == request.Type && a.Username == request.Username)- .FirstOrDefaultAsync();+ .FirstOrDefaultAsync().ConfigureAwait(false);return new AuthenticateResponse(){@@ -25,7 +25,7 @@ public class AuthenticateController(DavDatabaseClient dbClient) : BaseApiControlprotected override async Task<IActionResult> HandleRequest(){var request = new AuthenticateRequest(HttpContext);- var response = await Authenticate(request);+ var response = await Authenticate(request).ConfigureAwait(false);return Ok(response);}}\ No newline at end of filediff --git a/backend/Api/Controllers/BaseApiController.cs b/backend/Api/Controllers/BaseApiController.csindex 57d6aef5..37963c34 100644--- a/backend/Api/Controllers/BaseApiController.cs+++ b/backend/Api/Controllers/BaseApiController.cs@@ -25,7 +25,7 @@ public abstract class BaseApiController : ControllerBasethrow new UnauthorizedAccessException("API Key Incorrect");}- return await HandleRequest();+ return await HandleRequest().ConfigureAwait(false);}catch (BadHttpRequestException e){diff --git a/backend/Api/Controllers/ConvertStrmToSymlinks/ConvertStrmToSymlinksController.cs b/backend/Api/Controllers/ConvertStrmToSymlinks/ConvertStrmToSymlinksController.csindex ba844c83..019518f6 100644--- a/backend/Api/Controllers/ConvertStrmToSymlinks/ConvertStrmToSymlinksController.cs+++ b/backend/Api/Controllers/ConvertStrmToSymlinks/ConvertStrmToSymlinksController.cs@@ -17,7 +17,7 @@ public class ConvertStrmToSymlinks(protected override async Task<IActionResult> HandleRequest(){var task = new StrmToSymlinksTask(configManager, dbClient, websocketManager);- var executed = await task.Execute();+ var executed = await task.Execute().ConfigureAwait(false);return Ok(executed);}}\ No newline at end of filediff --git a/backend/Api/Controllers/CreateAccount/CreateAccountController.cs b/backend/Api/Controllers/CreateAccount/CreateAccountController.csindex 9dab392d..1c9dbe51 100644--- a/backend/Api/Controllers/CreateAccount/CreateAccountController.cs+++ b/backend/Api/Controllers/CreateAccount/CreateAccountController.cs@@ -20,14 +20,14 @@ public class CreateAccountController(DavDatabaseClient dbClient) : BaseApiControPasswordHash = PasswordUtil.Hash(request.Password, randomSalt),};dbClient.Ctx.Accounts.Add(account);- await dbClient.Ctx.SaveChangesAsync(HttpContext.RequestAborted);+ await dbClient.Ctx.SaveChangesAsync(HttpContext.RequestAborted).ConfigureAwait(false);return new CreateAccountResponse() { Status = true };}protected override async Task<IActionResult> HandleRequest(){var request = new CreateAccountRequest(HttpContext);- var response = await CreateAccount(request);+ var response = await CreateAccount(request).ConfigureAwait(false);return Ok(response);}}\ No newline at end of filediff --git a/backend/Api/Controllers/GetConfig/GetConfigController.cs b/backend/Api/Controllers/GetConfig/GetConfigController.csindex f1ba4c6e..5e1d62d3 100644--- a/backend/Api/Controllers/GetConfig/GetConfigController.cs+++ b/backend/Api/Controllers/GetConfig/GetConfigController.cs@@ -12,7 +12,7 @@ public class GetConfigController(DavDatabaseClient dbClient) : BaseApiController{var configItems = await dbClient.Ctx.ConfigItems.Where(x => request.ConfigKeys.Contains(x.ConfigName))- .ToListAsync(HttpContext.RequestAborted);+ .ToListAsync(HttpContext.RequestAborted).ConfigureAwait(false);var response = new GetConfigResponse { ConfigItems = configItems };return response;@@ -21,7 +21,7 @@ public class GetConfigController(DavDatabaseClient dbClient) : BaseApiControllerprotected override async Task<IActionResult> HandleRequest(){var request = new GetConfigRequest(HttpContext);- var response = await GetConfig(request);+ var response = await GetConfig(request).ConfigureAwait(false);return Ok(response);}}\ No newline at end of filediff --git a/backend/Api/Controllers/GetHealthCheckHistory/GetHealthCheckHistoryController.cs b/backend/Api/Controllers/GetHealthCheckHistory/GetHealthCheckHistoryController.csindex f3589e05..74ac56c8 100644--- a/backend/Api/Controllers/GetHealthCheckHistory/GetHealthCheckHistoryController.cs+++ b/backend/Api/Controllers/GetHealthCheckHistory/GetHealthCheckHistoryController.cs@@ -21,15 +21,15 @@ public class GetHealthCheckHistoryController(DavDatabaseClient dbClient) : BaseAreturn new GetHealthCheckHistoryResponse(){- Stats = await statsPromise,- Items = await itemsPromise+ Stats = await statsPromise.ConfigureAwait(false),+ Items = await itemsPromise.ConfigureAwait(false)};}protected override async Task<IActionResult> HandleRequest(){var request = new GetHealthCheckHistoryRequest(HttpContext);- var response = await GetHealthCheckHistory(request);+ var response = await GetHealthCheckHistory(request).ConfigureAwait(false);return Ok(response);}}\ No newline at end of filediff --git a/backend/Api/Controllers/GetHealthCheckQueue/GetHealthCheckQueueController.cs b/backend/Api/Controllers/GetHealthCheckQueue/GetHealthCheckQueueController.csindex a2c0aad9..fe949427 100644--- a/backend/Api/Controllers/GetHealthCheckQueue/GetHealthCheckQueueController.cs+++ b/backend/Api/Controllers/GetHealthCheckQueue/GetHealthCheckQueueController.cs@@ -1,7 +1,6 @@using Microsoft.AspNetCore.Mvc;using Microsoft.EntityFrameworkCore;using NzbWebDAV.Database;-using NzbWebDAV.Database.Models;using NzbWebDAV.Services;namespace NzbWebDAV.Api.Controllers.GetHealthCheckQueue;@@ -14,11 +13,11 @@ public class GetHealthCheckQueueController(DavDatabaseClient dbClient) : BaseApi{var davItems = await HealthCheckService.GetHealthCheckQueueItems(dbClient).Take(request.PageSize)- .ToListAsync();+ .ToListAsync().ConfigureAwait(false);var uncheckedCount = await HealthCheckService.GetHealthCheckQueueItemsQuery(dbClient).Where(x => x.NextHealthCheck == null)- .CountAsync();+ .CountAsync().ConfigureAwait(false);return new GetHealthCheckQueueResponse(){@@ -38,7 +37,7 @@ public class GetHealthCheckQueueController(DavDatabaseClient dbClient) : BaseApiprotected override async Task<IActionResult> HandleRequest(){var request = new GetHealthCheckQueueRequest(HttpContext);- var response = await GetHealthCheckQueue(request);+ var response = await GetHealthCheckQueue(request).ConfigureAwait(false);return Ok(response);}}\ No newline at end of filediff --git a/backend/Api/Controllers/GetWebdavItem/GetWebdavItemController.cs b/backend/Api/Controllers/GetWebdavItem/GetWebdavItemController.csindex 965d6268..575d84b4 100644--- a/backend/Api/Controllers/GetWebdavItem/GetWebdavItemController.cs+++ b/backend/Api/Controllers/GetWebdavItem/GetWebdavItemController.cs@@ -6,6 +6,7 @@ using NWebDav.Server.Stores;using NzbWebDAV.Config;using NzbWebDAV.Extensions;using NzbWebDAV.Par2Recovery;+using NzbWebDAV.Utils;using NzbWebDAV.WebDav;namespace NzbWebDAV.Api.Controllers.GetWebdavItem;@@ -18,16 +19,16 @@ public class ListWebdavDirectoryController(DatabaseStore store, ConfigManager coprivate async Task<Stream> GetWebdavItem(GetWebdavItemRequest request){- var item = await store.GetItemAsync(request.Item, HttpContext.RequestAborted);+ var item = await store.GetItemAsync(request.Item, HttpContext.RequestAborted).ConfigureAwait(false);if (item is null) throw new BadHttpRequestException("The file does not exist.");if (item is IStoreCollection) throw new BadHttpRequestException("The file does not exist.");// handle par2 previewif (Path.GetExtension(item.Name).ToLower() == ".par2" && configManager.IsPreviewPar2FilesEnabled())- return await GetPar2PreviewStream(item);+ return await GetPar2PreviewStream(item).ConfigureAwait(false);// get the file stream and set the file-size in header- var stream = await item.GetReadableStreamAsync(HttpContext.RequestAborted);+ var stream = await item.GetReadableStreamAsync(HttpContext.RequestAborted).ConfigureAwait(false);var fileSize = stream.Length;// set the content-typ header@@ -64,8 +65,8 @@ public class ListWebdavDirectoryController(DatabaseStore store, ConfigManager co{HttpContext.Items["configManager"] = configManager;var request = new GetWebdavItemRequest(HttpContext);- await using var response = await GetWebdavItem(request);- await response.CopyToAsync(Response.Body, bufferSize: 1024, HttpContext.RequestAborted);+ await using var response = await GetWebdavItem(request).ConfigureAwait(false);+ await response.CopyToAsync(Response.Body, bufferSize: 1024, HttpContext.RequestAborted).ConfigureAwait(false);}catch (UnauthorizedAccessException){@@ -86,8 +87,9 @@ public class ListWebdavDirectoryController(DatabaseStore store, ConfigManager coprivate async Task<Stream> GetPar2PreviewStream(IStoreItem item){Response.Headers.ContentType = "text/plain";- await using var stream = await item.GetReadableStreamAsync(HttpContext.RequestAborted);- var fileDescriptors = await Par2.ReadFileDescriptions(stream, HttpContext.RequestAborted).GetAllAsync();+ await using var stream = await item.GetReadableStreamAsync(HttpContext.RequestAborted).ConfigureAwait(false);+ var fileDescriptors = await Par2.ReadFileDescriptions(stream, HttpContext.RequestAborted).GetAllAsync()+ .ConfigureAwait(false);return new MemoryStream(Encoding.UTF8.GetBytes(fileDescriptors.ToIndentedJson()));}}\ No newline at end of filediff --git a/backend/Api/Controllers/IsOnboarding/IsOnboardingController.cs b/backend/Api/Controllers/IsOnboarding/IsOnboardingController.csindex 64fcb0b4..d1e3c21b 100644--- a/backend/Api/Controllers/IsOnboarding/IsOnboardingController.cs+++ b/backend/Api/Controllers/IsOnboarding/IsOnboardingController.cs@@ -13,13 +13,13 @@ public class IsOnboardingController(DavDatabaseClient dbClient) : BaseApiControl{var account = await dbClient.Ctx.Accounts.Where(a => a.Type == Account.AccountType.Admin)- .FirstOrDefaultAsync();+ .FirstOrDefaultAsync().ConfigureAwait(false);return new IsOnboardingResponse() { IsOnboarding = account == null };}protected override async Task<IActionResult> HandleRequest(){- var response = await IsOnboarding();+ var response = await IsOnboarding().ConfigureAwait(false);return Ok(response);}}\ No newline at end of filediff --git a/backend/Api/Controllers/ListWebdavDirectory/ListWebdavDirectoryController.cs b/backend/Api/Controllers/ListWebdavDirectory/ListWebdavDirectoryController.csindex 26b93d61..8563d3ec 100644--- a/backend/Api/Controllers/ListWebdavDirectory/ListWebdavDirectoryController.cs+++ b/backend/Api/Controllers/ListWebdavDirectory/ListWebdavDirectoryController.cs@@ -13,7 +13,7 @@ public class ListWebdavDirectoryController(DatabaseStore store, ConfigManager co{private async Task<ListWebdavDirectoryResponse> ListWebdavDirectory(ListWebdavDirectoryRequest request){- var item = await store.GetItemAsync(request.Directory, HttpContext.RequestAborted);+ var item = await store.GetItemAsync(request.Directory, HttpContext.RequestAborted).ConfigureAwait(false);if (item is null) throw new BadHttpRequestException("The directory does not exist.");if (item is not IStoreCollection dir) throw new BadHttpRequestException("The directory does not exist.");var children = new List<ListWebdavDirectoryResponse.DirectoryItem>();@@ -37,7 +37,7 @@ public class ListWebdavDirectoryController(DatabaseStore store, ConfigManager coprotected override async Task<IActionResult> HandleRequest(){var request = new ListWebdavDirectoryRequest(HttpContext);- var response = await ListWebdavDirectory(request);+ var response = await ListWebdavDirectory(request).ConfigureAwait(false);return Ok(response);}}\ No newline at end of filediff --git a/backend/Api/Controllers/RemoveUnlinkedFiles/RemoveUnlinkedFilesController.cs b/backend/Api/Controllers/RemoveUnlinkedFiles/RemoveUnlinkedFilesController.csindex d10e1f30..fd5715a1 100644--- a/backend/Api/Controllers/RemoveUnlinkedFiles/RemoveUnlinkedFilesController.cs+++ b/backend/Api/Controllers/RemoveUnlinkedFiles/RemoveUnlinkedFilesController.cs@@ -17,7 +17,7 @@ public class RemoveUnlinkedFilesController(protected override async Task<IActionResult> HandleRequest(){var task = new RemoveUnlinkedFilesTask(configManager, dbClient, websocketManager, isDryRun: false);- var executed = await task.Execute();+ var executed = await task.Execute().ConfigureAwait(false);return Ok(executed);}}\ No newline at end of filediff --git a/backend/Api/Controllers/RemoveUnlinkedFiles/RemoveUnlinkedFilesDryRunController.cs b/backend/Api/Controllers/RemoveUnlinkedFiles/RemoveUnlinkedFilesDryRunController.csindex c7d77837..99fa9566 100644--- a/backend/Api/Controllers/RemoveUnlinkedFiles/RemoveUnlinkedFilesDryRunController.cs+++ b/backend/Api/Controllers/RemoveUnlinkedFiles/RemoveUnlinkedFilesDryRunController.cs@@ -17,7 +17,7 @@ public class RemoveUnlinkedFilesDryRunController(protected override async Task<IActionResult> HandleRequest(){var task = new RemoveUnlinkedFilesTask(configManager, dbClient, websocketManager, isDryRun: true);- var executed = await task.Execute();+ var executed = await task.Execute().ConfigureAwait(false);return Ok(executed);}}\ No newline at end of filediff --git a/backend/Api/Controllers/TestArrConnection/TestArrConnectionController.cs b/backend/Api/Controllers/TestArrConnection/TestArrConnectionController.csindex d9bc9b81..330261d4 100644--- a/backend/Api/Controllers/TestArrConnection/TestArrConnectionController.cs+++ b/backend/Api/Controllers/TestArrConnection/TestArrConnectionController.cs@@ -12,7 +12,7 @@ public class TestArrConnectionController() : BaseApiControllertry{var client = new ArrClient(request.Host, request.ApiKey);- var apiInfo = await client.GetApiInfo();+ var apiInfo = await client.GetApiInfo().ConfigureAwait(false);return new TestArrConnectionResponse{Status = true,@@ -33,7 +33,7 @@ public class TestArrConnectionController() : BaseApiControllerprotected override async Task<IActionResult> HandleRequest(){var request = new TestArrConnectionRequest(HttpContext);- var response = await TestArrConnection(request);+ var response = await TestArrConnection(request).ConfigureAwait(false);return Ok(response);}}\ No newline at end of filediff --git a/backend/Api/Controllers/TestUsenetConnection/TestUsenetConnectionController.cs b/backend/Api/Controllers/TestUsenetConnection/TestUsenetConnectionController.csindex 6e27ef85..63684a39 100644--- a/backend/Api/Controllers/TestUsenetConnection/TestUsenetConnectionController.cs+++ b/backend/Api/Controllers/TestUsenetConnection/TestUsenetConnectionController.cs@@ -12,8 +12,7 @@ public class TestUsenetConnectionController() : BaseApiController{try{- await UsenetStreamingClient.CreateNewConnection(- request.Host, request.Port, request.UseSsl, request.User, request.Pass, HttpContext.RequestAborted);+ await UsenetStreamingClient.CreateNewConnection(request.ToConnectionDetails(), HttpContext.RequestAborted).ConfigureAwait(false);return new TestUsenetConnectionResponse { Status = true, Connected = true };}catch (CouldNotConnectToUsenetException)@@ -29,7 +28,7 @@ public class TestUsenetConnectionController() : BaseApiControllerprotected override async Task<IActionResult> HandleRequest(){var request = new TestUsenetConnectionRequest(HttpContext);- var response = await TestUsenetConnection(request);+ var response = await TestUsenetConnection(request).ConfigureAwait(false);return Ok(response);}}\ No newline at end of filediff --git a/backend/Api/Controllers/TestUsenetConnection/TestUsenetConnectionRequest.cs b/backend/Api/Controllers/TestUsenetConnection/TestUsenetConnectionRequest.csindex c4fe2341..26ca69dd 100644--- a/backend/Api/Controllers/TestUsenetConnection/TestUsenetConnectionRequest.cs+++ b/backend/Api/Controllers/TestUsenetConnection/TestUsenetConnectionRequest.cs@@ -1,4 +1,6 @@using Microsoft.AspNetCore.Http;+using NzbWebDAV.Config;+using NzbWebDAV.Models;namespace NzbWebDAV.Api.Controllers.TestUsenetConnection;@@ -35,4 +37,18 @@ public class TestUsenetConnectionRequest? throw new BadHttpRequestException("Invalid use-ssl value"): useSslValue;}++ public UsenetProviderConfig.ConnectionDetails ToConnectionDetails()+ {+ return new UsenetProviderConfig.ConnectionDetails+ {+ Host = Host,+ User = User,+ Pass = Pass,+ Port = Port,+ UseSsl = UseSsl,+ MaxConnections = 1,+ Type = ProviderType.Disabled+ };+ }}\ No newline at end of filediff --git a/backend/Api/Controllers/UpdateConfig/UpdateConfigController.cs b/backend/Api/Controllers/UpdateConfig/UpdateConfigController.csindex d5aae84d..f741f862 100644--- a/backend/Api/Controllers/UpdateConfig/UpdateConfigController.cs+++ b/backend/Api/Controllers/UpdateConfig/UpdateConfigController.cs@@ -16,7 +16,7 @@ public class UpdateConfigController(DavDatabaseClient dbClient, ConfigManager covar configNames = request.ConfigItems.Select(x => x.ConfigName).ToHashSet();var existingItems = await dbClient.Ctx.ConfigItems.Where(c => configNames.Contains(c.ConfigName))- .ToListAsync(HttpContext.RequestAborted);+ .ToListAsync(HttpContext.RequestAborted).ConfigureAwait(false);// 2. Split the items into those that need to be updated and those that need to be insertedvar existingItemsDict = existingItems.ToDictionary(i => i.ConfigName);@@ -40,7 +40,7 @@ public class UpdateConfigController(DavDatabaseClient dbClient, ConfigManager codbClient.Ctx.ConfigItems.UpdateRange(itemsToUpdate);// 4. Save changes in one call- await dbClient.Ctx.SaveChangesAsync(HttpContext.RequestAborted);+ await dbClient.Ctx.SaveChangesAsync(HttpContext.RequestAborted).ConfigureAwait(false);// 5. Update the ConfigManagerconfigManager.UpdateValues(request.ConfigItems);@@ -52,7 +52,7 @@ public class UpdateConfigController(DavDatabaseClient dbClient, ConfigManager coprotected override async Task<IActionResult> HandleRequest(){var request = new UpdateConfigRequest(HttpContext);- var response = await UpdateConfig(request);+ var response = await UpdateConfig(request).ConfigureAwait(false);return Ok(response);}}\ No newline at end of filediff --git a/backend/Api/SabControllers/AddFile/AddFileController.cs b/backend/Api/SabControllers/AddFile/AddFileController.csindex 8702c2ab..2c44478a 100644--- a/backend/Api/SabControllers/AddFile/AddFileController.cs+++ b/backend/Api/SabControllers/AddFile/AddFileController.cs@@ -26,7 +26,7 @@ public class AddFileController(var nzbFileContents = NormalizeNzbContents(request.NzbFileContents);var documentBytes = Encoding.UTF8.GetBytes(nzbFileContents);using var memoryStream = new MemoryStream(documentBytes);- var document = await NzbDocument.LoadAsync(memoryStream);+ var document = await NzbDocument.LoadAsync(memoryStream).ConfigureAwait(false);// add the queueItem to the databasevar queueItem = new QueueItem@@ -49,7 +49,7 @@ public class AddFileController(};dbClient.Ctx.QueueItems.Add(queueItem);dbClient.Ctx.QueueNzbContents.Add(queueNzbContents);- await dbClient.Ctx.SaveChangesAsync(request.CancellationToken);+ await dbClient.Ctx.SaveChangesAsync(request.CancellationToken).ConfigureAwait(false);var message = GetQueueResponse.QueueSlot.FromQueueItem(queueItem).ToJson();_ = websocketManager.SendMessage(WebsocketTopic.QueueItemAdded, message);@@ -63,8 +63,8 @@ public class AddFileController(protected override async Task<IActionResult> Handle(){- var request = await AddFileRequest.New(httpContext);- return Ok(await AddFileAsync(request));+ var request = await AddFileRequest.New(httpContext).ConfigureAwait(false);+ return Ok(await AddFileAsync(request).ConfigureAwait(false));}private static string NormalizeNzbContents(string nzbContents)diff --git a/backend/Api/SabControllers/AddFile/AddFileRequest.cs b/backend/Api/SabControllers/AddFile/AddFileRequest.csindex fc481f84..ee44a730 100644--- a/backend/Api/SabControllers/AddFile/AddFileRequest.cs+++ b/backend/Api/SabControllers/AddFile/AddFileRequest.cs@@ -28,7 +28,7 @@ public class AddFileRequest(){FileName = file.FileName,MimeType = file.ContentType,- NzbFileContents = await streamReader.ReadToEndAsync(context.RequestAborted),+ NzbFileContents = await streamReader.ReadToEndAsync(context.RequestAborted).ConfigureAwait(false),Category = context.GetQueryParam("cat") ?? throw new BadHttpRequestException("Invalid cat param"),Priority = MapPriorityOption(context.GetQueryParam("priority")),PostProcessing = MapPostProcessingOption(context.GetQueryParam("pp")),diff --git a/backend/Api/SabControllers/AddUrl/AddUrlController.cs b/backend/Api/SabControllers/AddUrl/AddUrlController.csindex 683dad30..9082e534 100644--- a/backend/Api/SabControllers/AddUrl/AddUrlController.cs+++ b/backend/Api/SabControllers/AddUrl/AddUrlController.cs@@ -19,7 +19,7 @@ public class AddUrlController(public async Task<AddUrlResponse> AddUrlAsync(AddUrlRequest request){var controller = new AddFileController(httpContext, dbClient, queueManager, configManager, websocketManager);- var response = await controller.AddFileAsync(request);+ var response = await controller.AddFileAsync(request).ConfigureAwait(false);return new AddUrlResponse(){Status = response.Status,@@ -29,7 +29,7 @@ public class AddUrlController(protected override async Task<IActionResult> Handle(){- var request = await AddUrlRequest.New(httpContext);- return Ok(await AddUrlAsync(request));+ var request = await AddUrlRequest.New(httpContext).ConfigureAwait(false);+ return Ok(await AddUrlAsync(request).ConfigureAwait(false));}}\ No newline at end of filediff --git a/backend/Api/SabControllers/AddUrl/AddUrlRequest.cs b/backend/Api/SabControllers/AddUrl/AddUrlRequest.csindex ec540a60..fc3773f7 100644--- a/backend/Api/SabControllers/AddUrl/AddUrlRequest.cs+++ b/backend/Api/SabControllers/AddUrl/AddUrlRequest.cs@@ -1,11 +1,15 @@using Microsoft.AspNetCore.Http;using NzbWebDAV.Api.SabControllers.AddFile;using NzbWebDAV.Extensions;+using NzbWebDAV.Utils;namespace NzbWebDAV.Api.SabControllers.AddUrl;public class AddUrlRequest() : AddFileRequest{+ private static readonly HttpClient HttpClient = GetHttpClient();++ private const int MaxAutomaticRedirections = 10;private const string UserAgentHeader ="Mozilla/5.0 (Windows NT 11.0; Win64; x64) AppleWebKit/537.36 " +"(KHTML, like Gecko) Chrome/134.0.6998.166 Safari/537.36";@@ -14,7 +18,7 @@ public class AddUrlRequest() : AddFileRequest{var nzbUrl = context.GetQueryParam("name");var nzbName = context.GetQueryParam("nzbname");- var nzbFile = await GetNzbFile(nzbUrl, nzbName);+ var nzbFile = await GetNzbFile(nzbUrl, nzbName).ConfigureAwait(false);return new AddUrlRequest(){FileName = nzbFile.FileName,@@ -36,9 +40,7 @@ public class AddUrlRequest() : AddFileRequestthrow new Exception($"The url is invalid.");// fetch url- var httpClient = new HttpClient();- httpClient.DefaultRequestHeaders.Add("User-Agent", UserAgentHeader);- var response = await httpClient.GetAsync(url);+ var response = await GetAsync(url).ConfigureAwait(false);if (!response.IsSuccessStatusCode)throw new Exception($"Received status code {response.StatusCode}.");@@ -56,7 +58,7 @@ public class AddUrlRequest() : AddFileRequest}// read the file contents- var fileContents = await response.Content.ReadAsStringAsync();+ var fileContents = await response.Content.ReadAsStringAsync().ConfigureAwait(false);if (string.IsNullOrWhiteSpace(fileContents))throw new Exception("NZB file contents are empty.");@@ -81,6 +83,39 @@ public class AddUrlRequest() : AddFileRequest: $"{nzbName}.nzb";}+ private static async Task<HttpResponseMessage> GetAsync(string url)+ {+ var response = await HttpClient.GetAsync(url);+ var remainingRedirects = MaxAutomaticRedirections;+ while+ (+ (int)response.StatusCode is >= 300 and < 400+ && remainingRedirects > 0+ && response.Headers.Location is not null+ && EnvironmentUtil.IsVariableTrue("ALLOW_HTTPS_TO_HTTP_REDIRECTS")+ )+ {+ var redirect = response.Headers.Location;+ var redirectUri = redirect.IsAbsoluteUri ? redirect : new Uri(new Uri(url), redirect);+ response = await HttpClient.GetAsync(redirectUri);+ remainingRedirects--;+ }++ return response;+ }++ private static HttpClient GetHttpClient()+ {+ var handler = new HttpClientHandler+ {+ AllowAutoRedirect = true,+ MaxAutomaticRedirections = MaxAutomaticRedirections,+ };+ var httpClient = new HttpClient(handler);+ httpClient.DefaultRequestHeaders.Add("User-Agent", UserAgentHeader);+ return httpClient;+ }+private class NzbFileResponse{public required string FileName { get; init; }diff --git a/backend/Api/SabControllers/GetConfig/GetConfigController.cs b/backend/Api/SabControllers/GetConfig/GetConfigController.csindex b1896497..dd43b0fa 100644--- a/backend/Api/SabControllers/GetConfig/GetConfigController.cs+++ b/backend/Api/SabControllers/GetConfig/GetConfigController.cs@@ -20,7 +20,7 @@ public class GetConfigController(protected override async Task<IActionResult> Handle(){// read the config template from file and deserialize it- var config = await EmbeddedResourceUtil.ReadAllTextAsync("config_template.json");+ var config = await EmbeddedResourceUtil.ReadAllTextAsync("config_template.json").ConfigureAwait(false);var root = JsonNode.Parse(config)!;// update the complete_dirdiff --git a/backend/Api/SabControllers/GetHistory/GetHistoryController.cs b/backend/Api/SabControllers/GetHistory/GetHistoryController.csindex 485ec0d0..898edd2f 100644--- a/backend/Api/SabControllers/GetHistory/GetHistoryController.cs+++ b/backend/Api/SabControllers/GetHistory/GetHistoryController.cs@@ -34,14 +34,14 @@ public class GetHistoryController(.ToArrayAsync(request.CancellationToken);// await results- var totalCount = await totalCountPromise;- var historyItems = await historyItemsPromise;+ var totalCount = await totalCountPromise.ConfigureAwait(false);+ var historyItems = await historyItemsPromise.ConfigureAwait(false);// get download foldersvar downloadFolderIds = historyItems.Select(x => x.DownloadDirId).ToHashSet();var davItems = await dbClient.Ctx.Items.Where(x => downloadFolderIds.Contains(x.Id))- .ToArrayAsync(request.CancellationToken);+ .ToArrayAsync(request.CancellationToken).ConfigureAwait(false);var davItemsDict = davItems.ToDictionary(x => x.Id, x => x);@@ -70,6 +70,6 @@ public class GetHistoryController(protected override async Task<IActionResult> Handle(){var request = new GetHistoryRequest(httpContext, configManager);- return Ok(await GetHistoryAsync(request));+ return Ok(await GetHistoryAsync(request).ConfigureAwait(false));}}\ No newline at end of filediff --git a/backend/Api/SabControllers/GetQueue/GetQueueController.cs b/backend/Api/SabControllers/GetQueue/GetQueueController.csindex c25d5847..7ef3e972 100644--- a/backend/Api/SabControllers/GetQueue/GetQueueController.cs+++ b/backend/Api/SabControllers/GetQueue/GetQueueController.cs@@ -20,10 +20,10 @@ public class GetQueueController(// get total countvar ct = request.CancellationToken;- var totalCount = await dbClient.GetQueueItemsCount(request.Category, ct);+ var totalCount = await dbClient.GetQueueItemsCount(request.Category, ct).ConfigureAwait(false);// get queued items- var queueItems = (await dbClient.GetQueueItems(request.Category, request.Start, request.Limit, ct))+ var queueItems = (await dbClient.GetQueueItems(request.Category, request.Start, request.Limit, ct).ConfigureAwait(false)).Where(x => x.Id != inProgressQueueItem?.Id).ToArray();@@ -54,6 +54,6 @@ public class GetQueueController(protected override async Task<IActionResult> Handle(){var request = new GetQueueRequest(httpContext);- return Ok(await GetQueueAsync(request));+ return Ok(await GetQueueAsync(request).ConfigureAwait(false));}}\ No newline at end of filediff --git a/backend/Api/SabControllers/RemoveFromHistory/RemoveFromHistoryController.cs b/backend/Api/SabControllers/RemoveFromHistory/RemoveFromHistoryController.csindex f9fd4a06..f4198b0a 100644--- a/backend/Api/SabControllers/RemoveFromHistory/RemoveFromHistoryController.cs+++ b/backend/Api/SabControllers/RemoveFromHistory/RemoveFromHistoryController.cs@@ -15,17 +15,17 @@ public class RemoveFromHistoryController({public async Task<RemoveFromHistoryResponse> RemoveFromHistory(RemoveFromHistoryRequest request){- await using var transaction = await dbClient.Ctx.Database.BeginTransactionAsync();- await dbClient.RemoveHistoryItemsAsync(request.NzoIds, request.DeleteCompletedFiles, request.CancellationToken);- await dbClient.Ctx.SaveChangesAsync(request.CancellationToken);- await transaction.CommitAsync(request.CancellationToken);+ await using var transaction = await dbClient.Ctx.Database.BeginTransactionAsync().ConfigureAwait(false);+ await dbClient.RemoveHistoryItemsAsync(request.NzoIds, request.DeleteCompletedFiles, request.CancellationToken).ConfigureAwait(false);+ await dbClient.Ctx.SaveChangesAsync(request.CancellationToken).ConfigureAwait(false);+ await transaction.CommitAsync(request.CancellationToken).ConfigureAwait(false);_ = websocketManager.SendMessage(WebsocketTopic.HistoryItemRemoved, string.Join(",", request.NzoIds));return new RemoveFromHistoryResponse() { Status = true };}protected override async Task<IActionResult> Handle(){- var request = await RemoveFromHistoryRequest.New(httpContext);- return Ok(await RemoveFromHistory(request));+ var request = await RemoveFromHistoryRequest.New(httpContext).ConfigureAwait(false);+ return Ok(await RemoveFromHistory(request).ConfigureAwait(false));}}\ No newline at end of filediff --git a/backend/Api/SabControllers/RemoveFromHistory/RemoveFromHistoryRequest.cs b/backend/Api/SabControllers/RemoveFromHistory/RemoveFromHistoryRequest.csindex b13cf35e..e903d221 100644--- a/backend/Api/SabControllers/RemoveFromHistory/RemoveFromHistoryRequest.cs+++ b/backend/Api/SabControllers/RemoveFromHistory/RemoveFromHistoryRequest.cs@@ -28,7 +28,7 @@ public class RemoveFromHistoryRequestreturn new RemoveFromHistoryRequest(){NzoIds = NzoIdsFromQueryParam(httpContext)- .Concat(await NzoIdsFromRequestBody(httpContext, cancellationToken))+ .Concat(await NzoIdsFromRequestBody(httpContext, cancellationToken).ConfigureAwait(false)).ToList(),DeleteCompletedFiles = httpContext.GetQueryParam("del_completed_files") == "1",CancellationToken = cancellationToken@@ -45,7 +45,7 @@ public class RemoveFromHistoryRequesttry{await using var stream = httpContext.Request.Body;- var deserialized = await JsonSerializer.DeserializeAsync<RequestBody>(stream, cancellationToken: ct);+ var deserialized = await JsonSerializer.DeserializeAsync<RequestBody>(stream, cancellationToken: ct).ConfigureAwait(false);return deserialized?.NzoIds ?? [];}catchdiff --git a/backend/Api/SabControllers/RemoveFromQueue/RemoveFromQueueController.cs b/backend/Api/SabControllers/RemoveFromQueue/RemoveFromQueueController.csindex 35a3968f..72543646 100644--- a/backend/Api/SabControllers/RemoveFromQueue/RemoveFromQueueController.cs+++ b/backend/Api/SabControllers/RemoveFromQueue/RemoveFromQueueController.cs@@ -17,14 +17,14 @@ public class RemoveFromQueueController({public async Task<RemoveFromQueueResponse> RemoveFromQueue(RemoveFromQueueRequest request){- await queueManager.RemoveQueueItemsAsync(request.NzoIds, dbClient, request.CancellationToken);+ await queueManager.RemoveQueueItemsAsync(request.NzoIds, dbClient, request.CancellationToken).ConfigureAwait(false);_ = websocketManager.SendMessage(WebsocketTopic.QueueItemRemoved, string.Join(",", request.NzoIds));return new RemoveFromQueueResponse() { Status = true };}protected override async Task<IActionResult> Handle(){- var request = await RemoveFromQueueRequest.New(httpContext);- return Ok(await RemoveFromQueue(request));+ var request = await RemoveFromQueueRequest.New(httpContext).ConfigureAwait(false);+ return Ok(await RemoveFromQueue(request).ConfigureAwait(false));}}\ No newline at end of filediff --git a/backend/Api/SabControllers/RemoveFromQueue/RemoveFromQueueRequest.cs b/backend/Api/SabControllers/RemoveFromQueue/RemoveFromQueueRequest.csindex 18aa81de..8288f9a7 100644--- a/backend/Api/SabControllers/RemoveFromQueue/RemoveFromQueueRequest.cs+++ b/backend/Api/SabControllers/RemoveFromQueue/RemoveFromQueueRequest.cs@@ -17,7 +17,7 @@ public class RemoveFromQueueRequest()return new RemoveFromQueueRequest(){NzoIds = NzoIdsFromQueryParam(httpContext)- .Concat(await NzoIdsFromRequestBody(httpContext, cancellationToken))+ .Concat(await NzoIdsFromRequestBody(httpContext, cancellationToken).ConfigureAwait(false)).ToList(),CancellationToken = cancellationToken};@@ -33,7 +33,7 @@ public class RemoveFromQueueRequest()try{await using var stream = httpContext.Request.Body;- var deserialized = await JsonSerializer.DeserializeAsync<RequestBody>(stream, cancellationToken: ct);+ var deserialized = await JsonSerializer.DeserializeAsync<RequestBody>(stream, cancellationToken: ct).ConfigureAwait(false);return deserialized?.NzoIds ?? [];}catchdiff --git a/backend/Api/SabControllers/SabApiController.cs b/backend/Api/SabControllers/SabApiController.csindex 3d77a4a4..6816ca7b 100644--- a/backend/Api/SabControllers/SabApiController.cs+++ b/backend/Api/SabControllers/SabApiController.cs@@ -34,7 +34,7 @@ public class SabApiController(try{var controller = GetController();- return await controller.HandleRequest();+ return await controller.HandleRequest().ConfigureAwait(false);}catch (BadHttpRequestException e){diff --git a/backend/Clients/RadarrSonarr/ArrClient.cs b/backend/Clients/RadarrSonarr/ArrClient.csindex 382c674a..f76da48f 100644--- a/backend/Clients/RadarrSonarr/ArrClient.cs+++ b/backend/Clients/RadarrSonarr/ArrClient.cs@@ -8,6 +8,8 @@ namespace NzbWebDAV.Clients.RadarrSonarr;public class ArrClient(string host, string apiKey){+ protected static readonly HttpClient HttpClient = new HttpClient();+public string Host { get; } = host;private string ApiKey { get; } = apiKey;private const string BasePath = "/api/v3";@@ -52,23 +54,25 @@ public class ArrClient(string host, string apiKey)protected async Task<T> GetRoot<T>(string rootPath){- using var httpClient = GetHttpClient();- await using var response = await httpClient.GetStreamAsync($"{Host}{rootPath}");- return await JsonSerializer.DeserializeAsync<T>(response) ?? throw new NullReferenceException();+ var request = new HttpRequestMessage(HttpMethod.Get, $"{Host}{rootPath}");+ using var response = await SendAsync(request);+ await using var stream = await response.Content.ReadAsStreamAsync();+ return await JsonSerializer.DeserializeAsync<T>(stream) ?? throw new NullReferenceException();}protected async Task<T> Post<T>(string path, object body){- using var httpClient = GetHttpClient();- using var response = await httpClient.PostAsJsonAsync(GetRequestUri(path), body);+ var request = new HttpRequestMessage(HttpMethod.Post, GetRequestUri(path));+ request.Content = new StringContent(JsonSerializer.Serialize(body));+ using var response = await SendAsync(request);await using var stream = await response.Content.ReadAsStreamAsync();return await JsonSerializer.DeserializeAsync<T>(stream) ?? throw new NullReferenceException();}protected async Task<HttpStatusCode> Delete(string path, Dictionary<string, string>? queryParams = null){- using var httpClient = GetHttpClient();- using var response = await httpClient.DeleteAsync(GetRequestUri(path, queryParams));+ var request = new HttpRequestMessage(HttpMethod.Delete, GetRequestUri(path, queryParams));+ using var response = await SendAsync(request);return response.StatusCode;}@@ -82,10 +86,9 @@ public class ArrClient(string host, string apiKey)return resource;}- private HttpClient GetHttpClient()+ private Task<HttpResponseMessage> SendAsync(HttpRequestMessage request){- var httpClient = new HttpClient();- httpClient.DefaultRequestHeaders.Add("X-Api-Key", ApiKey);- return httpClient;+ request.Headers.Add("X-Api-Key", ApiKey);+ return HttpClient.SendAsync(request);}}\ No newline at end of filediff --git a/backend/Clients/Usenet/CachingNntpClient.cs b/backend/Clients/Usenet/CachingNntpClient.csindex 36e45c7c..c05c990d 100644--- a/backend/Clients/Usenet/CachingNntpClient.cs+++ b/backend/Clients/Usenet/CachingNntpClient.cs@@ -7,8 +7,6 @@ namespace NzbWebDAV.Clients.Usenet;public class CachingNntpClient(INntpClient client, MemoryCache cache) : WrappingNntpClient(client){- private readonly INntpClient _client = client;-private readonly MemoryCacheEntryOptions _cacheOptions = new(){Size = 1,@@ -23,7 +21,7 @@ public class CachingNntpClient(INntpClient client, MemoryCache cache) : Wrapping){var cacheKey = segmentId;- var stream = await _client.GetSegmentStreamAsync(segmentId, includeHeaders, ct);+ var stream = await Client.GetSegmentStreamAsync(segmentId, includeHeaders, ct).ConfigureAwait(false);cache.Set(cacheKey, stream.Header, _cacheOptions);return stream;}@@ -34,14 +32,14 @@ public class CachingNntpClient(INntpClient client, MemoryCache cache) : Wrappingreturn (await cache.GetOrCreateAsync(cacheKey, cacheEntry =>{cacheEntry.SetOptions(_cacheOptions);- return _client.GetSegmentYencHeaderAsync(segmentId, ct);- })!)!;+ return Client.GetSegmentYencHeaderAsync(segmentId, ct);+ }).ConfigureAwait(false))!;}public override async Task<long> GetFileSizeAsync(NzbFile file, CancellationToken ct){if (file.Segments.Count == 0) return 0;- var header = await GetSegmentYencHeaderAsync(file.Segments[^1].MessageId, ct);+ var header = await GetSegmentYencHeaderAsync(file.Segments[^1].MessageId.Value, ct).ConfigureAwait(false);return header.PartOffset + header.PartSize;}}\ No newline at end of filediff --git a/backend/Clients/Usenet/Connections/CombinedSemaphoreSlim.cs b/backend/Clients/Usenet/Connections/CombinedSemaphoreSlim.csnew file mode 100644index 00000000..a02a7671--- /dev/null+++ b/backend/Clients/Usenet/Connections/CombinedSemaphoreSlim.cs@@ -0,0 +1,34 @@+namespace NzbWebDAV.Clients.Usenet.Connections+{+ public sealed class CombinedSemaphoreSlim(int maxCount, ExtendedSemaphoreSlim pooledSemaphore): IDisposable+ {+ private readonly SemaphoreSlim _semaphore = new(maxCount, maxCount);++ public int RemainingSemaphoreSlots => _semaphore.CurrentCount;++ public async Task WaitAsync(int requiredAvailable, CancellationToken cancellationToken)+ {+ await _semaphore.WaitAsync(cancellationToken);+ try+ {+ await pooledSemaphore.WaitAsync(requiredAvailable, cancellationToken);+ }+ catch (Exception)+ {+ _semaphore.Release();+ throw;+ }+ }++ public void Release()+ {+ _semaphore.Release();+ pooledSemaphore.Release();+ }++ public void Dispose()+ {+ _semaphore.Dispose();+ }+ }+}\ No newline at end of filediff --git a/backend/Clients/Usenet/Connections/ConnectionLock.cs b/backend/Clients/Usenet/Connections/ConnectionLock.csindex e2c6d555..e14bbd54 100644--- a/backend/Clients/Usenet/Connections/ConnectionLock.cs+++ b/backend/Clients/Usenet/Connections/ConnectionLock.cs@@ -6,28 +6,24 @@ namespace NzbWebDAV.Clients.Usenet.Connections;////// Note: This class was authored by ChatGPT 3o/// </summary>-public sealed class ConnectionLock<T> : IDisposable, IAsyncDisposable+public sealed class ConnectionLock<T> : IDisposable{- private readonly Action<T> _syncReturn;- private readonly Func<T, ValueTask>? _asyncReturn;- private readonly Action<T> _syncDestroy;- private readonly Func<T, ValueTask>? _asyncDestroy;- private T? _connection;- private int _disposed; // 0 == false, 1 == true- private int _replace; // 0 == false, 1 == true+ private readonly Action<T> _syncReturn;+ private readonly Action<T> _syncDestroy;+ private T? _connection;+ private int _disposed; // 0 == false, 1 == true+ private int _replace; // 0 == false, 1 == true- internal ConnectionLock(- T connection,- Action<T> syncReturn,- Func<T,ValueTask>? asyncReturn = null,- Action<T>? syncDestroy = null,- Func<T,ValueTask>? asyncDestroy = null)+ internal ConnectionLock+ (+ T connection,+ Action<T> syncReturn,+ Action<T> syncDestroy+ ){- _connection = connection;- _syncReturn = syncReturn;- _asyncReturn = asyncReturn;- _syncDestroy = syncDestroy ?? (_ => { /* no-op fallback */ });- _asyncDestroy = asyncDestroy; // may be null; will fall back to _syncDestroy+ _connection = connection;+ _syncReturn = syncReturn;+ _syncDestroy = syncDestroy;}public T Connection@@ -44,7 +40,7 @@ public sealed class ConnectionLock<T> : IDisposable, IAsyncDisposablepublic void Dispose(){- if (Interlocked.Exchange(ref _disposed, 1) == 1) return; // already done+ if (Interlocked.Exchange(ref _disposed, 1) == 1) return; // already donevar conn = Interlocked.Exchange(ref _connection, default);if (conn is not null){@@ -54,31 +50,7 @@ public sealed class ConnectionLock<T> : IDisposable, IAsyncDisposableelse_syncReturn(conn);}- GC.SuppressFinalize(this);- }- public async ValueTask DisposeAsync()- {- if (Interlocked.Exchange(ref _disposed, 1) == 1) return;- var conn = Interlocked.Exchange(ref _connection, default);- if (conn is not null)- {- var replace = Volatile.Read(ref _replace) == 1;- if (replace)- {- if (_asyncDestroy is not null)- await _asyncDestroy(conn).ConfigureAwait(false);- else- _syncDestroy(conn);- }- else- {- if (_asyncReturn is not null)- await _asyncReturn(conn).ConfigureAwait(false);- else- _syncReturn(conn);- }- }GC.SuppressFinalize(this);}}\ No newline at end of filediff --git a/backend/Clients/Usenet/Connections/ConnectionPool.cs b/backend/Clients/Usenet/Connections/ConnectionPool.csindex 3b2c1b83..c4145bc5 100644--- a/backend/Clients/Usenet/Connections/ConnectionPool.cs+++ b/backend/Clients/Usenet/Connections/ConnectionPool.cs@@ -22,7 +22,13 @@ public sealed class ConnectionPool<T> : IDisposable, IAsyncDisposable/* -------------------------------- configuration -------------------------------- */public TimeSpan IdleTimeout { get; }- public event EventHandler<ConnectionPoolChangedEventArgs>? OnConnectionPoolChanged;+ public int LiveConnections => _live;+ public int IdleConnections => _idleConnections.Count;+ public int ActiveConnections => _live - _idleConnections.Count;+ public int AvailableConnections => _maxConnections - ActiveConnections;+ public int RemainingSemaphoreSlots => _gate.RemainingSemaphoreSlots;++ public event EventHandler<ConnectionPoolStats.ConnectionPoolChangedEventArgs>? OnConnectionPoolChanged;private readonly Func<CancellationToken, ValueTask<T>> _factory;private readonly int _maxConnections;@@ -30,7 +36,7 @@ public sealed class ConnectionPool<T> : IDisposable, IAsyncDisposable/* --------------------------------- state --------------------------------------- */private readonly ConcurrentStack<Pooled> _idleConnections = new();- private readonly ExtendedSemaphoreSlim _gate;+ private readonly CombinedSemaphoreSlim _gate;private readonly CancellationTokenSource _sweepCts = new();private readonly Task _sweeperTask; // keeps timer alive@@ -41,6 +47,7 @@ public sealed class ConnectionPool<T> : IDisposable, IAsyncDisposablepublic ConnectionPool(int maxConnections,+ ExtendedSemaphoreSlim pooledSemaphore,Func<CancellationToken, ValueTask<T>> connectionFactory,TimeSpan? idleTimeout = null){@@ -52,7 +59,7 @@ public sealed class ConnectionPool<T> : IDisposable, IAsyncDisposableIdleTimeout = idleTimeout ?? TimeSpan.FromSeconds(30);_maxConnections = maxConnections;- _gate = new ExtendedSemaphoreSlim(maxConnections, maxConnections);+ _gate = new CombinedSemaphoreSlim(maxConnections, pooledSemaphore);_sweeperTask = Task.Run(SweepLoop); // background idle-reaper}@@ -66,9 +73,7 @@ public sealed class ConnectionPool<T> : IDisposable, IAsyncDisposablepublic async Task<ConnectionLock<T>> GetConnectionLockAsync(CancellationToken cancellationToken = default){- var reservedCount = cancellationToken.GetContext<ReservedConnectionsContext>().Count;- if (reservedCount < 0 || reservedCount > _maxConnections)- reservedCount = 0;+ var reservedCount = cancellationToken.GetContext<ReservedPooledConnectionsContext>().Count;// Make caller cancellation also cancel the wait on the gate.using var linked = CancellationTokenSource.CreateLinkedTokenSource(@@ -115,7 +120,7 @@ public sealed class ConnectionPool<T> : IDisposable, IAsyncDisposablereturn BuildLock(conn);ConnectionLock<T> BuildLock(T c)- => new ConnectionLock<T>(c, Return, ReturnAsync, Destroy, DestroyAsync);+ => new(c, Return, Destroy);static void ThrowDisposed()=> throw new ObjectDisposedException(nameof(ConnectionPool<T>));@@ -148,12 +153,6 @@ public sealed class ConnectionPool<T> : IDisposable, IAsyncDisposableTriggerConnectionPoolChangedEvent();}- private ValueTask ReturnAsync(T connection)- {- Return(connection);- return ValueTask.CompletedTask;- }-private void Destroy(T connection){// When a lock requests replacement, we dispose the connection instead of reusing.@@ -163,24 +162,13 @@ public sealed class ConnectionPool<T> : IDisposable, IAsyncDisposable{_gate.Release();}- TriggerConnectionPoolChangedEvent();- }- private ValueTask DestroyAsync(T connection)- {- _ = DisposeConnectionAsync(connection); // fire & forget- Interlocked.Decrement(ref _live);- if (Volatile.Read(ref _disposed) == 0)- {- _gate.Release();- }TriggerConnectionPoolChangedEvent();- return ValueTask.CompletedTask;}private void TriggerConnectionPoolChangedEvent(){- OnConnectionPoolChanged?.Invoke(this, new ConnectionPoolChangedEventArgs(+ OnConnectionPoolChanged?.Invoke(this, new ConnectionPoolStats.ConnectionPoolChangedEventArgs(_live,_idleConnections.Count,_maxConnections@@ -268,8 +256,7 @@ public sealed class ConnectionPool<T> : IDisposable, IAsyncDisposableawait DisposeConnectionAsync(item.Connection).ConfigureAwait(false);_sweepCts.Dispose();- // Intentionally NOT disposing _gate: outstanding handles may still try- // to Release(). A SemaphoreSlim with no waiters is effectively inert.+ _gate.Dispose();GC.SuppressFinalize(this);}@@ -279,12 +266,4 @@ public sealed class ConnectionPool<T> : IDisposable, IAsyncDisposable{_ = DisposeAsync().AsTask(); // fire-and-forget synchronous path}-- public sealed class ConnectionPoolChangedEventArgs(int live, int idle, int max) : EventArgs- {- public int Live { get; } = live;- public int Idle { get; } = idle;- public int Max { get; } = max;- public int Active => Live - Idle;- }}\ No newline at end of filediff --git a/backend/Clients/Usenet/Connections/ConnectionPoolStats.cs b/backend/Clients/Usenet/Connections/ConnectionPoolStats.csnew file mode 100644index 00000000..76336a02--- /dev/null+++ b/backend/Clients/Usenet/Connections/ConnectionPoolStats.cs@@ -0,0 +1,60 @@+using NzbWebDAV.Config;+using NzbWebDAV.Models;+using NzbWebDAV.Websocket;++namespace NzbWebDAV.Clients.Usenet.Connections;++public class ConnectionPoolStats+{+ private readonly int[] _live;+ private readonly int[] _idle;+ private readonly int _max;+ private int _totalLive;+ private int _totalIdle;+ private readonly UsenetProviderConfig _providerConfig;+ private readonly WebsocketManager _websocketManager;++ public ConnectionPoolStats(UsenetProviderConfig providerConfig, WebsocketManager websocketManager)+ {+ var count = providerConfig.Providers.Count;+ _live = new int[count];+ _idle = new int[count];+ _max = providerConfig.Providers+ .Where(x => x.Type == ProviderType.Pooled)+ .Select(x => x.MaxConnections)+ .Sum();++ _providerConfig = providerConfig;+ _websocketManager = websocketManager;+ }++ public EventHandler<ConnectionPoolChangedEventArgs> GetOnConnectionPoolChanged(int providerIndex)+ {+ return OnEvent;++ void OnEvent(object? _, ConnectionPoolChangedEventArgs args)+ {+ if (_providerConfig.Providers[providerIndex].Type == ProviderType.Pooled)+ {+ lock (this)+ {+ _live[providerIndex] = args.Live;+ _idle[providerIndex] = args.Idle;+ _totalLive = _live.Sum();+ _totalIdle = _idle.Sum();+ }+ }++ var message = $"{providerIndex}|{args.Live}|{args.Idle}|{_totalLive}|{_max}|{_totalIdle}";+ _websocketManager.SendMessage(WebsocketTopic.UsenetConnections, message);+ }+ }++ public sealed class ConnectionPoolChangedEventArgs(int live, int idle, int max) : EventArgs+ {+ public int Live { get; } = live;+ public int Idle { get; } = idle;+ public int Max { get; } = max;+ public int Active => Live - Idle;+ }+}\ No newline at end of filediff --git a/backend/Clients/Usenet/Connections/LastSuccessfulProviderContext.cs b/backend/Clients/Usenet/Connections/LastSuccessfulProviderContext.csnew file mode 100644index 00000000..75566629--- /dev/null+++ b/backend/Clients/Usenet/Connections/LastSuccessfulProviderContext.cs@@ -0,0 +1,6 @@+namespace NzbWebDAV.Clients.Usenet.Connections;++public class LastSuccessfulProviderContext+{+ public MultiConnectionNntpClient? Provider;+}\ No newline at end of filediff --git a/backend/Clients/Usenet/Connections/ReservedConnectionsContext.cs b/backend/Clients/Usenet/Connections/ReservedConnectionsContext.csdeleted file mode 100644index 918dc6dd..00000000--- a/backend/Clients/Usenet/Connections/ReservedConnectionsContext.cs+++ /dev/null@@ -1,6 +0,0 @@-namespace NzbWebDAV.Clients.Usenet.Connections;--public readonly struct ReservedConnectionsContext(int reservedCount)-{- public int Count => reservedCount;-}\ No newline at end of filediff --git a/backend/Clients/Usenet/Connections/ReservedPooledConnectionsContext.cs b/backend/Clients/Usenet/Connections/ReservedPooledConnectionsContext.csnew file mode 100644index 00000000..83c04a7d--- /dev/null+++ b/backend/Clients/Usenet/Connections/ReservedPooledConnectionsContext.cs@@ -0,0 +1,6 @@+namespace NzbWebDAV.Clients.Usenet.Connections;++public readonly struct ReservedPooledConnectionsContext(int reservedCount)+{+ public readonly int Count = Math.Max(reservedCount, 0);+}\ No newline at end of filediff --git a/backend/Clients/Usenet/MultiConnectionNntpClient.cs b/backend/Clients/Usenet/MultiConnectionNntpClient.csindex af28a536..fb438bb1 100644--- a/backend/Clients/Usenet/MultiConnectionNntpClient.cs+++ b/backend/Clients/Usenet/MultiConnectionNntpClient.cs@@ -1,5 +1,6 @@using NzbWebDAV.Clients.Usenet.Connections;using NzbWebDAV.Clients.Usenet.Models;+using NzbWebDAV.Models;using NzbWebDAV.Streams;using NzbWebDAV.Utils;using Usenet.Exceptions;@@ -9,8 +10,15 @@ using Usenet.Yenc;namespace NzbWebDAV.Clients.Usenet;-public class MultiConnectionNntpClient(ConnectionPool<INntpClient> connectionPool) : INntpClient+public class MultiConnectionNntpClient(ConnectionPool<INntpClient> connectionPool, ProviderType type) : INntpClient{+ public ProviderType ProviderType { get; } = type;+ public int LiveConnections => _connectionPool.LiveConnections;+ public int IdleConnections => _connectionPool.IdleConnections;+ public int ActiveConnections => _connectionPool.ActiveConnections;+ public int AvailableConnections => _connectionPool.AvailableConnections;+ public int RemainingSemaphoreSlots => _connectionPool.RemainingSemaphoreSlots;+private ConnectionPool<INntpClient> _connectionPool = connectionPool;public Task<bool> ConnectAsync(string host, int port, bool useSsl, CancellationToken cancellationToken)@@ -35,17 +43,22 @@ public class MultiConnectionNntpClient(ConnectionPool<INntpClient> connectionPoopublic Task<UsenetArticleHeaders> GetArticleHeadersAsync(string segmentId, CancellationToken cancellationToken){- return RunWithConnection(connection => connection.GetArticleHeadersAsync(segmentId, cancellationToken), cancellationToken);+ return RunWithConnection(connection => connection.GetArticleHeadersAsync(segmentId, cancellationToken),+ cancellationToken);}- public Task<YencHeaderStream> GetSegmentStreamAsync(string segmentId, bool includeHeaders, CancellationToken cancellationToken)+ public Task<YencHeaderStream> GetSegmentStreamAsync(string segmentId, bool includeHeaders,+ CancellationToken cancellationToken){- return RunWithConnection(connection => connection.GetSegmentStreamAsync(segmentId, includeHeaders, cancellationToken), cancellationToken);+ return RunWithConnection(+ connection => connection.GetSegmentStreamAsync(segmentId, includeHeaders, cancellationToken),+ cancellationToken);}public Task<YencHeader> GetSegmentYencHeaderAsync(string segmentId, CancellationToken cancellationToken){- return RunWithConnection(connection => connection.GetSegmentYencHeaderAsync(segmentId, cancellationToken), cancellationToken);+ return RunWithConnection(connection => connection.GetSegmentYencHeaderAsync(segmentId, cancellationToken),+ cancellationToken);}public Task<long> GetFileSizeAsync(NzbFile file, CancellationToken cancellationToken)@@ -55,7 +68,8 @@ public class MultiConnectionNntpClient(ConnectionPool<INntpClient> connectionPoopublic async Task WaitForReady(CancellationToken cancellationToken){- await using var connectionLock = await _connectionPool.GetConnectionLockAsync(cancellationToken);+ using var connectionLock =+ await _connectionPool.GetConnectionLockAsync(cancellationToken).ConfigureAwait(false);}private async Task<T> RunWithConnection<T>@@ -65,36 +79,35 @@ public class MultiConnectionNntpClient(ConnectionPool<INntpClient> connectionPooint retries = 1){- var connectionLock = await _connectionPool.GetConnectionLockAsync(cancellationToken);+ var connectionLock = await _connectionPool.GetConnectionLockAsync(cancellationToken).ConfigureAwait(false);+ var isDisposed = false;try{- var result = await task(connectionLock.Connection);-- // we only want to release the connection-lock once the underlying connection is ready again.- // ReSharper disable once MethodSupportsCancellation- // we intentionally do not pass the cancellation token to ContinueWith,- // since we want the continuation to always run.- _ = connectionLock.Connection.WaitForReady(SigtermUtil.GetCancellationToken())- .ContinueWith(_ => connectionLock.Dispose());- return result;+ return await task(connectionLock.Connection).ConfigureAwait(false);}- catch (NntpException e)+ catch (NntpException){// we want to replace the underlying connection in cases of NntpExceptions.connectionLock.Replace();connectionLock.Dispose();+ isDisposed = true;// and try again with a new connection (max 1 retry)if (retries > 0)- return await RunWithConnection<T>(task, cancellationToken, retries - 1);+ return await RunWithConnection<T>(task, cancellationToken, retries - 1).ConfigureAwait(false);throw;}- catch (Exception e)+ finally{- // we also want to release the connection-lock if there was any error getting the result.- connectionLock.Dispose();- throw;+ // we only want to release the connection-lock once the underlying connection is ready again.+ //+ // ReSharper disable once MethodSupportsCancellation+ // we intentionally do not pass the cancellation token to ContinueWith,+ // since we want the continuation to always run.+ if (!isDisposed)+ _ = connectionLock.Connection.WaitForReady(SigtermUtil.GetCancellationToken())+ .ContinueWith(_ => connectionLock.Dispose());}}diff --git a/backend/Clients/Usenet/MultiProviderNntpClient.cs b/backend/Clients/Usenet/MultiProviderNntpClient.csnew file mode 100644index 00000000..d676f43e--- /dev/null+++ b/backend/Clients/Usenet/MultiProviderNntpClient.cs@@ -0,0 +1,132 @@+using System.Runtime.ExceptionServices;+using NzbWebDAV.Clients.Usenet.Connections;+using NzbWebDAV.Clients.Usenet.Models;+using NzbWebDAV.Exceptions;+using NzbWebDAV.Extensions;+using NzbWebDAV.Models;+using NzbWebDAV.Streams;+using Serilog;+using Usenet.Nntp.Responses;+using Usenet.Nzb;+using Usenet.Yenc;++namespace NzbWebDAV.Clients.Usenet;++public class MultiProviderNntpClient(List<MultiConnectionNntpClient> providers) : INntpClient+{+ public Task<bool> ConnectAsync(string host, int port, bool useSsl, CancellationToken cancellationToken)+ {+ throw new NotSupportedException("Please connect within the connectionFactory");+ }++ public Task<bool> AuthenticateAsync(string user, string pass, CancellationToken cancellationToken)+ {+ throw new NotSupportedException("Please authenticate within the connectionFactory");+ }++ public Task<NntpStatResponse> StatAsync(string segmentId, CancellationToken cancellationToken)+ {+ return RunFromPoolWithBackup(connection => connection.StatAsync(segmentId, cancellationToken),+ cancellationToken);+ }++ public Task<NntpDateResponse> DateAsync(CancellationToken cancellationToken)+ {+ return RunFromPoolWithBackup(connection => connection.DateAsync(cancellationToken), cancellationToken);+ }++ public Task<UsenetArticleHeaders> GetArticleHeadersAsync(string segmentId, CancellationToken cancellationToken)+ {+ return RunFromPoolWithBackup(connection => connection.GetArticleHeadersAsync(segmentId, cancellationToken),+ cancellationToken);+ }++ public Task<YencHeaderStream> GetSegmentStreamAsync(string segmentId, bool includeHeaders,+ CancellationToken cancellationToken)+ {+ return RunFromPoolWithBackup(+ connection => connection.GetSegmentStreamAsync(segmentId, includeHeaders, cancellationToken),+ cancellationToken);+ }++ public Task<YencHeader> GetSegmentYencHeaderAsync(string segmentId, CancellationToken cancellationToken)+ {+ return RunFromPoolWithBackup(connection => connection.GetSegmentYencHeaderAsync(segmentId, cancellationToken),+ cancellationToken);+ }++ public Task<long> GetFileSizeAsync(NzbFile file, CancellationToken cancellationToken)+ {+ return RunFromPoolWithBackup(connection => connection.GetFileSizeAsync(file, cancellationToken),+ cancellationToken);+ }++ public Task WaitForReady(CancellationToken cancellationToken)+ {+ return Task.CompletedTask;+ }++ private async Task<T> RunFromPoolWithBackup<T>+ (+ Func<INntpClient, Task<T>> task,+ CancellationToken cancellationToken+ )+ {+ ExceptionDispatchInfo? lastException = null;+ var lastSuccessfulProviderContext = cancellationToken.GetContext<LastSuccessfulProviderContext>();+ var lastSuccessfulProvider = lastSuccessfulProviderContext?.Provider;+ var orderedProviders = GetOrderedProviders(lastSuccessfulProvider);+ T? result = default;+ foreach (var provider in orderedProviders)+ {+ cancellationToken.ThrowIfCancellationRequested();++ if (lastException is not null && lastException.SourceException is not UsenetArticleNotFoundException)+ {+ var msg = lastException.SourceException.Message;+ Log.Debug($"Encountered error during NNTP Operation: `{msg}`. Trying another provider.");+ }++ try+ {+ result = await task.Invoke(provider).ConfigureAwait(false);+ if (result is NntpStatResponse r && r.ResponseType != NntpStatResponseType.ArticleExists)+ throw new UsenetArticleNotFoundException(r.MessageId.Value);++ if (lastSuccessfulProviderContext is not null && lastSuccessfulProvider != provider)+ lastSuccessfulProviderContext.Provider = provider;+ return result;+ }+ catch (Exception e) when (e is not OperationCanceledException and not TaskCanceledException)+ {+ lastException = ExceptionDispatchInfo.Capture(e);+ }+ }++ if (result is NntpStatResponse)+ return result;++ lastException?.Throw();+ throw new Exception("There are no usenet providers configured.");+ }++ private IEnumerable<MultiConnectionNntpClient> GetOrderedProviders(MultiConnectionNntpClient? preferredProvider)+ {+ return providers+ .Where(x => x.ProviderType != ProviderType.Disabled)+ .OrderBy(x => x.ProviderType)+ .ThenByDescending(x => x.IdleConnections)+ .ThenByDescending(x => x.RemainingSemaphoreSlots)+ .Prepend(preferredProvider)+ .Where(x => x is not null)+ .Select(x => x!)+ .Distinct();+ }++ public void Dispose()+ {+ foreach (var provider in providers)+ provider.Dispose();+ GC.SuppressFinalize(this);+ }+}\ No newline at end of filediff --git a/backend/Clients/Usenet/ThreadSafeNntpClient.cs b/backend/Clients/Usenet/ThreadSafeNntpClient.csindex 262682c8..92a3d050 100644--- a/backend/Clients/Usenet/ThreadSafeNntpClient.cs+++ b/backend/Clients/Usenet/ThreadSafeNntpClient.cs@@ -59,7 +59,7 @@ public class ThreadSafeNntpClient : INntpClientCancellationToken cancellationToken){- await _semaphore.WaitAsync(cancellationToken);+ await _semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);return await Task.Run(() =>{try@@ -82,25 +82,27 @@ public class ThreadSafeNntpClient : INntpClient_semaphore.Release();throw;}- });+ }).ConfigureAwait(false);}public async Task<YencHeader> GetSegmentYencHeaderAsync(string segmentId, CancellationToken cancellationToken){- await using var stream = await GetSegmentStreamAsync(new NntpMessageId(segmentId), false, cancellationToken);+ await using var stream = await GetSegmentStreamAsync(new NntpMessageId(segmentId), false, cancellationToken)+ .ConfigureAwait(false);return stream.Header;}public async Task<long> GetFileSizeAsync(NzbFile file, CancellationToken cancellationToken){if (file.Segments.Count == 0) return 0;- var header = await GetSegmentYencHeaderAsync(file.Segments[^1].MessageId.Value, cancellationToken);+ var header = await GetSegmentYencHeaderAsync(file.Segments[^1].MessageId.Value, cancellationToken)+ .ConfigureAwait(false);return header.PartOffset + header.PartSize;}public async Task WaitForReady(CancellationToken cancellationToken){- await _semaphore.WaitAsync(cancellationToken);+ await _semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);_semaphore.Release();}@@ -111,10 +113,10 @@ public class ThreadSafeNntpClient : INntpClientprivate async Task<T> Synchronized<T>(Func<Task<T>> run, CancellationToken cancellationToken){- await _semaphore.WaitAsync(cancellationToken);+ await _semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);try{- return await run();+ return await run().ConfigureAwait(false);}finally{diff --git a/backend/Clients/Usenet/UsenetStreamingClient.cs b/backend/Clients/Usenet/UsenetStreamingClient.csindex 8c3b0398..ea5cb325 100644--- a/backend/Clients/Usenet/UsenetStreamingClient.cs+++ b/backend/Clients/Usenet/UsenetStreamingClient.cs@@ -1,4 +1,5 @@-using Microsoft.Extensions.Caching.Memory;+using System.Text.Json;+using Microsoft.Extensions.Caching.Memory;using NzbWebDAV.Clients.Usenet.Connections;using NzbWebDAV.Clients.Usenet.Models;using NzbWebDAV.Config;@@ -13,7 +14,7 @@ namespace NzbWebDAV.Clients.Usenet;public class UsenetStreamingClient{- private readonly INntpClient _client;+ private readonly CachingNntpClient _client;private readonly WebsocketManager _websocketManager;public UsenetStreamingClient(ConfigManager configManager, WebsocketManager websocketManager)@@ -22,41 +23,23 @@ public class UsenetStreamingClient_websocketManager = websocketManager;// get connection settings from config-manager- var host = configManager.GetConfigValue("usenet.host") ?? string.Empty;- var port = int.Parse(configManager.GetConfigValue("usenet.port") ?? "119");- var useSsl = bool.Parse(configManager.GetConfigValue("usenet.use-ssl") ?? "false");- var user = configManager.GetConfigValue("usenet.user") ?? string.Empty;- var pass = configManager.GetConfigValue("usenet.pass") ?? string.Empty;- var connections = configManager.GetMaxConnections();+ var providerConfig = configManager.GetUsenetProviderConfig();// initialize the nntp-client- var createNewConnection = (CancellationToken ct) => CreateNewConnection(host, port, useSsl, user, pass, ct);- var connectionPool = CreateNewConnectionPool(connections, createNewConnection);- var multiConnectionClient = new MultiConnectionNntpClient(connectionPool);+ var multiProviderClient = CreateMultiProviderClient(providerConfig);var cache = new MemoryCache(new MemoryCacheOptions() { SizeLimit = 8192 });- _client = new CachingNntpClient(multiConnectionClient, cache);+ _client = new CachingNntpClient(multiProviderClient, cache);// when config changes, update the connection-poolconfigManager.OnConfigChanged += (_, configEventArgs) =>{// if unrelated config changed, do nothing- if (!configEventArgs.ChangedConfig.ContainsKey("usenet.host") &&- !configEventArgs.ChangedConfig.ContainsKey("usenet.port") &&- !configEventArgs.ChangedConfig.ContainsKey("usenet.use-ssl") &&- !configEventArgs.ChangedConfig.ContainsKey("usenet.user") &&- !configEventArgs.ChangedConfig.ContainsKey("usenet.pass") &&- !configEventArgs.ChangedConfig.ContainsKey("usenet.connections")) return;+ if (!configEventArgs.ChangedConfig.TryGetValue("usenet.providers", out var rawConfig)) return;// update the connection-pool according to the new config- var connectionCount = int.Parse(configEventArgs.NewConfig["usenet.connections"]);- var newHost = configEventArgs.NewConfig["usenet.host"];- var newPort = int.Parse(configEventArgs.NewConfig["usenet.port"]);- var newUseSsl = bool.Parse(configEventArgs.NewConfig.GetValueOrDefault("usenet.use-ssl", "false"));- var newUser = configEventArgs.NewConfig["usenet.user"];- var newPass = configEventArgs.NewConfig["usenet.pass"];- var newConnectionPool = CreateNewConnectionPool(connectionCount, cancellationToken =>- CreateNewConnection(newHost, newPort, newUseSsl, newUser, newPass, cancellationToken));- multiConnectionClient.UpdateConnectionPool(newConnectionPool);+ var newProviderConfig = JsonSerializer.Deserialize<UsenetProviderConfig>(rawConfig);+ var newMultiProviderClient = CreateMultiProviderClient(newProviderConfig!);+ _client.UpdateUnderlyingClient(newMultiProviderClient);};}@@ -69,22 +52,23 @@ public class UsenetStreamingClient){using var childCt = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);- using var _ = childCt.Token.SetScopedContext(cancellationToken.GetContext<object>());+ using var _1 = childCt.Token.SetScopedContext(cancellationToken.GetContext<ReservedPooledConnectionsContext>());+ using var _2 = childCt.Token.SetScopedContext(cancellationToken.GetContext<LastSuccessfulProviderContext>());var token = childCt.Token;var tasks = segmentIds.Select(async x => (SegmentId: x,- Result: await _client.StatAsync(x, token)+ Result: await _client.StatAsync(x, token).ConfigureAwait(false))).WithConcurrencyAsync(concurrency);var processed = 0;- await foreach (var task in tasks)+ await foreach (var task in tasks.ConfigureAwait(false)){progress?.Report(++processed);if (task.Result.ResponseType == NntpStatResponseType.ArticleExists) continue;- await childCt.CancelAsync();+ await childCt.CancelAsync().ConfigureAwait(false);throw new UsenetArticleNotFoundException(task.SegmentId);}}@@ -92,7 +76,7 @@ public class UsenetStreamingClientpublic async Task<NzbFileStream> GetFileStream(NzbFile nzbFile, int concurrentConnections, CancellationToken ct){var segmentIds = nzbFile.GetSegmentIds();- var fileSize = await _client.GetFileSizeAsync(nzbFile, cancellationToken: ct);+ var fileSize = await _client.GetFileSizeAsync(nzbFile, ct).ConfigureAwait(false);return new NzbFileStream(segmentIds, fileSize, _client, concurrentConnections);}@@ -124,36 +108,64 @@ public class UsenetStreamingClientprivate ConnectionPool<INntpClient> CreateNewConnectionPool(int maxConnections,- Func<CancellationToken, ValueTask<INntpClient>> connectionFactory+ ExtendedSemaphoreSlim pooledSemaphore,+ Func<CancellationToken, ValueTask<INntpClient>> connectionFactory,+ EventHandler<ConnectionPoolStats.ConnectionPoolChangedEventArgs> onConnectionPoolChanged){- var connectionPool = new ConnectionPool<INntpClient>(maxConnections, connectionFactory);- connectionPool.OnConnectionPoolChanged += OnConnectionPoolChanged;- var args = new ConnectionPool<INntpClient>.ConnectionPoolChangedEventArgs(0, 0, maxConnections);- OnConnectionPoolChanged(connectionPool, args);+ var connectionPool = new ConnectionPool<INntpClient>(maxConnections, pooledSemaphore, connectionFactory);+ connectionPool.OnConnectionPoolChanged += onConnectionPoolChanged;+ var args = new ConnectionPoolStats.ConnectionPoolChangedEventArgs(0, 0, maxConnections);+ onConnectionPoolChanged(connectionPool, args);return connectionPool;}- private void OnConnectionPoolChanged(object? _, ConnectionPool<INntpClient>.ConnectionPoolChangedEventArgs args)+ private MultiProviderNntpClient CreateMultiProviderClient(UsenetProviderConfig providerConfig){- var message = $"{args.Live}|{args.Max}|{args.Idle}";- _websocketManager.SendMessage(WebsocketTopic.UsenetConnections, message);+ var connectionPoolStats = new ConnectionPoolStats(providerConfig, _websocketManager);+ var totalPooledConnectionCount = providerConfig.TotalPooledConnections;+ var pooledSemaphore = new ExtendedSemaphoreSlim(totalPooledConnectionCount, totalPooledConnectionCount);+ var providerClients = providerConfig.Providers+ .Select((provider, index) => CreateProviderClient(+ provider,+ connectionPoolStats.GetOnConnectionPoolChanged(index),+ pooledSemaphore+ ))+ .ToList();+ return new MultiProviderNntpClient(providerClients);+ }++ private MultiConnectionNntpClient CreateProviderClient+ (+ UsenetProviderConfig.ConnectionDetails connectionDetails,+ EventHandler<ConnectionPoolStats.ConnectionPoolChangedEventArgs> onConnectionPoolChanged,+ ExtendedSemaphoreSlim pooledSemaphore+ )+ {+ var connectionPool = CreateNewConnectionPool(+ maxConnections: connectionDetails.MaxConnections,+ pooledSemaphore: pooledSemaphore,+ connectionFactory: ct => CreateNewConnection(connectionDetails, ct),+ onConnectionPoolChanged+ );+ return new MultiConnectionNntpClient(connectionPool, connectionDetails.Type);}public static async ValueTask<INntpClient> CreateNewConnection(- string host,- int port,- bool useSsl,- string user,- string pass,+ UsenetProviderConfig.ConnectionDetails connectionDetails,CancellationToken cancellationToken){var connection = new ThreadSafeNntpClient();- if (!await connection.ConnectAsync(host, port, useSsl, cancellationToken))+ var host = connectionDetails.Host;+ var port = connectionDetails.Port;+ var useSsl = connectionDetails.UseSsl;+ var user = connectionDetails.User;+ var pass = connectionDetails.Pass;+ if (!await connection.ConnectAsync(host, port, useSsl, cancellationToken).ConfigureAwait(false))throw new CouldNotConnectToUsenetException("Could not connect to usenet host. Check connection settings.");- if (!await connection.AuthenticateAsync(user, pass, cancellationToken))+ if (!await connection.AuthenticateAsync(user, pass, cancellationToken).ConfigureAwait(false))throw new CouldNotLoginToUsenetException("Could not login to usenet host. Check username and password.");return connection;}diff --git a/backend/Clients/Usenet/WrappingNntpClient.cs b/backend/Clients/Usenet/WrappingNntpClient.csindex e6a790e2..7ca4145b 100644--- a/backend/Clients/Usenet/WrappingNntpClient.cs+++ b/backend/Clients/Usenet/WrappingNntpClient.cs@@ -8,29 +8,31 @@ namespace NzbWebDAV.Clients.Usenet;public abstract class WrappingNntpClient(INntpClient client) : INntpClient{+ protected INntpClient Client = client;+public virtual Task<bool> ConnectAsync(string host, int port, bool useSsl, CancellationToken cancellationToken){- return client.ConnectAsync(host, port, useSsl, cancellationToken);+ return Client.ConnectAsync(host, port, useSsl, cancellationToken);}public virtual Task<bool> AuthenticateAsync(string user, string pass, CancellationToken cancellationToken){- return client.AuthenticateAsync(user, pass, cancellationToken);+ return Client.AuthenticateAsync(user, pass, cancellationToken);}public virtual Task<NntpStatResponse> StatAsync(string segmentId, CancellationToken cancellationToken){- return client.StatAsync(segmentId, cancellationToken);+ return Client.StatAsync(segmentId, cancellationToken);}public virtual Task<NntpDateResponse> DateAsync(CancellationToken cancellationToken){- return client.DateAsync(cancellationToken);+ return Client.DateAsync(cancellationToken);}public Task<UsenetArticleHeaders> GetArticleHeadersAsync(string segmentId, CancellationToken cancellationToken){- return client.GetArticleHeadersAsync(segmentId, cancellationToken);+ return Client.GetArticleHeadersAsync(segmentId, cancellationToken);}public virtual Task<YencHeaderStream> GetSegmentStreamAsync@@ -40,27 +42,34 @@ public abstract class WrappingNntpClient(INntpClient client) : INntpClientCancellationToken cancellationToken){- return client.GetSegmentStreamAsync(segmentId, includeHeaders, cancellationToken);+ return Client.GetSegmentStreamAsync(segmentId, includeHeaders, cancellationToken);}public virtual Task<YencHeader> GetSegmentYencHeaderAsync(string segmentId, CancellationToken cancellationToken){- return client.GetSegmentYencHeaderAsync(segmentId, cancellationToken);+ return Client.GetSegmentYencHeaderAsync(segmentId, cancellationToken);}public virtual Task<long> GetFileSizeAsync(NzbFile file, CancellationToken cancellationToken){- return client.GetFileSizeAsync(file, cancellationToken);+ return Client.GetFileSizeAsync(file, cancellationToken);}public virtual Task WaitForReady(CancellationToken cancellationToken){- return client.WaitForReady(cancellationToken);+ return Client.WaitForReady(cancellationToken);+ }++ public void UpdateUnderlyingClient(INntpClient client)+ {+ var oldClient = Client;+ Client = client;+ oldClient.Dispose();}public void Dispose(){- client.Dispose();+ Client.Dispose();GC.SuppressFinalize(this);}}\ No newline at end of filediff --git a/backend/Config/ConfigManager.cs b/backend/Config/ConfigManager.csindex df0f8be0..91b50de9 100644--- a/backend/Config/ConfigManager.cs+++ b/backend/Config/ConfigManager.cs@@ -14,7 +14,7 @@ public class ConfigManagerpublic async Task LoadConfig(){await using var dbContext = new DavDatabaseContext();- var configItems = await dbContext.ConfigItems.ToListAsync();+ var configItems = await dbContext.ConfigItems.ToListAsync().ConfigureAwait(false);lock (_config){_config.Clear();@@ -90,14 +90,6 @@ public class ConfigManager?? "uncategorized";}- public int GetMaxConnections()- {- return int.Parse(- StringUtil.EmptyToNull(GetConfigValue("usenet.connections"))- ?? "50"- );- }-public int GetConnectionsPerStream(){return int.Parse(@@ -110,7 +102,8 @@ public class ConfigManagerpublic string? GetWebdavUser(){return StringUtil.EmptyToNull(GetConfigValue("webdav.user"))- ?? StringUtil.EmptyToNull(Environment.GetEnvironmentVariable("WEBDAV_USER"));+ ?? StringUtil.EmptyToNull(Environment.GetEnvironmentVariable("WEBDAV_USER"))+ ?? "admin";}public string? GetWebdavPasswordHash()@@ -145,7 +138,7 @@ public class ConfigManager{return int.Parse(StringUtil.EmptyToNull(GetConfigValue("api.max-queue-connections"))- ?? GetMaxConnections().ToString()+ ?? GetUsenetProviderConfig().TotalPooledConnections.ToString());}@@ -181,7 +174,7 @@ public class ConfigManager{return int.Parse(StringUtil.EmptyToNull(GetConfigValue("repair.connections"))- ?? GetMaxConnections().ToString()+ ?? GetUsenetProviderConfig().TotalPooledConnections.ToString());}@@ -202,6 +195,12 @@ public class ConfigManagerreturn GetConfigValue<ArrConfig>("arr.instances") ?? defaultValue;}+ public UsenetProviderConfig GetUsenetProviderConfig()+ {+ var defaultValue = new UsenetProviderConfig();+ return GetConfigValue<UsenetProviderConfig>("usenet.providers") ?? defaultValue;+ }+public string GetDuplicateNzbBehavior(){var defaultValue = "increment";diff --git a/backend/Config/UsenetProviderConfig.cs b/backend/Config/UsenetProviderConfig.csnew file mode 100644index 00000000..0b048bf1--- /dev/null+++ b/backend/Config/UsenetProviderConfig.cs@@ -0,0 +1,24 @@+using NzbWebDAV.Models;++namespace NzbWebDAV.Config;++public class UsenetProviderConfig+{+ public List<ConnectionDetails> Providers { get; set; } = [];++ public int TotalPooledConnections => Math.Max(1, Providers+ .Where(x => x.Type == ProviderType.Pooled)+ .Select(x => x.MaxConnections)+ .Sum());++ public class ConnectionDetails+ {+ public required ProviderType Type { get; set; }+ public required string Host { get; set; }+ public required int Port { get; set; }+ public required bool UseSsl { get; set; }+ public required string User { get; set; }+ public required string Pass { get; set; }+ public required int MaxConnections { get; set; }+ }+}\ No newline at end of filediff --git a/backend/Database/DavDatabaseClient.cs b/backend/Database/DavDatabaseClient.csindex 6e975977..a3a15f3a 100644--- a/backend/Database/DavDatabaseClient.cs+++ b/backend/Database/DavDatabaseClient.cs@@ -39,7 +39,7 @@ public sealed class DavDatabaseClient(DavDatabaseContext ctx){if (dirId == DavItem.Root.Id){- return await Ctx.Items.SumAsync(x => x.FileSize, ct) ?? 0;+ return await Ctx.Items.SumAsync(x => x.FileSize, ct).ConfigureAwait(false) ?? 0;}const string sql = @"@@ -58,21 +58,21 @@ public sealed class DavDatabaseClient(DavDatabaseContext ctx)FROM RecursiveChildren;";var connection = Ctx.Database.GetDbConnection();- if (connection.State != System.Data.ConnectionState.Open) await connection.OpenAsync(ct);+ if (connection.State != System.Data.ConnectionState.Open) await connection.OpenAsync(ct).ConfigureAwait(false);await using var command = connection.CreateCommand();command.CommandText = sql;var parameter = command.CreateParameter();parameter.ParameterName = "@parentId";parameter.Value = dirId;command.Parameters.Add(parameter);- var result = await command.ExecuteScalarAsync(ct);+ var result = await command.ExecuteScalarAsync(ct).ConfigureAwait(false);return Convert.ToInt64(result);}// nzbfilepublic async Task<DavNzbFile?> GetNzbFileAsync(Guid id, CancellationToken ct = default){- return await ctx.NzbFiles.FirstOrDefaultAsync(x => x.Id == id, ct);+ return await ctx.NzbFiles.FirstOrDefaultAsync(x => x.Id == id, ct).ConfigureAwait(false);}// queue@@ -88,9 +88,9 @@ public sealed class DavDatabaseClient(DavDatabaseContext ctx).Where(q => q.PauseUntil == null || nowTime >= q.PauseUntil).Skip(0).Take(1)- .FirstOrDefaultAsync(ct);+ .FirstOrDefaultAsync(ct).ConfigureAwait(false);var queueNzbContents = queueItem != null- ? await Ctx.QueueNzbContents.FirstOrDefaultAsync(q => q.Id == queueItem.Id, ct)+ ? await Ctx.QueueNzbContents.FirstOrDefaultAsync(q => q.Id == queueItem.Id, ct).ConfigureAwait(false): null;return (queueItem, queueNzbContents);}@@ -126,13 +126,13 @@ public sealed class DavDatabaseClient(DavDatabaseContext ctx){await Ctx.QueueItems.Where(x => ids.Contains(x.Id))- .ExecuteDeleteAsync(ct);+ .ExecuteDeleteAsync(ct).ConfigureAwait(false);}// historypublic async Task<HistoryItem?> GetHistoryItemAsync(string id){- return await Ctx.HistoryItems.FirstOrDefaultAsync(x => x.Id == Guid.Parse(id));+ return await Ctx.HistoryItems.FirstOrDefaultAsync(x => x.Id == Guid.Parse(id)).ConfigureAwait(false);}public async Task RemoveHistoryItemsAsync(List<Guid> ids, bool deleteFiles, CancellationToken ct = default)@@ -144,12 +144,12 @@ public sealed class DavDatabaseClient(DavDatabaseContext ctx).Where(h => ids.Contains(h.Id) && h.DownloadDirId != null).Select(h => h.DownloadDirId!).Contains(d.Id))- .ExecuteDeleteAsync(ct);+ .ExecuteDeleteAsync(ct).ConfigureAwait(false);}await Ctx.HistoryItems.Where(x => ids.Contains(x.Id))- .ExecuteDeleteAsync(ct);+ .ExecuteDeleteAsync(ct).ConfigureAwait(false);}private class FileSizeResult@@ -174,7 +174,7 @@ public sealed class DavDatabaseClient(DavDatabaseContext ctx)RepairStatus = g.Key.RepairStatus,Count = g.Select(r => r.Count).Sum(),})- .ToListAsync(ct);+ .ToListAsync(ct).ConfigureAwait(false);}// completed-symlinks@@ -188,6 +188,6 @@ public sealed class DavDatabaseClient(DavDatabaseContext ctx)join davItem in Ctx.Items on historyItem.DownloadDirId equals davItem.Idwhere davItem.Type == DavItem.ItemType.Directoryselect davItem;- return await query.Distinct().ToListAsync(ct);+ return await query.Distinct().ToListAsync(ct).ConfigureAwait(false);}}\ No newline at end of filediff --git a/backend/Database/Migrations/20251113081523_Populate-Usenet-Providers-Config.Designer.cs b/backend/Database/Migrations/20251113081523_Populate-Usenet-Providers-Config.Designer.csnew file mode 100644index 00000000..1a017e38--- /dev/null+++ b/backend/Database/Migrations/20251113081523_Populate-Usenet-Providers-Config.Designer.cs@@ -0,0 +1,386 @@+// <auto-generated />+using System;+using Microsoft.EntityFrameworkCore;+using Microsoft.EntityFrameworkCore.Infrastructure;+using Microsoft.EntityFrameworkCore.Migrations;+using Microsoft.EntityFrameworkCore.Storage.ValueConversion;+using NzbWebDAV.Database;++#nullable disable++namespace NzbWebDAV.Database.Migrations+{+ [DbContext(typeof(DavDatabaseContext))]+ [Migration("20251113081523_Populate-Usenet-Providers-Config")]+ partial class PopulateUsenetProvidersConfig+ {+ /// <inheritdoc />+ protected override void BuildTargetModel(ModelBuilder modelBuilder)+ {+#pragma warning disable 612, 618+ modelBuilder.HasAnnotation("ProductVersion", "9.0.4");++ modelBuilder.Entity("NzbWebDAV.Database.Models.Account", b =>+ {+ b.Property<int>("Type")+ .HasColumnType("INTEGER");++ b.Property<string>("Username")+ .HasMaxLength(255)+ .HasColumnType("TEXT");++ b.Property<string>("PasswordHash")+ .IsRequired()+ .HasColumnType("TEXT");++ b.Property<string>("RandomSalt")+ .IsRequired()+ .HasColumnType("TEXT");++ b.HasKey("Type", "Username");++ b.ToTable("Accounts", (string)null);+ });++ modelBuilder.Entity("NzbWebDAV.Database.Models.ConfigItem", b =>+ {+ b.Property<string>("ConfigName")+ .HasColumnType("TEXT");++ b.Property<string>("ConfigValue")+ .IsRequired()+ .HasColumnType("TEXT");++ b.HasKey("ConfigName");++ b.ToTable("ConfigItems", (string)null);+ });++ modelBuilder.Entity("NzbWebDAV.Database.Models.DavItem", b =>+ {+ b.Property<Guid>("Id")+ .HasColumnType("TEXT");++ b.Property<DateTime>("CreatedAt")+ .HasColumnType("TEXT");++ b.Property<long?>("FileSize")+ .HasColumnType("INTEGER");++ b.Property<string>("IdPrefix")+ .IsRequired()+ .HasColumnType("TEXT");++ b.Property<long?>("LastHealthCheck")+ .HasColumnType("INTEGER");++ b.Property<string>("Name")+ .IsRequired()+ .HasMaxLength(255)+ .HasColumnType("TEXT");++ b.Property<long?>("NextHealthCheck")+ .HasColumnType("INTEGER");++ b.Property<Guid?>("ParentId")+ .HasColumnType("TEXT");++ b.Property<string>("Path")+ .IsRequired()+ .HasColumnType("TEXT");++ b.Property<long?>("ReleaseDate")+ .HasColumnType("INTEGER");++ b.Property<int>("Type")+ .HasColumnType("INTEGER");++ b.HasKey("Id");++ b.HasIndex("IdPrefix", "Type");++ b.HasIndex("ParentId", "Name")+ .IsUnique();++ b.HasIndex("Type", "NextHealthCheck", "ReleaseDate", "Id");++ b.ToTable("DavItems", (string)null);+ });++ modelBuilder.Entity("NzbWebDAV.Database.Models.DavMultipartFile", b =>+ {+ b.Property<Guid>("Id")+ .HasColumnType("TEXT");++ b.Property<string>("Metadata")+ .IsRequired()+ .HasColumnType("TEXT");++ b.HasKey("Id");++ b.ToTable("DavMultipartFiles", (string)null);+ });++ modelBuilder.Entity("NzbWebDAV.Database.Models.DavNzbFile", b =>+ {+ b.Property<Guid>("Id")+ .HasColumnType("TEXT");++ b.Property<string>("SegmentIds")+ .IsRequired()+ .HasColumnType("TEXT");++ b.HasKey("Id");++ b.ToTable("DavNzbFiles", (string)null);+ });++ modelBuilder.Entity("NzbWebDAV.Database.Models.DavRarFile", b =>+ {+ b.Property<Guid>("Id")+ .HasColumnType("TEXT");++ b.Property<string>("RarParts")+ .IsRequired()+ .HasColumnType("TEXT");++ b.HasKey("Id");++ b.ToTable("DavRarFiles", (string)null);+ });++ modelBuilder.Entity("NzbWebDAV.Database.Models.HealthCheckResult", b =>+ {+ b.Property<Guid>("Id")+ .HasColumnType("TEXT");++ b.Property<long>("CreatedAt")+ .HasColumnType("INTEGER");++ b.Property<Guid>("DavItemId")+ .HasColumnType("TEXT");++ b.Property<string>("Message")+ .HasColumnType("TEXT");++ b.Property<string>("Path")+ .IsRequired()+ .HasColumnType("TEXT");++ b.Property<int>("RepairStatus")+ .HasColumnType("INTEGER");++ b.Property<int>("Result")+ .HasColumnType("INTEGER");++ b.HasKey("Id");++ b.HasIndex("CreatedAt");++ b.HasIndex("DavItemId")+ .HasFilter("\"RepairStatus\" = 3");++ b.HasIndex("Result", "RepairStatus", "CreatedAt");++ b.ToTable("HealthCheckResults", (string)null);+ });++ modelBuilder.Entity("NzbWebDAV.Database.Models.HealthCheckStat", b =>+ {+ b.Property<long>("DateStartInclusive")+ .HasColumnType("INTEGER");++ b.Property<long>("DateEndExclusive")+ .HasColumnType("INTEGER");++ b.Property<int>("Result")+ .HasColumnType("INTEGER");++ b.Property<int>("RepairStatus")+ .HasColumnType("INTEGER");++ b.Property<int>("Count")+ .HasColumnType("INTEGER");++ b.HasKey("DateStartInclusive", "DateEndExclusive", "Result", "RepairStatus");++ b.ToTable("HealthCheckStats", (string)null);+ });++ modelBuilder.Entity("NzbWebDAV.Database.Models.HistoryItem", b =>+ {+ b.Property<Guid>("Id")+ .HasColumnType("TEXT");++ b.Property<string>("Category")+ .IsRequired()+ .HasColumnType("TEXT");++ b.Property<DateTime>("CreatedAt")+ .HasColumnType("TEXT");++ b.Property<Guid?>("DownloadDirId")+ .HasColumnType("TEXT");++ b.Property<int>("DownloadStatus")+ .HasColumnType("INTEGER");++ b.Property<int>("DownloadTimeSeconds")+ .HasColumnType("INTEGER");++ b.Property<string>("FailMessage")+ .HasColumnType("TEXT");++ b.Property<string>("FileName")+ .IsRequired()+ .HasColumnType("TEXT");++ b.Property<string>("JobName")+ .IsRequired()+ .HasColumnType("TEXT");++ b.Property<long>("TotalSegmentBytes")+ .HasColumnType("INTEGER");++ b.HasKey("Id");++ b.HasIndex("Category");++ b.HasIndex("CreatedAt");++ b.HasIndex("Category", "CreatedAt");++ b.HasIndex("Category", "DownloadDirId");++ b.ToTable("HistoryItems", (string)null);+ });++ modelBuilder.Entity("NzbWebDAV.Database.Models.QueueItem", b =>+ {+ b.Property<Guid>("Id")+ .HasColumnType("TEXT");++ b.Property<string>("Category")+ .IsRequired()+ .HasColumnType("TEXT");++ b.Property<DateTime>("CreatedAt")+ .HasColumnType("TEXT");++ b.Property<string>("FileName")+ .IsRequired()+ .HasColumnType("TEXT");++ b.Property<string>("JobName")+ .IsRequired()+ .HasColumnType("TEXT");++ b.Property<long>("NzbFileSize")+ .HasColumnType("INTEGER");++ b.Property<DateTime?>("PauseUntil")+ .HasColumnType("TEXT");++ b.Property<int>("PostProcessing")+ .HasColumnType("INTEGER");++ b.Property<int>("Priority")+ .HasColumnType("INTEGER");++ b.Property<long>("TotalSegmentBytes")+ .HasColumnType("INTEGER");++ b.HasKey("Id");++ b.HasIndex("Category");++ b.HasIndex("CreatedAt");++ b.HasIndex("FileName")+ .IsUnique();++ b.HasIndex("Priority");++ b.HasIndex("Priority", "CreatedAt");++ b.HasIndex("Category", "Priority", "CreatedAt");++ b.ToTable("QueueItems", (string)null);+ });++ modelBuilder.Entity("NzbWebDAV.Database.Models.QueueNzbContents", b =>+ {+ b.Property<Guid>("Id")+ .HasColumnType("TEXT");++ b.Property<string>("NzbContents")+ .IsRequired()+ .HasColumnType("TEXT");++ b.HasKey("Id");++ b.ToTable("QueueNzbContents", (string)null);+ });++ modelBuilder.Entity("NzbWebDAV.Database.Models.DavItem", b =>+ {+ b.HasOne("NzbWebDAV.Database.Models.DavItem", "Parent")+ .WithMany("Children")+ .HasForeignKey("ParentId")+ .OnDelete(DeleteBehavior.Cascade);++ b.Navigation("Parent");+ });++ modelBuilder.Entity("NzbWebDAV.Database.Models.DavMultipartFile", b =>+ {+ b.HasOne("NzbWebDAV.Database.Models.DavItem", "DavItem")+ .WithOne()+ .HasForeignKey("NzbWebDAV.Database.Models.DavMultipartFile", "Id")+ .OnDelete(DeleteBehavior.Cascade)+ .IsRequired();++ b.Navigation("DavItem");+ });++ modelBuilder.Entity("NzbWebDAV.Database.Models.DavNzbFile", b =>+ {+ b.HasOne("NzbWebDAV.Database.Models.DavItem", "DavItem")+ .WithOne()+ .HasForeignKey("NzbWebDAV.Database.Models.DavNzbFile", "Id")+ .OnDelete(DeleteBehavior.Cascade)+ .IsRequired();++ b.Navigation("DavItem");+ });++ modelBuilder.Entity("NzbWebDAV.Database.Models.DavRarFile", b =>+ {+ b.HasOne("NzbWebDAV.Database.Models.DavItem", "DavItem")+ .WithOne()+ .HasForeignKey("NzbWebDAV.Database.Models.DavRarFile", "Id")+ .OnDelete(DeleteBehavior.Cascade)+ .IsRequired();++ b.Navigation("DavItem");+ });++ modelBuilder.Entity("NzbWebDAV.Database.Models.QueueNzbContents", b =>+ {+ b.HasOne("NzbWebDAV.Database.Models.QueueItem", "QueueItem")+ .WithOne()+ .HasForeignKey("NzbWebDAV.Database.Models.QueueNzbContents", "Id")+ .OnDelete(DeleteBehavior.Cascade)+ .IsRequired();++ b.Navigation("QueueItem");+ });++ modelBuilder.Entity("NzbWebDAV.Database.Models.DavItem", b =>+ {+ b.Navigation("Children");+ });+#pragma warning restore 612, 618+ }+ }+}diff --git a/backend/Database/Migrations/20251113081523_Populate-Usenet-Providers-Config.cs b/backend/Database/Migrations/20251113081523_Populate-Usenet-Providers-Config.csnew file mode 100644index 00000000..8a6d0e22--- /dev/null+++ b/backend/Database/Migrations/20251113081523_Populate-Usenet-Providers-Config.cs@@ -0,0 +1,57 @@+using Microsoft.EntityFrameworkCore.Migrations;++#nullable disable++namespace NzbWebDAV.Database.Migrations+{+ /// <inheritdoc />+ public partial class PopulateUsenetProvidersConfig : Migration+ {+ /// <inheritdoc />+ protected override void Up(MigrationBuilder migrationBuilder)+ {+ migrationBuilder.Sql("""+ WITH existing AS (+ SELECT+ NULLIF(TRIM((SELECT "ConfigValue" FROM "ConfigItems" WHERE "ConfigName" = 'usenet.host')), '') AS host,+ NULLIF(TRIM((SELECT "ConfigValue" FROM "ConfigItems" WHERE "ConfigName" = 'usenet.port')), '') AS port,+ NULLIF(TRIM((SELECT "ConfigValue" FROM "ConfigItems" WHERE "ConfigName" = 'usenet.use-ssl')), '') AS use_ssl,+ COALESCE((SELECT "ConfigValue" FROM "ConfigItems" WHERE "ConfigName" = 'usenet.user'), '') AS user,+ COALESCE((SELECT "ConfigValue" FROM "ConfigItems" WHERE "ConfigName" = 'usenet.pass'), '') AS pass,+ NULLIF(TRIM((SELECT "ConfigValue" FROM "ConfigItems" WHERE "ConfigName" = 'usenet.connections')), '') AS connections+ )+ INSERT INTO "ConfigItems" ("ConfigName", "ConfigValue")+ SELECT+ 'usenet.providers',+ '{"Providers":[{"Type":1,"Host":"' ||+ replace(replace(host, '\', '\\'), '"', '\"') ||+ '","Port":' || CAST(COALESCE(port, '119') AS INTEGER) ||+ ',"UseSsl":' ||+ CASE+ WHEN use_ssl IS NOT NULL AND LOWER(use_ssl) IN ('1','true','t','yes','y','on') THEN 'true'+ ELSE 'false'+ END ||+ ',"User":"' || replace(replace(COALESCE(user, ''), '\', '\\'), '"', '\"') ||+ '","Pass":"' || replace(replace(COALESCE(pass, ''), '\', '\\'), '"', '\"') ||+ '","MaxConnections":' || CAST(COALESCE(connections, '50') AS INTEGER) ||+ '}]}'+ FROM existing+ WHERE host IS NOT NULL+ AND NOT EXISTS (+ SELECT 1+ FROM "ConfigItems"+ WHERE "ConfigName" = 'usenet.providers'+ );+ """);+ }++ /// <inheritdoc />+ protected override void Down(MigrationBuilder migrationBuilder)+ {+ migrationBuilder.Sql("""+ DELETE FROM "ConfigItems"+ WHERE "ConfigName" = 'usenet.providers';+ """);+ }+ }+}diff --git a/backend/Extensions/CancellationTokenExtensions.cs b/backend/Extensions/CancellationTokenExtensions.csindex 6aa1efec..65c4a39b 100644--- a/backend/Extensions/CancellationTokenExtensions.cs+++ b/backend/Extensions/CancellationTokenExtensions.cs@@ -4,24 +4,32 @@ namespace NzbWebDAV.Extensions;public static class CancellationTokenExtensions{- private static readonly ConcurrentDictionary<CancellationToken, object?> Context = new();+ private static readonly ConcurrentDictionary<LookupKey, object?> Context = new();public static CancellationTokenScopedContext SetScopedContext<T>(this CancellationToken ct, T? value){- Context[ct] = value;- return new CancellationTokenScopedContext(ct);+ var lookupKey = new LookupKey() { CancellationToken = ct, Type = typeof(T) };+ Context[lookupKey] = value;+ return new CancellationTokenScopedContext(lookupKey, value);}public static T? GetContext<T>(this CancellationToken ct){- return Context.TryGetValue(ct, out var result) && result is T context ? context : default;+ var lookupKey = new LookupKey() { CancellationToken = ct, Type = typeof(T) };+ return Context.TryGetValue(lookupKey, out var result) && result is T context ? context : default;}- public class CancellationTokenScopedContext(CancellationToken ct) : IDisposable+ public class CancellationTokenScopedContext(LookupKey lookupKey, object? value) : IDisposable{public void Dispose(){- Context.Remove(ct, out _);+ Context.Remove(lookupKey, out _);}}++ public record struct LookupKey+ {+ public CancellationToken CancellationToken;+ public Type Type;+ }}\ No newline at end of filediff --git a/backend/Extensions/IEnumerableTaskExtensions.cs b/backend/Extensions/IEnumerableTaskExtensions.csindex cf9d3cd9..1429a057 100644--- a/backend/Extensions/IEnumerableTaskExtensions.cs+++ b/backend/Extensions/IEnumerableTaskExtensions.cs@@ -76,16 +76,16 @@ public static class IEnumerableTaskExtensions{runningTasks.Add(task);if (runningTasks.Count < concurrency) continue;- var completedTask = await Task.WhenAny(runningTasks);+ var completedTask = await Task.WhenAny(runningTasks).ConfigureAwait(false);runningTasks.Remove(completedTask);- yield return await completedTask;+ yield return await completedTask.ConfigureAwait(false);}while (runningTasks.Count > 0){- var completedTask = await Task.WhenAny(runningTasks);+ var completedTask = await Task.WhenAny(runningTasks).ConfigureAwait(false);runningTasks.Remove(completedTask);- yield return await completedTask;+ yield return await completedTask.ConfigureAwait(false);}}}\ No newline at end of filediff --git a/backend/Middlewares/ExceptionMiddleware.cs b/backend/Middlewares/ExceptionMiddleware.csindex 1cc7b8af..a210b76b 100644--- a/backend/Middlewares/ExceptionMiddleware.cs+++ b/backend/Middlewares/ExceptionMiddleware.cs@@ -2,6 +2,7 @@using NWebDav.Server.Helpers;using NzbWebDAV.Database.Models;using NzbWebDAV.Exceptions;+using NzbWebDAV.Utils;using Serilog;namespace NzbWebDAV.Middlewares;@@ -12,16 +13,16 @@ public class ExceptionMiddleware(RequestDelegate next){try{- await next(context);+ await next(context).ConfigureAwait(false);}- catch (OperationCanceledException) when (context.RequestAborted.IsCancellationRequested)+ catch (Exception e) when (IsCausedByAbortedRequest(e, context)){// If the response has not started, we can write our custom responseif (!context.Response.HasStarted){context.Response.Clear();context.Response.StatusCode = 499; // Non-standard status code for client closed request- await context.Response.WriteAsync("Client closed request.");+ await context.Response.WriteAsync("Client closed request.").ConfigureAwait(false);}}catch (UsenetArticleNotFoundException e)@@ -56,10 +57,20 @@ public class ExceptionMiddleware(RequestDelegate next)}var filePath = GetRequestFilePath(context);- Log.Error($"File `{filePath}` could not be read due to unhandled {e.GetType()}: {e.Message}");+ var seekPosition = context.Request.GetRange()?.Start?.ToString() ?? "0";+ Log.Error($"File `{filePath}` could not be read from byte position: {seekPosition} " ++ $"due to unhandled {e.GetType()}: {e.Message}");}}+ private bool IsCausedByAbortedRequest(Exception e, HttpContext context)+ {+ var isAffectedException = e is OperationCanceledException or EndOfStreamException;+ var isRequestAborted = context.RequestAborted.IsCancellationRequested ||+ SigtermUtil.GetCancellationToken().IsCancellationRequested;+ return isAffectedException && isRequestAborted;+ }+private static string GetRequestFilePath(HttpContext context){return context.Items["DavItem"] is DavItem davItemdiff --git a/backend/Models/ProviderType.cs b/backend/Models/ProviderType.csnew file mode 100644index 00000000..a6aa5817--- /dev/null+++ b/backend/Models/ProviderType.cs@@ -0,0 +1,9 @@+namespace NzbWebDAV.Models;++public enum ProviderType+{+ Disabled = 0,+ Pooled = 1,+ BackupAndStats = 2,+ BackupOnly = 3,+}\ No newline at end of filediff --git a/backend/Par2Recovery/Packets/Par2Packet.cs b/backend/Par2Recovery/Packets/Par2Packet.csindex b90634ea..c1d0bd5f 100644--- a/backend/Par2Recovery/Packets/Par2Packet.cs+++ b/backend/Par2Recovery/Packets/Par2Packet.cs@@ -21,7 +21,7 @@ namespace NzbWebDAV.Par2Recovery.Packets// Read the calculated number of bytes from the stream.var body = new byte[bodyLength];- await stream.ReadExactlyAsync(body.AsMemory(0, (int)bodyLength));+ await stream.ReadExactlyAsync(body.AsMemory(0, (int)bodyLength)).ConfigureAwait(false);// Pass the body to the further implementation for parsing.ParseBody(body);diff --git a/backend/Par2Recovery/Par2.cs b/backend/Par2Recovery/Par2.csindex 5325ddec..61e5000d 100644--- a/backend/Par2Recovery/Par2.cs+++ b/backend/Par2Recovery/Par2.cs@@ -26,7 +26,7 @@ namespace NzbWebDAV.Par2Recovery{try{- packet = await ReadPacketAsync(stream);+ packet = await ReadPacketAsync(stream).ConfigureAwait(false);}catch (Exception e){@@ -44,7 +44,7 @@ namespace NzbWebDAV.Par2Recoveryprivate static async Task<Par2Packet> ReadPacketAsync(Stream stream){// Read a Packet Header.- var header = await ReadStructAsync<Par2PacketHeader>(stream);+ var header = await ReadStructAsync<Par2PacketHeader>(stream).ConfigureAwait(false);// Test if the magic constant matches.var magic = Encoding.ASCII.GetString(header.Magic);@@ -65,7 +65,7 @@ namespace NzbWebDAV.Par2Recovery}// Let the packet type parse more of the stream as needed.- await result.ReadAsync(stream);+ await result.ReadAsync(stream).ConfigureAwait(false);return result;}diff --git a/backend/Program.cs b/backend/Program.csindex 8904bc47..4b6da8c5 100644--- a/backend/Program.cs+++ b/backend/Program.cs@@ -28,9 +28,11 @@ class Programstatic async Task Main(string[] args){// Update thread-pool- ThreadPool.GetMaxThreads(out var maxWorker, out var maxIo);- ThreadPool.SetMaxThreads(maxWorker, Math.Max(maxIo, 2000));- ThreadPool.SetMinThreads(100, 200);+ var coreCount = Environment.ProcessorCount;+ var minThreads = Math.Max(coreCount * 2, 50); // 2x cores, minimum 50+ var maxThreads = Math.Max(coreCount * 50, 1000); // 50x cores, minimum 1000+ ThreadPool.SetMinThreads(minThreads, minThreads);+ ThreadPool.SetMaxThreads(maxThreads, maxThreads);// Initialize loggervar defaultLevel = LogEventLevel.Information;@@ -55,13 +57,13 @@ class Program{var argIndex = args.ToList().IndexOf("--db-migration");var targetMigration = args.Length > argIndex + 1 ? args[argIndex + 1] : null;- await databaseContext.Database.MigrateAsync(targetMigration, SigtermUtil.GetCancellationToken());+ await databaseContext.Database.MigrateAsync(targetMigration, SigtermUtil.GetCancellationToken()).ConfigureAwait(false);return;}// initialize the config-managervar configManager = new ConfigManager();- await configManager.LoadConfig();+ await configManager.LoadConfig().ConfigureAwait(false);// initialize websocket-managervar websocketManager = new WebsocketManager();@@ -110,6 +112,6 @@ class Programapp.UseWebdavBasicAuthentication();app.UseNWebDav();app.Lifetime.ApplicationStopping.Register(SigtermUtil.Cancel);- await app.RunAsync();+ await app.RunAsync().ConfigureAwait(false);}}\ No newline at end of filediff --git a/backend/Queue/DeobfuscationSteps/1.FetchFirstSegment/FetchFirstSegmentsStep.cs b/backend/Queue/DeobfuscationSteps/1.FetchFirstSegment/FetchFirstSegmentsStep.csindex 2c714e57..bd8a96eb 100644--- a/backend/Queue/DeobfuscationSteps/1.FetchFirstSegment/FetchFirstSegmentsStep.cs+++ b/backend/Queue/DeobfuscationSteps/1.FetchFirstSegment/FetchFirstSegmentsStep.cs@@ -24,7 +24,7 @@ public static class FetchFirstSegmentsStep.Where(x => x.Segments.Count > 0).Select(x => FetchFirstSegment(x, client, cancellationToken)).WithConcurrencyAsync(configManager.GetMaxQueueConnections())- .GetAllAsync(cancellationToken, progress);+ .GetAllAsync(cancellationToken, progress).ConfigureAwait(false);}private static async Task<NzbFileWithFirstSegment> FetchFirstSegment@@ -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, true, cancellationToken);+ await using var stream = await client.GetSegmentStreamAsync(firstSegment, true, cancellationToken).ConfigureAwait(false);// read up to the first 16KB from the streamvar totalRead = 0;@@ -46,7 +46,7 @@ public static class FetchFirstSegmentsStepwhile (totalRead < buffer.Length){var read = await stream.ReadAsync(buffer.AsMemory(totalRead, buffer.Length - totalRead),- cancellationToken);+ cancellationToken).ConfigureAwait(false);if (read == 0) break;totalRead += read;}diff --git a/backend/Queue/DeobfuscationSteps/2.GetPar2FileDescriptors/GetPar2FileDescriptorsStep.cs b/backend/Queue/DeobfuscationSteps/2.GetPar2FileDescriptors/GetPar2FileDescriptorsStep.csindex c7b1697b..d62213bd 100644--- a/backend/Queue/DeobfuscationSteps/2.GetPar2FileDescriptors/GetPar2FileDescriptorsStep.cs+++ b/backend/Queue/DeobfuscationSteps/2.GetPar2FileDescriptors/GetPar2FileDescriptorsStep.cs@@ -27,9 +27,9 @@ public static class GetPar2FileDescriptorsStepvar segments = par2Index.NzbFile.GetSegmentIds();var filesize = par2Index.NzbFile.Segments.Count == 1? par2Index.Header!.PartOffset + par2Index.Header!.PartSize- : await client.GetFileSizeAsync(par2Index.NzbFile, cancellationToken);+ : await client.GetFileSizeAsync(par2Index.NzbFile, cancellationToken).ConfigureAwait(false);await using var stream = client.GetFileStream(segments, filesize, concurrentConnections: 1);- await foreach (var fileDescriptor in Par2.ReadFileDescriptions(stream, cancellationToken))+ await foreach (var fileDescriptor in Par2.ReadFileDescriptions(stream, cancellationToken).ConfigureAwait(false))fileDescriptors.Add(fileDescriptor);return fileDescriptors;}diff --git a/backend/Queue/FileProcessors/FileProcessor.cs b/backend/Queue/FileProcessors/FileProcessor.csindex 094faae9..d6c09b87 100644--- a/backend/Queue/FileProcessors/FileProcessor.cs+++ b/backend/Queue/FileProcessors/FileProcessor.cs@@ -21,7 +21,7 @@ public class FileProcessor({NzbFile = fileInfo.NzbFile,FileName = fileInfo.FileName,- FileSize = fileInfo.FileSize ?? await usenet.GetFileSizeAsync(fileInfo.NzbFile, ct),+ FileSize = fileInfo.FileSize ?? await usenet.GetFileSizeAsync(fileInfo.NzbFile, ct).ConfigureAwait(false),ReleaseDate = fileInfo.ReleaseDate,};}diff --git a/backend/Queue/FileProcessors/MultipartMkvProcessor.cs b/backend/Queue/FileProcessors/MultipartMkvProcessor.csindex b71deead..61eab86b 100644--- a/backend/Queue/FileProcessors/MultipartMkvProcessor.cs+++ b/backend/Queue/FileProcessors/MultipartMkvProcessor.cs@@ -31,7 +31,7 @@ public class MultipartMkvProcessor : BaseProcessorvar fileParts = new List<DavMultipartFile.FilePart>();foreach (var fileInfo in sortedFileInfos){- var partSize = fileInfo.FileSize ?? await _client.GetFileSizeAsync(fileInfo.NzbFile, _ct);+ var partSize = fileInfo.FileSize ?? await _client.GetFileSizeAsync(fileInfo.NzbFile, _ct).ConfigureAwait(false);fileParts.Add(new DavMultipartFile.FilePart{SegmentIds = fileInfo.NzbFile.GetSegmentIds(),diff --git a/backend/Queue/FileProcessors/RarProcessor.cs b/backend/Queue/FileProcessors/RarProcessor.csindex 40f51837..f4fe0f42 100644--- a/backend/Queue/FileProcessors/RarProcessor.cs+++ b/backend/Queue/FileProcessors/RarProcessor.cs@@ -19,8 +19,8 @@ public class RarProcessor({public override async Task<BaseProcessor.Result?> ProcessAsync(){- await using var stream = await GetNzbFileStream();- var headers = await RarUtil.GetRarHeadersAsync(stream, password, ct);+ await using var stream = await GetNzbFileStream().ConfigureAwait(false);+ var headers = await RarUtil.GetRarHeadersAsync(stream, password, ct).ConfigureAwait(false);var archiveName = GetArchiveName();var partNumber = GetPartNumber(headers);return new Result()@@ -91,7 +91,7 @@ public class RarProcessor(private async Task<NzbFileStream> GetNzbFileStream(){- var filesize = fileInfo.FileSize ?? await usenet.GetFileSizeAsync(fileInfo.NzbFile, ct);+ var filesize = fileInfo.FileSize ?? await usenet.GetFileSizeAsync(fileInfo.NzbFile, ct).ConfigureAwait(false);return usenet.GetFileStream(fileInfo.NzbFile, filesize, concurrentConnections: 1);}diff --git a/backend/Queue/FileProcessors/SevenZipProcessor.cs b/backend/Queue/FileProcessors/SevenZipProcessor.csindex 2c762667..e23f300e 100644--- a/backend/Queue/FileProcessors/SevenZipProcessor.cs+++ b/backend/Queue/FileProcessors/SevenZipProcessor.cs@@ -34,9 +34,9 @@ public class SevenZipProcessor : BaseProcessorpublic override async Task<BaseProcessor.Result?> ProcessAsync(){- var multipartFile = await GetMultipartFile();+ var multipartFile = await GetMultipartFile().ConfigureAwait(false);await using var stream = new MultipartFileStream(multipartFile, _client);- var sevenZipEntries = await SevenZipUtil.GetSevenZipEntriesAsync(stream, _archivePassword, _ct);+ var sevenZipEntries = await SevenZipUtil.GetSevenZipEntriesAsync(stream, _archivePassword, _ct).ConfigureAwait(false);if (sevenZipEntries.Any(x => x.CompressionType != CompressionType.None)){const string message = "Only uncompressed 7z files are supported.";@@ -69,7 +69,7 @@ public class SevenZipProcessor : BaseProcessorforeach (var fileInfo in sortedFileInfos){var nzbFile = fileInfo.NzbFile;- var fileSize = fileInfo.FileSize ?? await _client.GetFileSizeAsync(nzbFile, _ct);+ var fileSize = fileInfo.FileSize ?? await _client.GetFileSizeAsync(nzbFile, _ct).ConfigureAwait(false);var endExclusive = startInclusive + fileSize;fileParts.Add(new MultipartFile.FilePart(){diff --git a/backend/Queue/PostProcessors/CreateStrmFilesPostProcessor.cs b/backend/Queue/PostProcessors/CreateStrmFilesPostProcessor.csindex c90d63b1..fd90c2bc 100644--- a/backend/Queue/PostProcessors/CreateStrmFilesPostProcessor.cs+++ b/backend/Queue/PostProcessors/CreateStrmFilesPostProcessor.cs@@ -10,7 +10,7 @@ namespace NzbWebDAV.Queue.PostProcessors;public class CreateStrmFilesPostProcessor(ConfigManager configManager, DavDatabaseClient dbClient){- public void CreateStrmFiles()+ public async Task CreateStrmFilesAsync(){// Add strm files to the download dirvar videoItems = dbClient.Ctx.ChangeTracker.Entries<DavItem>()@@ -19,19 +19,20 @@ public class CreateStrmFilesPostProcessor(ConfigManager configManager, DavDataba.Where(x => x.Type != DavItem.ItemType.Directory).Where(x => FilenameUtil.IsVideoFile(x.Name));foreach (var videoItem in videoItems)- CreateStrmFile(videoItem);+ await CreateStrmFileAsync(videoItem).ConfigureAwait(false);}- private void CreateStrmFile(DavItem davItem)+ private async Task CreateStrmFileAsync(DavItem davItem){// create necessary directories if they don't already existvar strmFilePath = GetStrmFilePath(davItem);var directoryName = Path.GetDirectoryName(strmFilePath);- if (directoryName != null) Directory.CreateDirectory(directoryName);+ if (directoryName != null)+ await Task.Run(() => Directory.CreateDirectory(directoryName)).ConfigureAwait(false);// create the strm filevar targetUrl = GetStrmTargetUrl(davItem);- File.WriteAllText(strmFilePath, targetUrl);+ await File.WriteAllTextAsync(strmFilePath, targetUrl).ConfigureAwait(false);}private string GetStrmFilePath(DavItem davItem)diff --git a/backend/Queue/QueueItemProcessor.cs b/backend/Queue/QueueItemProcessor.csindex 524fbfd2..c29db63a 100644--- a/backend/Queue/QueueItemProcessor.cs+++ b/backend/Queue/QueueItemProcessor.cs@@ -43,7 +43,7 @@ public class QueueItemProcessor(// process the jobtry{- await ProcessQueueItemAsync(startTime);+ await ProcessQueueItemAsync(startTime).ConfigureAwait(false);}// When a queue-item is removed while processing,@@ -67,7 +67,7 @@ public class QueueItemProcessor(queueItem.PauseUntil = DateTime.Now.AddMinutes(1);dbClient.Ctx.QueueItems.Attach(queueItem);dbClient.Ctx.Entry(queueItem).Property(x => x.PauseUntil).IsModified = true;- await dbClient.Ctx.SaveChangesAsync();+ await dbClient.Ctx.SaveChangesAsync().ConfigureAwait(false);_ = websocketManager.SendMessage(WebsocketTopic.QueueItemStatus, $"{queueItem.Id}|Queued");}catch (Exception ex)@@ -83,7 +83,7 @@ public class QueueItemProcessor({try{- await MarkQueueItemCompleted(startTime, error: e.Message);+ await MarkQueueItemCompleted(startTime, error: e.Message).ConfigureAwait(false);}catch (Exception ex){@@ -94,7 +94,7 @@ public class QueueItemProcessor(private async Task ProcessQueueItemAsync(DateTime startTime){- var existingMountFolder = await GetMountFolder();+ var existingMountFolder = await GetMountFolder().ConfigureAwait(false);var duplicateNzbBehavior = configManager.GetDuplicateNzbBehavior();// if the mount folder already exists and setting is `marked-failed`@@ -103,18 +103,20 @@ public class QueueItemProcessor(if (isDuplicateNzb && duplicateNzbBehavior == "mark-failed"){const string error = "Duplicate nzb: the download folder for this nzb already exists.";- await MarkQueueItemCompleted(startTime, error, () => Task.FromResult(existingMountFolder));+ await MarkQueueItemCompleted(startTime, error, () => Task.FromResult(existingMountFolder)).ConfigureAwait(false);return;}// ensure we don't use more than max-queue-connections- var reservedConnections = configManager.GetMaxConnections() - configManager.GetMaxQueueConnections();- using var _ = ct.SetScopedContext(new ReservedConnectionsContext(reservedConnections));+ var providerConfig = configManager.GetUsenetProviderConfig();+ var concurrency = configManager.GetMaxQueueConnections();+ var reservedConnections = providerConfig.TotalPooledConnections - concurrency;+ using var _ = ct.SetScopedContext(new ReservedPooledConnectionsContext(reservedConnections));// read the nzb documentvar documentBytes = Encoding.UTF8.GetBytes(queueNzbContents.NzbContents);using var stream = new MemoryStream(documentBytes);- var nzb = await NzbDocument.LoadAsync(stream);+ var nzb = await NzbDocument.LoadAsync(stream).ConfigureAwait(false);var archivePassword = nzb.MetaData.GetValueOrDefault("password")?.FirstOrDefault();var nzbFiles = nzb.Files.Where(x => x.Segments.Count > 0).ToList();@@ -128,9 +130,9 @@ public class QueueItemProcessor(.Scale(50, 100).ToPercentage(nzbFiles.Count);var segments = await FetchFirstSegmentsStep.FetchFirstSegments(- nzbFiles, usenetClient, configManager, ct, part1Progress);+ nzbFiles, usenetClient, configManager, ct, part1Progress).ConfigureAwait(false);var par2FileDescriptors = await GetPar2FileDescriptorsStep.GetPar2FileDescriptors(- segments, usenetClient, ct);+ segments, usenetClient, ct).ConfigureAwait(false);var fileInfos = GetFileInfosStep.GetFileInfos(segments, par2FileDescriptors);@@ -142,8 +144,8 @@ public class QueueItemProcessor(.ToPercentage(fileProcessors.Count);var fileProcessingResultsAll = await fileProcessors.Select(x => x!.ProcessAsync())- .WithConcurrencyAsync(configManager.GetMaxQueueConnections())- .GetAllAsync(ct, part2Progress);+ .WithConcurrencyAsync(concurrency)+ .GetAllAsync(ct, part2Progress).ConfigureAwait(false);var fileProcessingResults = fileProcessingResultsAll.Where(x => x is not null).Select(x => x!)@@ -160,16 +162,15 @@ public class QueueItemProcessor(var part3Progress = progress.Offset(100).ToPercentage(articlesToCheck.Count);- var concurrency = configManager.GetMaxQueueConnections();- await usenetClient.CheckAllSegmentsAsync(articlesToCheck, concurrency, part3Progress, ct);+ await usenetClient.CheckAllSegmentsAsync(articlesToCheck, concurrency, part3Progress, ct).ConfigureAwait(false);checkedFullHealth = true;}// update the databaseawait MarkQueueItemCompleted(startTime, error: null, async () =>{- var categoryFolder = await GetOrCreateCategoryFolder();- var mountFolder = await CreateMountFolder(categoryFolder, existingMountFolder, duplicateNzbBehavior);+ var categoryFolder = await GetOrCreateCategoryFolder().ConfigureAwait(false);+ var mountFolder = await CreateMountFolder(categoryFolder, existingMountFolder, duplicateNzbBehavior).ConfigureAwait(false);new RarAggregator(dbClient, mountFolder, checkedFullHealth).UpdateDatabase(fileProcessingResults);new FileAggregator(dbClient, mountFolder, checkedFullHealth).UpdateDatabase(fileProcessingResults);new SevenZipAggregator(dbClient, mountFolder, checkedFullHealth).UpdateDatabase(fileProcessingResults);@@ -185,10 +186,10 @@ public class QueueItemProcessor(// create strm files, if necessaryif (configManager.GetImportStrategy() == "strm")- new CreateStrmFilesPostProcessor(configManager, dbClient).CreateStrmFiles();+ await new CreateStrmFilesPostProcessor(configManager, dbClient).CreateStrmFilesAsync().ConfigureAwait(false);return mountFolder;- });+ }).ConfigureAwait(false);}private IEnumerable<BaseProcessor> GetFileProcessors@@ -237,14 +238,14 @@ public class QueueItemProcessor(&& categoryFolder.ParentId == DavItem.ContentFolder.Idselect mountFolder;- return await query.FirstOrDefaultAsync(ct);+ return await query.FirstOrDefaultAsync(ct).ConfigureAwait(false);}private async Task<DavItem> GetOrCreateCategoryFolder(){// if the category item already exists, return itvar categoryFolder = await dbClient.GetDirectoryChildAsync(- DavItem.ContentFolder.Id, queueItem.Category, ct);+ DavItem.ContentFolder.Id, queueItem.Category, ct).ConfigureAwait(false);if (categoryFolder is not null)return categoryFolder;@@ -290,7 +291,7 @@ public class QueueItemProcessor(for (var i = 2; i < 100; i++){var name = $"{queueItem.JobName} ({i})";- var existingMountFolder = await dbClient.GetDirectoryChildAsync(categoryFolder.Id, name, ct);+ var existingMountFolder = await dbClient.GetDirectoryChildAsync(categoryFolder.Id, name, ct).ConfigureAwait(false);if (existingMountFolder is not null) continue;var mountFolder = DavItem.New(@@ -336,12 +337,12 @@ public class QueueItemProcessor(){dbClient.Ctx.ChangeTracker.Clear();- var mountFolder = databaseOperations != null ? await databaseOperations.Invoke() : null;+ var mountFolder = databaseOperations != null ? await databaseOperations.Invoke().ConfigureAwait(false) : null;var historyItem = CreateHistoryItem(mountFolder, startTime, error);var historySlot = GetHistoryResponse.HistorySlot.FromHistoryItem(historyItem, mountFolder, configManager);dbClient.Ctx.QueueItems.Remove(queueItem);dbClient.Ctx.HistoryItems.Add(historyItem);- await dbClient.Ctx.SaveChangesAsync(ct);+ await dbClient.Ctx.SaveChangesAsync(ct).ConfigureAwait(false);_ = websocketManager.SendMessage(WebsocketTopic.QueueItemRemoved, queueItem.Id.ToString());_ = websocketManager.SendMessage(WebsocketTopic.HistoryItemAdded, historySlot.ToJson());_ = RefreshMonitoredDownloads();@@ -353,17 +354,17 @@ public class QueueItemProcessor(.GetArrConfig().GetArrClients().Select(RefreshMonitoredDownloads);- await Task.WhenAll(tasks);+ await Task.WhenAll(tasks).ConfigureAwait(false);}private async Task RefreshMonitoredDownloads(ArrClient arrClient){try{- var downloadClients = await arrClient.GetDownloadClientsAsync();+ var downloadClients = await arrClient.GetDownloadClientsAsync().ConfigureAwait(false);if (downloadClients.All(x => x.Category != queueItem.Category)) return;- var queueCount = await arrClient.GetQueueCountAsync();- if (queueCount < 60) await arrClient.RefreshMonitoredDownloads();+ var queueCount = await arrClient.GetQueueCountAsync().ConfigureAwait(false);+ if (queueCount < 60) await arrClient.RefreshMonitoredDownloads().ConfigureAwait(false);}catch (Exception e){diff --git a/backend/Queue/QueueManager.cs b/backend/Queue/QueueManager.csindex 9df0d818..5c20fd33 100644--- a/backend/Queue/QueueManager.cs+++ b/backend/Queue/QueueManager.cs@@ -53,14 +53,14 @@ public class QueueManager : IDisposablevar inProgressId = _inProgressQueueItem?.QueueItem?.Id;if (inProgressId is not null && queueItemIds.Contains(inProgressId.Value)){- await _inProgressQueueItem!.CancellationTokenSource.CancelAsync();- await _inProgressQueueItem.ProcessingTask;+ await _inProgressQueueItem!.CancellationTokenSource.CancelAsync().ConfigureAwait(false);+ await _inProgressQueueItem.ProcessingTask.ConfigureAwait(false);_inProgressQueueItem = null;}- await dbClient.RemoveQueueItemsAsync(queueItemIds, ct);- await dbClient.Ctx.SaveChangesAsync(ct);- });+ await dbClient.RemoveQueueItemsAsync(queueItemIds, ct).ConfigureAwait(false);+ await dbClient.Ctx.SaveChangesAsync(ct).ConfigureAwait(false);+ }).ConfigureAwait(false);}private async Task ProcessQueueAsync(CancellationToken ct)@@ -72,12 +72,12 @@ public class QueueManager : IDisposable// get the next queue-item from the databaseawait using var dbContext = new DavDatabaseContext();var dbClient = new DavDatabaseClient(dbContext);- var topItem = await LockAsync(() => dbClient.GetTopQueueItem(ct));+ var topItem = await LockAsync(() => dbClient.GetTopQueueItem(ct)).ConfigureAwait(false);if (topItem.queueItem is null || topItem.queueNzbContents is null){// if we're done with the queue, wait// five seconds before checking again.- await Task.Delay(TimeSpan.FromSeconds(5), ct);+ await Task.Delay(TimeSpan.FromSeconds(5), ct).ConfigureAwait(false);continue;}@@ -88,8 +88,8 @@ public class QueueManager : IDisposable_inProgressQueueItem = BeginProcessingQueueItem(dbClient, topItem.queueItem, topItem.queueNzbContents, queueItemCancellationTokenSource);- });- await (_inProgressQueueItem?.ProcessingTask ?? Task.CompletedTask);+ }).ConfigureAwait(false);+ await (_inProgressQueueItem?.ProcessingTask ?? Task.CompletedTask).ConfigureAwait(false);}catch (Exception e){@@ -97,7 +97,7 @@ public class QueueManager : IDisposable}finally{- await LockAsync(() => { _inProgressQueueItem = null; });+ await LockAsync(() => { _inProgressQueueItem = null; }).ConfigureAwait(false);}}}@@ -136,10 +136,10 @@ public class QueueManager : IDisposableprivate async Task LockAsync(Func<Task> actionAsync){- await _semaphore.WaitAsync();+ await _semaphore.WaitAsync().ConfigureAwait(false);try{- await actionAsync();+ await actionAsync().ConfigureAwait(false);}finally{@@ -149,10 +149,10 @@ public class QueueManager : IDisposableprivate async Task<T> LockAsync<T>(Func<Task<T>> actionAsync){- await _semaphore.WaitAsync();+ await _semaphore.WaitAsync().ConfigureAwait(false);try{- return await actionAsync();+ return await actionAsync().ConfigureAwait(false);}finally{@@ -162,7 +162,7 @@ public class QueueManager : IDisposableprivate async Task LockAsync(Action action){- await _semaphore.WaitAsync();+ await _semaphore.WaitAsync().ConfigureAwait(false);try{action();diff --git a/backend/Services/ArrMonitoringService.cs b/backend/Services/ArrMonitoringService.csindex 9c8607dc..c0163c57 100644--- a/backend/Services/ArrMonitoringService.cs+++ b/backend/Services/ArrMonitoringService.cs@@ -29,7 +29,7 @@ public class ArrMonitoringServicewhile (!_cancellationToken.IsCancellationRequested){// Ensure delay runs on each iteration- await Task.Delay(TimeSpan.FromSeconds(10), _cancellationToken);+ await Task.Delay(TimeSpan.FromSeconds(10), _cancellationToken).ConfigureAwait(false);// if all queue-actions are disabled, then do nothingvar arrConfig = _configManager.GetArrConfig();@@ -38,7 +38,7 @@ public class ArrMonitoringService// otherwise, handle stuck queue items according to the configforeach (var arrClient in arrConfig.GetArrClients())- await HandleStuckQueueItems(arrConfig, arrClient);+ await HandleStuckQueueItems(arrConfig, arrClient).ConfigureAwait(false);}}@@ -46,13 +46,13 @@ public class ArrMonitoringService{try{- var queueStatus = await client.GetQueueStatusAsync();+ var queueStatus = await client.GetQueueStatusAsync().ConfigureAwait(false);if (queueStatus is { Warnings: false, UnknownWarnings: false }) return;- var queue = await client.GetQueueAsync();+ var queue = await client.GetQueueAsync().ConfigureAwait(false);var actionableStatuses = arrConfig.QueueRules.Select(x => x.Message);var stuckRecords = queue.Records.Where(x => actionableStatuses.Any(x.HasStatusMessage));foreach (var record in stuckRecords)- await HandleStuckQueueItem(record, arrConfig, client);+ await HandleStuckQueueItem(record, arrConfig, client).ConfigureAwait(false);}catch (Exception e){@@ -71,7 +71,7 @@ public class ArrMonitoringService.Max();if (action is ArrConfig.QueueAction.DoNothing) return;- await client.DeleteQueueRecord(item.Id, action);+ await client.DeleteQueueRecord(item.Id, action).ConfigureAwait(false);Log.Warning($"Resolved stuck queue item `{item.Title}` from `{client.Host}, with action `{action}`");}}\ No newline at end of filediff --git a/backend/Services/HealthCheckService.cs b/backend/Services/HealthCheckService.csindex efc70fe1..dd142475 100644--- a/backend/Services/HealthCheckService.cs+++ b/backend/Services/HealthCheckService.cs@@ -54,15 +54,18 @@ public class HealthCheckService// if the repair-job is disabled, then don't do anythingif (!_configManager.IsRepairJobEnabled()){- await Task.Delay(TimeSpan.FromSeconds(5), _cancellationToken);+ await Task.Delay(TimeSpan.FromSeconds(5), _cancellationToken).ConfigureAwait(false);continue;}+ // get concurrency+ var concurrency = _configManager.GetMaxRepairConnections();+// set reserved-connections context- var maxRepairConnections = _configManager.GetMaxRepairConnections();using var cts = CancellationTokenSource.CreateLinkedTokenSource(_cancellationToken);- var reservedConnections = _configManager.GetMaxConnections() - maxRepairConnections;- using var _ = cts.Token.SetScopedContext(new ReservedConnectionsContext(reservedConnections));+ var providerConfig = _configManager.GetUsenetProviderConfig();+ var reservedConnections = providerConfig.TotalPooledConnections - concurrency;+ using var _ = cts.Token.SetScopedContext(new ReservedPooledConnectionsContext(reservedConnections));// get the davItem to health-checkawait using var dbContext = new DavDatabaseContext();@@ -70,22 +73,22 @@ public class HealthCheckServicevar currentDateTime = DateTimeOffset.UtcNow;var davItem = await GetHealthCheckQueueItems(dbClient).Where(x => x.NextHealthCheck == null || x.NextHealthCheck < currentDateTime)- .FirstOrDefaultAsync(cts.Token);+ .FirstOrDefaultAsync(cts.Token).ConfigureAwait(false);// if there is no item to health-check, don't do anythingif (davItem == null){- await Task.Delay(TimeSpan.FromSeconds(5), cts.Token);+ await Task.Delay(TimeSpan.FromSeconds(5), cts.Token).ConfigureAwait(false);continue;}// perform the health check- await PerformHealthCheck(davItem, dbClient, maxRepairConnections, cts.Token);+ await PerformHealthCheck(davItem, dbClient, concurrency, cts.Token).ConfigureAwait(false);}catch (Exception e){Log.Error(e, $"Unexpected error performing background health checks: {e.Message}");- await Task.Delay(TimeSpan.FromSeconds(5), _cancellationToken);+ await Task.Delay(TimeSpan.FromSeconds(5), _cancellationToken).ConfigureAwait(false);}}}@@ -120,8 +123,8 @@ public class HealthCheckServicetry{// update the release date, if null- var segments = await GetAllSegments(davItem, dbClient, ct);- if (davItem.ReleaseDate == null) await UpdateReleaseDate(davItem, segments, ct);+ var segments = await GetAllSegments(davItem, dbClient, ct).ConfigureAwait(false);+ if (davItem.ReleaseDate == null) await UpdateReleaseDate(davItem, segments, ct).ConfigureAwait(false);// setup progress tracking@@ -135,7 +138,7 @@ public class HealthCheckService// perform health checkvar progress = progressHook.ToPercentage(segments.Count);- await _usenetClient.CheckAllSegmentsAsync(segments, concurrency, progress, ct);+ await _usenetClient.CheckAllSegmentsAsync(segments, concurrency, progress, ct).ConfigureAwait(false);_ = _websocketManager.SendMessage(WebsocketTopic.HealthItemProgress, $"{davItem.Id}|100");_ = _websocketManager.SendMessage(WebsocketTopic.HealthItemProgress, $"{davItem.Id}|done");@@ -152,7 +155,7 @@ public class HealthCheckServiceRepairStatus = HealthCheckResult.RepairAction.None,Message = "File is healthy."}));- await dbClient.Ctx.SaveChangesAsync(ct);+ await dbClient.Ctx.SaveChangesAsync(ct).ConfigureAwait(false);}catch (UsenetArticleNotFoundException e){@@ -163,7 +166,7 @@ public class HealthCheckService_missingSegmentIds.Add(e.SegmentId);// when usenet article is missing, perform repairs- await Repair(davItem, dbClient, ct);+ await Repair(davItem, dbClient, ct).ConfigureAwait(false);}}@@ -171,7 +174,7 @@ public class HealthCheckService{var firstSegmentId = StringUtil.EmptyToNull(segments.FirstOrDefault());if (firstSegmentId == null) return;- var articleHeaders = await _usenetClient.GetArticleHeadersAsync(firstSegmentId, ct);+ var articleHeaders = await _usenetClient.GetArticleHeadersAsync(firstSegmentId, ct).ConfigureAwait(false);davItem.ReleaseDate = articleHeaders.Date;}@@ -179,7 +182,7 @@ public class HealthCheckService{if (davItem.Type == DavItem.ItemType.NzbFile){- var nzbFile = await dbClient.GetNzbFileAsync(davItem.Id, ct);+ var nzbFile = await dbClient.GetNzbFileAsync(davItem.Id, ct).ConfigureAwait(false);return nzbFile?.SegmentIds?.ToList() ?? [];}@@ -187,7 +190,7 @@ public class HealthCheckService{var rarFile = await dbClient.Ctx.RarFiles.Where(x => x.Id == davItem.Id)- .FirstOrDefaultAsync(ct);+ .FirstOrDefaultAsync(ct).ConfigureAwait(false);return rarFile?.RarParts?.SelectMany(x => x.SegmentIds)?.ToList() ?? [];}@@ -195,7 +198,7 @@ public class HealthCheckService{var multipartFile = await dbClient.Ctx.MultipartFiles.Where(x => x.Id == davItem.Id)- .FirstOrDefaultAsync(ct);+ .FirstOrDefaultAsync(ct).ConfigureAwait(false);return multipartFile?.Metadata?.FileParts?.SelectMany(x => x.SegmentIds)?.ToList() ?? [];}@@ -226,7 +229,7 @@ public class HealthCheckService"Deleted file."])}));- await dbClient.Ctx.SaveChangesAsync(ct);+ await dbClient.Ctx.SaveChangesAsync(ct).ConfigureAwait(false);return;}@@ -250,7 +253,7 @@ public class HealthCheckService"Deleted file."])}));- await dbClient.Ctx.SaveChangesAsync(ct);+ await dbClient.Ctx.SaveChangesAsync(ct).ConfigureAwait(false);return;}@@ -259,12 +262,12 @@ public class HealthCheckServicevar linkType = symlinkOrStrmPath.ToLower().EndsWith("strm") ? "strm-file" : "symlink";foreach (var arrClient in _configManager.GetArrConfig().GetArrClients()){- var rootFolders = await arrClient.GetRootFolders();+ var rootFolders = await arrClient.GetRootFolders().ConfigureAwait(false);if (!rootFolders.Any(x => symlinkOrStrmPath.StartsWith(x.Path!))) continue;// if we found a corresponding arr instance,// then remove and search.- if (await arrClient.RemoveAndSearch(symlinkOrStrmPath))+ if (await arrClient.RemoveAndSearch(symlinkOrStrmPath).ConfigureAwait(false)){dbClient.Ctx.Items.Remove(davItem);dbClient.Ctx.HealthCheckResults.Add(SendStatus(new HealthCheckResult()@@ -281,7 +284,7 @@ public class HealthCheckService"Triggered new Arr search."])}));- await dbClient.Ctx.SaveChangesAsync(ct);+ await dbClient.Ctx.SaveChangesAsync(ct).ConfigureAwait(false);return;}@@ -294,7 +297,7 @@ public class HealthCheckService// if we could not find a corresponding arr instance// then we can delete both the item and the link-file.- File.Delete(symlinkOrStrmPath);+ await Task.Run(() => File.Delete(symlinkOrStrmPath)).ConfigureAwait(false);dbClient.Ctx.Items.Remove(davItem);dbClient.Ctx.HealthCheckResults.Add(SendStatus(new HealthCheckResult(){@@ -311,7 +314,7 @@ public class HealthCheckService$"Deleted the webdav-file and {linkType}."])}));- await dbClient.Ctx.SaveChangesAsync(ct);+ await dbClient.Ctx.SaveChangesAsync(ct).ConfigureAwait(false);}catch (Exception e){@@ -330,7 +333,7 @@ public class HealthCheckServiceRepairStatus = HealthCheckResult.RepairAction.ActionNeeded,Message = $"Error performing file repair: {e.Message}"}));- await dbClient.Ctx.SaveChangesAsync(ct);+ await dbClient.Ctx.SaveChangesAsync(ct).ConfigureAwait(false);}}diff --git a/backend/Streams/CombinedStream.cs b/backend/Streams/CombinedStream.csindex 5a3973e9..b6a75cb9 100644--- a/backend/Streams/CombinedStream.cs+++ b/backend/Streams/CombinedStream.cs@@ -32,7 +32,7 @@ public class CombinedStream(IEnumerable<Task<Stream>> streams) : Streamif (_currentStream == null){if (!_streams.MoveNext()) return 0;- _currentStream = await _streams.Current;+ _currentStream = await _streams.Current.ConfigureAwait(false);}// read from our current stream@@ -40,15 +40,15 @@ public class CombinedStream(IEnumerable<Task<Stream>> streams) : Stream(buffer.AsMemory(offset, count),cancellationToken- );+ ).ConfigureAwait(false);_position += readCount;if (readCount > 0) return readCount;// If we couldn't read anything from our current stream,// it's time to advance to the next stream.- await _currentStream.DisposeAsync();+ await _currentStream.DisposeAsync().ConfigureAwait(false);if (!_streams.MoveNext()) return 0;- _currentStream = await _streams.Current;+ _currentStream = await _streams.Current.ConfigureAwait(false);}return 0;@@ -62,7 +62,7 @@ public class CombinedStream(IEnumerable<Task<Stream>> streams) : Streamwhile (remaining > 0){var toRead = (int)Math.Min(remaining, throwaway.Length);- var read = await ReadAsync(throwaway, 0, toRead);+ var read = await ReadAsync(throwaway, 0, toRead).ConfigureAwait(false);remaining -= read;if (read == 0) break;}@@ -102,7 +102,7 @@ public class CombinedStream(IEnumerable<Task<Stream>> streams) : Streampublic override async ValueTask DisposeAsync(){if (_isDisposed) return;- if (_currentStream != null) await _currentStream.DisposeAsync();+ if (_currentStream != null) await _currentStream.DisposeAsync().ConfigureAwait(false);_streams.Dispose();_isDisposed = true;GC.SuppressFinalize(this);diff --git a/backend/Streams/DavMultipartFileStream.cs b/backend/Streams/DavMultipartFileStream.csindex 38964ee5..87e677f1 100644--- a/backend/Streams/DavMultipartFileStream.cs+++ b/backend/Streams/DavMultipartFileStream.cs@@ -1,5 +1,6 @@using NzbWebDAV.Clients.Usenet;using NzbWebDAV.Database.Models;+using NzbWebDAV.Exceptions;using NzbWebDAV.Extensions;namespace NzbWebDAV.Streams;@@ -28,7 +29,7 @@ public class DavMultipartFileStream(public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken){if (_innerStream == null) _innerStream = GetFileStream(_position, cancellationToken);- var read = await _innerStream.ReadAsync(buffer, offset, count, cancellationToken);+ var read = await _innerStream.ReadAsync(buffer, offset, count, cancellationToken).ConfigureAwait(false);_position += read;return read;}@@ -79,7 +80,7 @@ public class DavMultipartFileStream(offset = nextOffset;}- throw new ArgumentOutOfRangeException(nameof(byteOffset));+ throw new SeekPositionNotFoundException($"Corrupt file. Cannot seek to byte position {byteOffset}.");}private CombinedStream GetFileStream(long rangeStart, CancellationToken cancellationToken)@@ -113,7 +114,7 @@ public class DavMultipartFileStream(public override async ValueTask DisposeAsync(){if (_disposed) return;- if (_innerStream != null) await _innerStream.DisposeAsync();+ if (_innerStream != null) await _innerStream.DisposeAsync().ConfigureAwait(false);_disposed = true;GC.SuppressFinalize(this);}diff --git a/backend/Streams/DisposableCallbackStream.cs b/backend/Streams/DisposableCallbackStream.csindex 03fcf9bf..cd9682e2 100644--- a/backend/Streams/DisposableCallbackStream.cs+++ b/backend/Streams/DisposableCallbackStream.cs@@ -39,15 +39,15 @@ public class DisposableCallbackStream : Stream{if (_disposed) return;- await _inner.DisposeAsync();+ await _inner.DisposeAsync().ConfigureAwait(false);if (_onDisposeAsync != null)- await _onDisposeAsync();+ await _onDisposeAsync().ConfigureAwait(false);else_onDispose?.Invoke();_disposed = true;- await base.DisposeAsync();+ await base.DisposeAsync().ConfigureAwait(false);}// Core stream overridesdiff --git a/backend/Streams/LimitedLengthStream.cs b/backend/Streams/LimitedLengthStream.csindex d6711b94..ce371c77 100644--- a/backend/Streams/LimitedLengthStream.cs+++ b/backend/Streams/LimitedLengthStream.cs@@ -14,7 +14,7 @@ public class LimitedLengthStream(Stream stream, long length) : Streampublic override async Task<int>ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) =>- await ReadAsync(buffer.AsMemory(offset, count), cancellationToken);+ await ReadAsync(buffer.AsMemory(offset, count), cancellationToken).ConfigureAwait(false);public override async ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default){@@ -27,7 +27,7 @@ public class LimitedLengthStream(Stream stream, long length) : Streamvar bytesToRead = (int)Math.Min(remainingBytes, buffer.Length);// Read from the underlying stream- var bytesRead = await stream.ReadAsync(buffer[..bytesToRead], cancellationToken);+ var bytesRead = await stream.ReadAsync(buffer[..bytesToRead], cancellationToken).ConfigureAwait(false);// Update the position by the number of bytes read_position += bytesRead;@@ -61,7 +61,7 @@ public class LimitedLengthStream(Stream stream, long length) : Streampublic override async ValueTask DisposeAsync(){if (_disposed) return;- await stream.DisposeAsync();+ await stream.DisposeAsync().ConfigureAwait(false);_disposed = true;GC.SuppressFinalize(this);}diff --git a/backend/Streams/MultipartFileStream.cs b/backend/Streams/MultipartFileStream.csindex 2ee09646..e8cbb62c 100644--- a/backend/Streams/MultipartFileStream.cs+++ b/backend/Streams/MultipartFileStream.cs@@ -47,13 +47,13 @@ public class MultipartFileStream : Stream(buffer.AsMemory(offset, count),cancellationToken- );+ ).ConfigureAwait(false);_position += readCount;if (readCount > 0) return readCount;// If we couldn't read anything from our current stream,// it's time to advance to the next stream.- await _currentStream.DisposeAsync();+ await _currentStream.DisposeAsync().ConfigureAwait(false);_currentStream = null;}@@ -113,7 +113,7 @@ public class MultipartFileStream : Streampublic override async ValueTask DisposeAsync(){if (_isDisposed) return;- if (_currentStream != null) await _currentStream.DisposeAsync();+ if (_currentStream != null) await _currentStream.DisposeAsync().ConfigureAwait(false);_isDisposed = true;GC.SuppressFinalize(this);}diff --git a/backend/Streams/NzbFileStream.cs b/backend/Streams/NzbFileStream.csindex 046cba80..75c89323 100644--- a/backend/Streams/NzbFileStream.cs+++ b/backend/Streams/NzbFileStream.cs@@ -28,8 +28,8 @@ public class NzbFileStream(public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken){- if (_innerStream == null) _innerStream = await GetFileStream(_position, cancellationToken);- var read = await _innerStream.ReadAsync(buffer, offset, count, cancellationToken);+ if (_innerStream == null) _innerStream = await GetFileStream(_position, cancellationToken).ConfigureAwait(false);+ var read = await _innerStream.ReadAsync(buffer, offset, count, cancellationToken).ConfigureAwait(false);_position += read;return read;}@@ -76,19 +76,19 @@ public class NzbFileStream(new LongRange(0, fileSize),async (guess) =>{- var header = await client.GetSegmentYencHeaderAsync(fileSegmentIds[guess], ct);+ var header = await client.GetSegmentYencHeaderAsync(fileSegmentIds[guess], ct).ConfigureAwait(false);return new LongRange(header.PartOffset, header.PartOffset + header.PartSize);},ct- );+ ).ConfigureAwait(false);}private async Task<CombinedStream> GetFileStream(long rangeStart, CancellationToken cancellationToken){if (rangeStart == 0) return GetCombinedStream(0, cancellationToken);- var foundSegment = await SeekSegment(rangeStart, cancellationToken);+ var foundSegment = await SeekSegment(rangeStart, cancellationToken).ConfigureAwait(false);var stream = GetCombinedStream(foundSegment.FoundIndex, cancellationToken);- await stream.DiscardBytesAsync(rangeStart - foundSegment.FoundByteRange.StartInclusive);+ await stream.DiscardBytesAsync(rangeStart - foundSegment.FoundByteRange.StartInclusive).ConfigureAwait(false);return stream;}@@ -96,7 +96,7 @@ public class NzbFileStream({return new CombinedStream(fileSegmentIds[firstSegmentIndex..]- .Select(async x => (Stream)await client.GetSegmentStreamAsync(x, false, ct))+ .Select(async x => (Stream)await client.GetSegmentStreamAsync(x, false, ct).ConfigureAwait(false)).WithConcurrency(concurrentConnections));}@@ -111,7 +111,7 @@ public class NzbFileStream(public override async ValueTask DisposeAsync(){if (_disposed) return;- if (_innerStream != null) await _innerStream.DisposeAsync();+ if (_innerStream != null) await _innerStream.DisposeAsync().ConfigureAwait(false);_disposed = true;GC.SuppressFinalize(this);}diff --git a/backend/Streams/ProbingStream.cs b/backend/Streams/ProbingStream.csindex f6c49a53..b675a007 100644--- a/backend/Streams/ProbingStream.cs+++ b/backend/Streams/ProbingStream.cs@@ -19,7 +19,7 @@ public class ProbingStream(Stream stream) : Streamreturn _isEmpty.Value;var buffer = new byte[1];- var bytesRead = await stream.ReadAsync(buffer.AsMemory(0, 1));+ var bytesRead = await stream.ReadAsync(buffer.AsMemory(0, 1)).ConfigureAwait(false);if (bytesRead == 0){@@ -58,7 +58,7 @@ public class ProbingStream(Stream stream) : Stream{if (!_isEmpty.HasValue){- var read = await stream.ReadAsync(buffer.AsMemory(offset, count), cancellationToken);+ var read = await stream.ReadAsync(buffer.AsMemory(offset, count), cancellationToken).ConfigureAwait(false);_isEmpty = read == 0;return read;}@@ -67,18 +67,18 @@ public class ProbingStream(Stream stream) : Stream{buffer[offset] = _probeByte.Value;_probeByte = null;- var read = await stream.ReadAsync(buffer.AsMemory(offset + 1, count - 1), cancellationToken);+ var read = await stream.ReadAsync(buffer.AsMemory(offset + 1, count - 1), cancellationToken).ConfigureAwait(false);return 1 + read;}- return await stream.ReadAsync(buffer, offset, count, cancellationToken);+ return await stream.ReadAsync(buffer, offset, count, cancellationToken).ConfigureAwait(false);}public override async ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default){if (!_isEmpty.HasValue){- var read = await stream.ReadAsync(buffer, cancellationToken);+ var read = await stream.ReadAsync(buffer, cancellationToken).ConfigureAwait(false);_isEmpty = read == 0;return read;}@@ -92,11 +92,11 @@ public class ProbingStream(Stream stream) : Streamspan[0] = (byte)_probeByte.Value;_probeByte = null;- var read = await stream.ReadAsync(buffer[1..], cancellationToken);+ var read = await stream.ReadAsync(buffer[1..], cancellationToken).ConfigureAwait(false);return 1 + read;}- return await stream.ReadAsync(buffer, cancellationToken);+ return await stream.ReadAsync(buffer, cancellationToken).ConfigureAwait(false);}public override void Flush() => stream.Flush();@@ -125,7 +125,7 @@ public class ProbingStream(Stream stream) : Streampublic override async ValueTask DisposeAsync(){if (_disposed) return;- await stream.DisposeAsync();+ await stream.DisposeAsync().ConfigureAwait(false);_disposed = true;GC.SuppressFinalize(this);}diff --git a/backend/Streams/YencHeaderStream.cs b/backend/Streams/YencHeaderStream.csindex f2012f12..d4a23951 100644--- a/backend/Streams/YencHeaderStream.cs+++ b/backend/Streams/YencHeaderStream.cs@@ -43,7 +43,7 @@ public class YencHeaderStream(YencHeader header, UsenetArticleHeaders? articleHepublic override async ValueTask DisposeAsync(){if (_disposed) return;- await stream.DisposeAsync();+ await stream.DisposeAsync().ConfigureAwait(false);_disposed = true;GC.SuppressFinalize(this);}diff --git a/backend/Tasks/BaseTask.cs b/backend/Tasks/BaseTask.csindex bb1ecaf5..2055cce6 100644--- a/backend/Tasks/BaseTask.cs+++ b/backend/Tasks/BaseTask.cs@@ -9,7 +9,7 @@ public abstract class BaseTaskpublic async Task<bool> Execute(){- await Semaphore.WaitAsync();+ await Semaphore.WaitAsync().ConfigureAwait(false);Task? task;try{@@ -27,7 +27,7 @@ public abstract class BaseTask}// and wait for it to finish.- await task;+ await task.ConfigureAwait(false);return true;}}\ No newline at end of filediff --git a/backend/Tasks/RemoveUnlinkedFilesTask.cs b/backend/Tasks/RemoveUnlinkedFilesTask.csindex dc18da54..ff147ed9 100644--- a/backend/Tasks/RemoveUnlinkedFilesTask.cs+++ b/backend/Tasks/RemoveUnlinkedFilesTask.cs@@ -22,7 +22,7 @@ public class RemoveUnlinkedFilesTask({try{- await RemoveUnlinkedFiles();+ await RemoveUnlinkedFiles().ConfigureAwait(false);}catch (Exception e){@@ -37,7 +37,7 @@ public class RemoveUnlinkedFilesTask(var dryRun = isDryRun ? "Dry Run - " : string.Empty;Report(dryRun + "Enumerating all webdav files...");- var allDavItems = await dbClient.Ctx.Items.ToListAsync();+ var allDavItems = await dbClient.Ctx.Items.ToListAsync().ConfigureAwait(false);// get linked file pathsReport(dryRun + $"Found {allDavItems.Count} webdav files.\nEnumerating all linked files...");@@ -77,7 +77,7 @@ public class RemoveUnlinkedFilesTask(RemoveItem(unlinkedFile, removedItems);// save changes to database- if (!isDryRun) await dbClient.Ctx.SaveChangesAsync();+ if (!isDryRun) await dbClient.Ctx.SaveChangesAsync().ConfigureAwait(false);// return all removed paths_allRemovedPaths = allDavItemsdiff --git a/backend/Tasks/StrmToSymlinksTask.cs b/backend/Tasks/StrmToSymlinksTask.csindex ac902f44..96cc7415 100644--- a/backend/Tasks/StrmToSymlinksTask.cs+++ b/backend/Tasks/StrmToSymlinksTask.cs@@ -21,7 +21,7 @@ public class StrmToSymlinksTask(try{var ct = SigtermUtil.GetCancellationToken();- await ConvertAllStrmFilesToSymlinks(ct);+ await ConvertAllStrmFilesToSymlinks(ct).ConfigureAwait(false);}catch (Exception e){@@ -40,7 +40,7 @@ public class StrmToSymlinksTask(ReportProgress("Scanning library for strm files...", completedCount);foreach (var batch in batches)- await ConvertBatchOfStrmFilesToSymlinks(batch, OnItemCompleted, token);+ await ConvertBatchOfStrmFilesToSymlinks(batch, OnItemCompleted, token).ConfigureAwait(false);ReportProgress("Done!", completedCount);return;@@ -67,7 +67,7 @@ public class StrmToSymlinksTask(.ToList();var davItems = await dbClient.Ctx.Items.Where(x => davItemsToFetch.Contains(x.Id))- .ToDictionaryAsync(x => x.Id, x => x, token);+ .ToDictionaryAsync(x => x.Id, x => x, token).ConfigureAwait(false);var itemsWithExtension = items.Select(x => new{@@ -81,8 +81,11 @@ public class StrmToSymlinksTask({var symlinkPath = PathUtil.ReplaceExtension(item.Link.LinkPath, item.Extension);var symlinkTarget = DatabaseStoreSymlinkFile.GetTargetPath(item.Link.DavItemId, mountDir);- File.CreateSymbolicLink(symlinkPath, symlinkTarget);- File.Delete(item.Link.LinkPath);+ await Task.Run(() =>+ {+ File.CreateSymbolicLink(symlinkPath, symlinkTarget);+ File.Delete(item.Link.LinkPath);+ }).ConfigureAwait(false);onItemCompleted?.Invoke();}}diff --git a/backend/Utils/EmbeddedResourceUtil.cs b/backend/Utils/EmbeddedResourceUtil.csindex ff3fb74e..f7a3e1cd 100644--- a/backend/Utils/EmbeddedResourceUtil.cs+++ b/backend/Utils/EmbeddedResourceUtil.cs@@ -23,7 +23,7 @@ public static class EmbeddedResourceUtil{await using var stream = GetStream(resourcePath);using var reader = new StreamReader(stream);- return await reader.ReadToEndAsync();+ return await reader.ReadToEndAsync().ConfigureAwait(false);}private static string GetFullResourcePath(string resourcePath)diff --git a/backend/Utils/InterpolationSearch.cs b/backend/Utils/InterpolationSearch.csindex 736100c9..12d64d86 100644--- a/backend/Utils/InterpolationSearch.cs+++ b/backend/Utils/InterpolationSearch.cs@@ -44,7 +44,7 @@ public static class InterpolationSearchvar bytesPerIndex = (double)byteRangeToSearch.Count / indexRangeToSearch.Count;var guessFromStart = (long)Math.Floor(searchByteFromStart / bytesPerIndex);var guessedIndex = (int)(indexRangeToSearch.StartInclusive + guessFromStart);- var byteRangeOfGuessedIndex = await getByteRangeOfGuessedIndex(guessedIndex);+ var byteRangeOfGuessedIndex = await getByteRangeOfGuessedIndex(guessedIndex).ConfigureAwait(false);// make sure the result is within the range of our search spaceif (!byteRangeOfGuessedIndex.IsContainedWithin(byteRangeToSearch))diff --git a/backend/Utils/RarUtil.cs b/backend/Utils/RarUtil.csindex 51e8a86a..1fa8e705 100644--- a/backend/Utils/RarUtil.cs+++ b/backend/Utils/RarUtil.cs@@ -17,7 +17,7 @@ public static class RarUtil){await using var cancellableStream = new CancellableStream(stream, ct);- return await Task.Run(() => GetRarHeaders(cancellableStream, password), ct);+ return await Task.Run(() => GetRarHeaders(cancellableStream, password), ct).ConfigureAwait(false);}private static List<IRarHeader> GetRarHeaders(Stream stream, string? password)diff --git a/backend/Utils/SevenZipUtil.cs b/backend/Utils/SevenZipUtil.csindex 5afc8138..9a86c065 100644--- a/backend/Utils/SevenZipUtil.cs+++ b/backend/Utils/SevenZipUtil.cs@@ -17,7 +17,7 @@ public static class SevenZipUtil){await using var cancellableStream = new CancellableStream(stream, ct);- return await Task.Run(() => GetSevenZipEntries(cancellableStream, password), ct);+ return await Task.Run(() => GetSevenZipEntries(cancellableStream, password), ct).ConfigureAwait(false);}public static List<SevenZipEntry> GetSevenZipEntries(Stream stream, string? password = null)diff --git a/backend/Utils/TaskUtil.cs b/backend/Utils/TaskUtil.csindex c5ff4d04..75fbfdb2 100644--- a/backend/Utils/TaskUtil.cs+++ b/backend/Utils/TaskUtil.cs@@ -20,7 +20,7 @@ public static class TaskUtilvar completedTasks = 0;while (taskList.Count > 0){- var completedTask = await Task.WhenAny(taskList);+ var completedTask = await Task.WhenAny(taskList).ConfigureAwait(false);taskList.Remove(completedTask);if (completedTask.IsFaulted)diff --git a/backend/WebDav/Base/BaseStoreCollection.cs b/backend/WebDav/Base/BaseStoreCollection.csindex ea91fb9e..dd33a8f0 100644--- a/backend/WebDav/Base/BaseStoreCollection.cs+++ b/backend/WebDav/Base/BaseStoreCollection.cs@@ -48,7 +48,7 @@ public abstract class BaseStoreCollection : IStoreCollectionpublic async IAsyncEnumerable<IStoreItem> GetItemsAsync(CancellationToken cancellationToken){- var allItems = await GetAllItemsAsync(cancellationToken);+ var allItems = await GetAllItemsAsync(cancellationToken).ConfigureAwait(false);foreach (var item in allItems){yield return item;@@ -64,7 +64,7 @@ public abstract class BaseStoreCollection : IStoreCollection{Name = name,CancellationToken = cancellationToken- }) ?? EmptyFileManager.Get(name);+ }).ConfigureAwait(false) ?? EmptyFileManager.Get(name);}public async Task<StoreItemResult> CreateItemAsync@@ -75,7 +75,7 @@ public abstract class BaseStoreCollection : IStoreCollectionCancellationToken cancellationToken){- var existingItem = await GetItemAsync(name, cancellationToken);+ var existingItem = await GetItemAsync(name, cancellationToken).ConfigureAwait(false);var probingStream = new ProbingStream(stream);// if the item doesn't already exist, create it@@ -88,7 +88,7 @@ public abstract class BaseStoreCollection : IStoreCollectionif (existingItem is null){// This handles step #1 in the note above.- if (await probingStream.IsEmptyAsync())+ if (await probingStream.IsEmptyAsync().ConfigureAwait(false)){var emptyFile = new BaseStoreEmptyFile(name);EmptyFileManager.Add(emptyFile);@@ -106,7 +106,7 @@ public abstract class BaseStoreCollection : IStoreCollectionStream = probingStream,Overwrite = overwrite,CancellationToken = cancellationToken- });+ }).ConfigureAwait(false);}return new StoreItemResult(DavStatusCode.Conflict);@@ -187,7 +187,7 @@ public abstract class BaseStoreCollection : IStoreCollectionIStoreCollection current = this;for (var i = 0; i < segments.Length; i++){- var nextItem = await current.GetItemAsync(segments[i], cancellationToken);+ var nextItem = await current.GetItemAsync(segments[i], cancellationToken).ConfigureAwait(false);if (nextItem is null) return null;if (i == segments.Length - 1)diff --git a/backend/WebDav/Base/BaseStoreStreamFile.cs b/backend/WebDav/Base/BaseStoreStreamFile.csnew file mode 100644index 00000000..2d946f39--- /dev/null+++ b/backend/WebDav/Base/BaseStoreStreamFile.cs@@ -0,0 +1,21 @@+using NzbWebDAV.Clients.Usenet.Connections;+using NzbWebDAV.Extensions;+using NzbWebDAV.Streams;++namespace NzbWebDAV.WebDav.Base;++public abstract class BaseStoreStreamFile() : BaseStoreReadonlyItem+{+ public abstract Task<Stream> GetStreamAsync(CancellationToken cancellationToken);++ public override async Task<Stream> GetReadableStreamAsync(CancellationToken cancellationToken)+ {+ var stream = await GetStreamAsync(cancellationToken).ConfigureAwait(false);+ var scopedContext = cancellationToken.SetScopedContext(new LastSuccessfulProviderContext());+ return new DisposableCallbackStream+ (+ stream,+ () => scopedContext.Dispose()+ );+ }+}\ No newline at end of filediff --git a/backend/WebDav/DatabaseStore.cs b/backend/WebDav/DatabaseStore.csindex 3353cbd3..a72b2606 100644--- a/backend/WebDav/DatabaseStore.cs+++ b/backend/WebDav/DatabaseStore.cs@@ -31,7 +31,7 @@ public class DatabaseStore(public async Task<IStoreItem?> GetItemAsync(string path, CancellationToken cancellationToken){path = path.Trim('/');- return path == "" ? _root : await _root.ResolvePath(path, cancellationToken);+ return path == "" ? _root : await _root.ResolvePath(path, cancellationToken).ConfigureAwait(false);}public Task<IStoreItem?> GetItemAsync(Uri uri, CancellationToken cancellationToken)@@ -41,6 +41,6 @@ public class DatabaseStore(public async Task<IStoreCollection?> GetCollectionAsync(Uri uri, CancellationToken cancellationToken){- return await GetItemAsync(uri, cancellationToken) as IStoreCollection;+ return await GetItemAsync(uri, cancellationToken).ConfigureAwait(false) as IStoreCollection;}}\ No newline at end of filediff --git a/backend/WebDav/DatabaseStoreCollection.cs b/backend/WebDav/DatabaseStoreCollection.csindex 600ddc61..7a50ce09 100644--- a/backend/WebDav/DatabaseStoreCollection.cs+++ b/backend/WebDav/DatabaseStoreCollection.cs@@ -29,14 +29,14 @@ public class DatabaseStoreCollection(protected override async Task<IStoreItem?> GetItemAsync(GetItemRequest request){- var child = await dbClient.GetDirectoryChildAsync(davDirectory.Id, request.Name, request.CancellationToken);+ var child = await dbClient.GetDirectoryChildAsync(davDirectory.Id, request.Name, request.CancellationToken).ConfigureAwait(false);if (child is null) return null;return GetItem(child);}protected override async Task<IStoreItem[]> GetAllItemsAsync(CancellationToken cancellationToken){- return (await dbClient.GetDirectoryChildrenAsync(davDirectory.Id, cancellationToken))+ return (await dbClient.GetDirectoryChildrenAsync(davDirectory.Id, cancellationToken).ConfigureAwait(false)).Select(GetItem).ToArray();}@@ -57,14 +57,14 @@ public class DatabaseStoreCollection(return DavStatusCode.Forbidden;// Get the item being deleted- var davItem = await dbClient.GetDirectoryChildAsync(davDirectory.Id, request.Name, request.CancellationToken);+ var davItem = await dbClient.GetDirectoryChildAsync(davDirectory.Id, request.Name, request.CancellationToken).ConfigureAwait(false);if (davItem is null) return DavStatusCode.NotFound;// If the item is a file, simply delete it and we're done.if (davItem.Type is DavItem.ItemType.NzbFile or DavItem.ItemType.RarFile or DavItem.ItemType.MultipartFile){dbClient.Ctx.Items.Remove(davItem);- await dbClient.Ctx.SaveChangesAsync();+ await dbClient.Ctx.SaveChangesAsync().ConfigureAwait(false);return DavStatusCode.Ok;}@@ -72,7 +72,7 @@ public class DatabaseStoreCollection(if (davItem.Type == DavItem.ItemType.Directory && !davItem.IsProtected()){dbClient.Ctx.Items.Remove(davItem);- await dbClient.Ctx.SaveChangesAsync();+ await dbClient.Ctx.SaveChangesAsync().ConfigureAwait(false);return DavStatusCode.Ok;}diff --git a/backend/WebDav/DatabaseStoreIdsCollection.cs b/backend/WebDav/DatabaseStoreIdsCollection.csindex 651c8ee1..96678019 100644--- a/backend/WebDav/DatabaseStoreIdsCollection.cs+++ b/backend/WebDav/DatabaseStoreIdsCollection.cs@@ -40,7 +40,7 @@ public class DatabaseStoreIdsCollection(return new DatabaseStoreIdsCollection(dir, Path.Join(currentPath, dir), ctx, db, usenet, config);}- var item = await dbClient.GetFileById(request.Name);+ var item = await dbClient.GetFileById(request.Name).ConfigureAwait(false);return item == null ? null : new DatabaseStoreIdFile(item, ctx, dbClient, usenet, config);}@@ -55,7 +55,7 @@ public class DatabaseStoreIdsCollection(.ToArray();var idPrefix = string.Join("", _currentPathParts);- return (await dbClient.GetFilesByIdPrefix(idPrefix))+ return (await dbClient.GetFilesByIdPrefix(idPrefix).ConfigureAwait(false)).Select(x => new DatabaseStoreIdFile(x, ctx, db, usenet, config)).Select(x => x as IStoreItem).ToArray();diff --git a/backend/WebDav/DatabaseStoreMultipartFile.cs b/backend/WebDav/DatabaseStoreMultipartFile.csindex 9bd24f7d..24b6d61d 100644--- a/backend/WebDav/DatabaseStoreMultipartFile.cs+++ b/backend/WebDav/DatabaseStoreMultipartFile.cs@@ -15,7 +15,7 @@ public class DatabaseStoreMultipartFile(DavDatabaseClient dbClient,UsenetStreamingClient usenetClient,ConfigManager configManager-) : BaseStoreReadonlyItem+) : BaseStoreStreamFile{public DavItem DavItem => davMultipartFile;public override string Name => davMultipartFile.Name;@@ -23,14 +23,14 @@ public class DatabaseStoreMultipartFile(public override long FileSize => davMultipartFile.FileSize!.Value;public override DateTime CreatedAt => davMultipartFile.CreatedAt;- public override async Task<Stream> GetReadableStreamAsync(CancellationToken ct)+ public override async Task<Stream> GetStreamAsync(CancellationToken ct){// store the DavItem being accessed in the http contexthttpContext.Items["DavItem"] = davMultipartFile;// return the streamvar id = davMultipartFile.Id;- var multipartFile = await dbClient.Ctx.MultipartFiles.Where(x => x.Id == id).FirstOrDefaultAsync(ct);+ var multipartFile = await dbClient.Ctx.MultipartFiles.Where(x => x.Id == id).FirstOrDefaultAsync(ct).ConfigureAwait(false);if (multipartFile is null) throw new FileNotFoundException($"Could not find nzb file with id: {id}");var packedStream = new DavMultipartFileStream(multipartFile.Metadata.FileParts,diff --git a/backend/WebDav/DatabaseStoreNzbFile.cs b/backend/WebDav/DatabaseStoreNzbFile.csindex 2935f735..f850c408 100644--- a/backend/WebDav/DatabaseStoreNzbFile.cs+++ b/backend/WebDav/DatabaseStoreNzbFile.cs@@ -13,7 +13,7 @@ public class DatabaseStoreNzbFile(DavDatabaseClient dbClient,UsenetStreamingClient usenetClient,ConfigManager configManager-) : BaseStoreReadonlyItem+) : BaseStoreStreamFile{public DavItem DavItem => davNzbFile;public override string Name => davNzbFile.Name;@@ -21,14 +21,14 @@ public class DatabaseStoreNzbFile(public override long FileSize => davNzbFile.FileSize!.Value;public override DateTime CreatedAt => davNzbFile.CreatedAt;- public override async Task<Stream> GetReadableStreamAsync(CancellationToken cancellationToken)+ public override async Task<Stream> GetStreamAsync(CancellationToken cancellationToken){// store the DavItem being accessed in the http contexthttpContext.Items["DavItem"] = davNzbFile;// return the streamvar id = davNzbFile.Id;- var file = await dbClient.GetNzbFileAsync(id, cancellationToken);+ var file = await dbClient.GetNzbFileAsync(id, cancellationToken).ConfigureAwait(false);if (file is null) throw new FileNotFoundException($"Could not find nzb file with id: {id}");return usenetClient.GetFileStream(file.SegmentIds, FileSize, configManager.GetConnectionsPerStream());}diff --git a/backend/WebDav/DatabaseStoreQueueItem.cs b/backend/WebDav/DatabaseStoreQueueItem.csindex ae8353e6..f827d7c5 100644--- a/backend/WebDav/DatabaseStoreQueueItem.cs+++ b/backend/WebDav/DatabaseStoreQueueItem.cs@@ -19,7 +19,7 @@ public class DatabaseStoreQueueItem(public override async Task<Stream> GetReadableStreamAsync(CancellationToken ct){var id = queueItem.Id;- var document = await dbClient.Ctx.QueueNzbContents.Where(x => x.Id == id).FirstOrDefaultAsync(ct);+ var document = await dbClient.Ctx.QueueNzbContents.Where(x => x.Id == id).FirstOrDefaultAsync(ct).ConfigureAwait(false);if (document is null) throw new FileNotFoundException($"Could not find nzb document with id: {id}");return new MemoryStream(Encoding.UTF8.GetBytes(document.NzbContents));}diff --git a/backend/WebDav/DatabaseStoreRarFile.cs b/backend/WebDav/DatabaseStoreRarFile.csindex 25452998..dd0cdf77 100644--- a/backend/WebDav/DatabaseStoreRarFile.cs+++ b/backend/WebDav/DatabaseStoreRarFile.cs@@ -15,7 +15,7 @@ public class DatabaseStoreRarFile(DavDatabaseClient dbClient,UsenetStreamingClient usenetClient,ConfigManager configManager-) : BaseStoreReadonlyItem+) : BaseStoreStreamFile{public DavItem DavItem => davRarFile;public override string Name => davRarFile.Name;@@ -23,14 +23,14 @@ public class DatabaseStoreRarFile(public override long FileSize => davRarFile.FileSize!.Value;public override DateTime CreatedAt => davRarFile.CreatedAt;- public override async Task<Stream> GetReadableStreamAsync(CancellationToken ct)+ public override async Task<Stream> GetStreamAsync(CancellationToken ct){// store the DavItem being accessed in the http contexthttpContext.Items["DavItem"] = davRarFile;// return the streamvar id = davRarFile.Id;- var rarFile = await dbClient.Ctx.RarFiles.Where(x => x.Id == id).FirstOrDefaultAsync(ct);+ var rarFile = await dbClient.Ctx.RarFiles.Where(x => x.Id == id).FirstOrDefaultAsync(ct).ConfigureAwait(false);if (rarFile is null) throw new FileNotFoundException($"Could not find nzb file with id: {id}");return new DavMultipartFileStream(diff --git a/backend/WebDav/DatabaseStoreSymlinkCollection.cs b/backend/WebDav/DatabaseStoreSymlinkCollection.csindex 17a09895..b4bfb30d 100644--- a/backend/WebDav/DatabaseStoreSymlinkCollection.cs+++ b/backend/WebDav/DatabaseStoreSymlinkCollection.cs@@ -27,7 +27,7 @@ public class DatabaseStoreSymlinkCollection({if (DeletedFiles.IsDeleted(request.Name)) return null;var name = Regex.Replace(request.Name, @"\.rclonelink$", "");- var child = await dbClient.GetDirectoryChildAsync(TargetId, name, request.CancellationToken);+ var child = await dbClient.GetDirectoryChildAsync(TargetId, name, request.CancellationToken).ConfigureAwait(false);if (child is null) return null;return GetItem(child);}@@ -38,8 +38,8 @@ public class DatabaseStoreSymlinkCollection(// then we only want to show children that correspond to Completed History items.var isCategoryFolder = davDirectory.ParentId == DavItem.ContentFolder.Id;var children = isCategoryFolder- ? await dbClient.GetCompletedSymlinkCategoryChildren(davDirectory.Name, cancellationToken)- : await dbClient.GetDirectoryChildrenAsync(TargetId, cancellationToken);+ ? await dbClient.GetCompletedSymlinkCategoryChildren(davDirectory.Name, cancellationToken).ConfigureAwait(false)+ : await dbClient.GetDirectoryChildrenAsync(TargetId, cancellationToken).ConfigureAwait(false);return children.Select(GetItem)diff --git a/backend/WebDav/DatabaseStoreWatchFolder.cs b/backend/WebDav/DatabaseStoreWatchFolder.csindex 22b4ce37..2d984f89 100644--- a/backend/WebDav/DatabaseStoreWatchFolder.cs+++ b/backend/WebDav/DatabaseStoreWatchFolder.cs@@ -36,14 +36,14 @@ public class DatabaseStoreWatchFolder({var queueItem = await dbClient.Ctx.QueueItems.Where(x => x.FileName == request.Name)- .FirstOrDefaultAsync(request.CancellationToken);+ .FirstOrDefaultAsync(request.CancellationToken).ConfigureAwait(false);if (queueItem is null) return null;return new DatabaseStoreQueueItem(queueItem, dbClient);}protected override async Task<IStoreItem[]> GetAllItemsAsync(CancellationToken cancellationToken){- return (await dbClient.GetQueueItems(null, 0, int.MaxValue, cancellationToken))+ return (await dbClient.GetQueueItems(null, 0, int.MaxValue, cancellationToken).ConfigureAwait(false)).Select(x => new DatabaseStoreQueueItem(x, dbClient)).Select(IStoreItem (x) => x).ToArray();@@ -53,7 +53,7 @@ public class DatabaseStoreWatchFolder({var controller = new AddFileController(null!, dbClient, queueManager, configManager, websocketManager);using var streamReader = new StreamReader(request.Stream);- var nzbFileContents = await streamReader.ReadToEndAsync(request.CancellationToken);+ var nzbFileContents = await streamReader.ReadToEndAsync(request.CancellationToken).ConfigureAwait(false);var addFileRequest = new AddFileRequest(){FileName = request.Name,@@ -65,7 +65,7 @@ public class DatabaseStoreWatchFolder(NzbFileContents = nzbFileContents,CancellationToken = request.CancellationToken};- var response = await controller.AddFileAsync(addFileRequest);+ var response = await controller.AddFileAsync(addFileRequest).ConfigureAwait(false);var queueItem = dbClient.Ctx.ChangeTracker.Entries<QueueItem>().Select(x => x.Entity)@@ -80,7 +80,7 @@ public class DatabaseStoreWatchFolder(// get the item to deletevar item = await dbClient.Ctx.QueueItems.Where(x => x.FileName == request.Name)- .FirstOrDefaultAsync(request.CancellationToken);+ .FirstOrDefaultAsync(request.CancellationToken).ConfigureAwait(false);// if the item doesn't exist, return 404if (item is null)@@ -92,7 +92,7 @@ public class DatabaseStoreWatchFolder({NzoIds = [item.Id],CancellationToken = request.CancellationToken- });+ }).ConfigureAwait(false);return DavStatusCode.NoContent;}}\ No newline at end of filediff --git a/backend/Websocket/WebsocketManager.cs b/backend/Websocket/WebsocketManager.csindex 11cb26f5..86322c09 100644--- a/backend/Websocket/WebsocketManager.cs+++ b/backend/Websocket/WebsocketManager.cs@@ -16,11 +16,11 @@ public class WebsocketManager{if (context.WebSockets.IsWebSocketRequest){- using var webSocket = await context.WebSockets.AcceptWebSocketAsync();- if (!await Authenticate(webSocket))+ using var webSocket = await context.WebSockets.AcceptWebSocketAsync().ConfigureAwait(false);+ if (!await Authenticate(webSocket).ConfigureAwait(false)){Log.Warning($"Closing unauthenticated websocket connection from {context.Connection.RemoteIpAddress}");- await CloseUnauthorizedConnection(webSocket);+ await CloseUnauthorizedConnection(webSocket).ConfigureAwait(false);return;}@@ -33,10 +33,10 @@ public class WebsocketManagerlock (_lastMessage) lastMessage = _lastMessage.ToList();foreach (var message in lastMessage)if (message.Key.Type == WebsocketTopic.TopicType.State)- await SendMessage(webSocket, message.Key, message.Value);+ await SendMessage(webSocket, message.Key, message.Value).ConfigureAwait(false);// wait for the socket to disconnect- await WaitForDisconnected(webSocket);+ await WaitForDisconnected(webSocket).ConfigureAwait(false);lock (_authenticatedSockets)_authenticatedSockets.Remove(webSocket);}@@ -68,7 +68,7 @@ public class WebsocketManager/// <returns>True if authenticated, False otherwise.</returns>private static async Task<bool> Authenticate(WebSocket socket){- var apiKey = await ReceiveAuthToken(socket);+ var apiKey = await ReceiveAuthToken(socket).ConfigureAwait(false);return apiKey == EnvironmentUtil.GetVariable("FRONTEND_BACKEND_API_KEY");}@@ -84,8 +84,8 @@ public class WebsocketManagervar buffer = new byte[1024];WebSocketReceiveResult? result = null;while (result is not { CloseStatus: not null })- result = await socket.ReceiveAsync(new ArraySegment<byte>(buffer), SigtermUtil.GetCancellationToken());- await socket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None);+ result = await socket.ReceiveAsync(new ArraySegment<byte>(buffer), SigtermUtil.GetCancellationToken()).ConfigureAwait(false);+ await socket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None).ConfigureAwait(false);}catch (Exception e){@@ -103,7 +103,7 @@ public class WebsocketManager{var topicMessage = new TopicMessage(topic, message);var bytes = new ArraySegment<byte>(Encoding.UTF8.GetBytes(topicMessage.ToJson()));- await SendMessage(socket, bytes);+ await SendMessage(socket, bytes).ConfigureAwait(false);}/// <summary>@@ -115,7 +115,7 @@ public class WebsocketManager{try{- await socket.SendAsync(message, WebSocketMessageType.Text, true, SigtermUtil.GetCancellationToken());+ await socket.SendAsync(message, WebSocketMessageType.Text, true, SigtermUtil.GetCancellationToken()).ConfigureAwait(false);}catch (Exception e){@@ -136,7 +136,7 @@ public class WebsocketManagervar buffer = new byte[1024];using var cts = CancellationTokenSource.CreateLinkedTokenSource(SigtermUtil.GetCancellationToken());cts.CancelAfter(TimeSpan.FromSeconds(5));- var result = await socket.ReceiveAsync(new ArraySegment<byte>(buffer), cts.Token);+ var result = await socket.ReceiveAsync(new ArraySegment<byte>(buffer), cts.Token).ConfigureAwait(false);return result.MessageType == WebSocketMessageType.Text? Encoding.UTF8.GetString(buffer, 0, result.Count): null;@@ -154,7 +154,7 @@ public class WebsocketManagerprivate static async Task CloseUnauthorizedConnection(WebSocket socket){if (socket.State == WebSocketState.Open)- await socket.CloseAsync(WebSocketCloseStatus.PolicyViolation, "Unauthorized", CancellationToken.None);+ await socket.CloseAsync(WebSocketCloseStatus.PolicyViolation, "Unauthorized", CancellationToken.None).ConfigureAwait(false);}private sealed class TopicMessage(WebsocketTopic topic, string message)diff --git a/frontend/app/routes/_index/components/live-usenet-connections/live-usenet-connections.module.css b/frontend/app/routes/_index/components/live-usenet-connections/live-usenet-connections.module.cssindex 3c6fee36..e618dde5 100644--- a/frontend/app/routes/_index/components/live-usenet-connections/live-usenet-connections.module.css+++ b/frontend/app/routes/_index/components/live-usenet-connections/live-usenet-connections.module.css@@ -27,6 +27,7 @@position: absolute;height: 100%;width: 0%;+ transition: width 0.3s ease;}.active {@@ -34,6 +35,7 @@position: absolute;height: 100%;width: 0%;+ transition: width 0.3s ease;}.caption {diff --git a/frontend/app/routes/_index/components/live-usenet-connections/live-usenet-connections.tsx b/frontend/app/routes/_index/components/live-usenet-connections/live-usenet-connections.tsxindex 3bea6f21..40e84799 100644--- a/frontend/app/routes/_index/components/live-usenet-connections/live-usenet-connections.tsx+++ b/frontend/app/routes/_index/components/live-usenet-connections/live-usenet-connections.tsx@@ -8,8 +8,8 @@ const usenetConnectionsTopic = {'cxs': 'state'};export function LiveUsenetConnections() {const navigate = useNavigate();const [connections, setConnections] = useState<string | null>(null);- const parts = (connections || "0|1|0").split("|");- const [live, max, idle] = parts.map(x => Number(x));+ const parts = (connections || "0|0|0|0|1|0").split("|");+ const [_0, _1, _2, live, max, idle] = parts.map(x => Number(x));const active = live - idle;const activePercent = 100 * (active / max);const livePercent = 100 * (live / max);diff --git a/frontend/app/routes/settings/route.tsx b/frontend/app/routes/settings/route.tsxindex 7434982c..451339e0 100644--- a/frontend/app/routes/settings/route.tsx+++ b/frontend/app/routes/settings/route.tsx@@ -3,7 +3,7 @@ import styles from "./route.module.css"import { Tabs, Tab, Button, Form } from "react-bootstrap"import { backendClient } from "~/clients/backend-client.server";import { isUsenetSettingsUpdated, UsenetSettings } from "./usenet/usenet";-import React, { useEffect } from "react";+import React from "react";import { isSabnzbdSettingsUpdated, isSabnzbdSettingsValid, SabnzbdSettings } from "./sabnzbd/sabnzbd";import { isWebdavSettingsUpdated, isWebdavSettingsValid, WebdavSettings } from "./webdav/webdav";import { isArrsSettingsUpdated, isArrsSettingsValid, ArrsSettings } from "./arrs/arrs";@@ -23,14 +23,9 @@ const defaultConfig = {"api.duplicate-nzb-behavior": "increment","api.import-strategy": "symlinks","api.completed-downloads-dir": "",- "usenet.host": "",- "usenet.port": "",- "usenet.use-ssl": "false",- "usenet.connections": "",- "usenet.connections-per-stream": "",- "usenet.user": "",- "usenet.pass": "",- "webdav.user": "",+ "usenet.providers": "",+ "usenet.connections-per-stream": "5",+ "webdav.user": "admin","webdav.pass": "","webdav.show-hidden-files": "false","webdav.enforce-readonly": "true",@@ -68,7 +63,6 @@ function Body(props: BodyProps) {// stateful variablesconst [config, setConfig] = React.useState(props.config);const [newConfig, setNewConfig] = React.useState(config);- const [isUsenetSettingsReadyToSave, setIsUsenetSettingsReadyToSave] = React.useState(false);const [isSaving, setIsSaving] = React.useState(false);const [isSaved, setIsSaved] = React.useState(false);const [activeTab, setActiveTab] = React.useState('usenet');@@ -90,7 +84,6 @@ function Body(props: BodyProps) {const saveButtonLabel = isSaving ? "Saving...": !isUpdated && isSaved ? "Saved ✅": !isUpdated && !isSaved ? "There are no changes to save"- : iseUsenetUpdated && !isUsenetSettingsReadyToSave ? "Must test the usenet connection to save": isSabnzbdUpdated && !isSabnzbdSettingsValid(newConfig) ? "Invalid SABnzbd settings": isWebdavUpdated && !isWebdavSettingsValid(newConfig) ? "Invalid WebDAV settings": isArrsUpdated && !isArrsSettingsValid(newConfig) ? "Invalid Arrs settings"@@ -107,10 +100,6 @@ function Body(props: BodyProps) {setIsSaved(false);}, [config, setNewConfig]);- const onUsenetSettingsReadyToSave = React.useCallback((isReadyToSave: boolean) => {- setIsUsenetSettingsReadyToSave(isReadyToSave);- }, [setIsUsenetSettingsReadyToSave]);-const onSave = React.useCallback(async () => {setIsSaving(true);setIsSaved(false);@@ -138,7 +127,7 @@ function Body(props: BodyProps) {className={styles.tabs}><Tab eventKey="usenet" title={usenetTitle}>- <UsenetSettings config={newConfig} setNewConfig={setNewConfig} onReadyToSave={onUsenetSettingsReadyToSave} />+ <UsenetSettings config={newConfig} setNewConfig={setNewConfig} /></Tab><Tab eventKey="sabnzbd" title={sabnzbdTitle}><SabnzbdSettings config={newConfig} setNewConfig={setNewConfig} />diff --git a/frontend/app/routes/settings/usenet/usenet.module.css b/frontend/app/routes/settings/usenet/usenet.module.cssindex feac1f2f..488d8390 100644--- a/frontend/app/routes/settings/usenet/usenet.module.css+++ b/frontend/app/routes/settings/usenet/usenet.module.css@@ -1,22 +1,526 @@.container {- max-width:400px;+ max-width: 600px;margin-bottom: 25px;}+.section {+ margin-bottom: 30px;+}++.sectionHeader {+ display: flex;+ justify-content: space-between;+ align-items: center;+ margin-bottom: 20px;+}++.sectionHeader h5 {+ margin: 0;+}++.alertMessage {+ color: #93a1a1;+ font-style: italic;+ padding: 20px;+ background-color: #002b36;+ border: 1px solid #586e75;+ border-radius: 8px;+}++.providers-grid {+ display: grid;+ grid-template-columns: repeat(auto-fill, minmax(480px, 1fr));+ gap: 20px;+ margin-bottom: 28px;+}++.provider-card {+ position: relative;+ background: linear-gradient(135deg, hsl(198 100% 5.5%) 0%, hsl(196 100% 4.5%) 100%);+ border: 1px solid hsl(198 100% 10%);+ border-radius: 12px;+ overflow: hidden;+}++.provider-card-inner {+ padding: 20px;+}++.provider-header {+ display: flex;+ align-items: flex-start;+ gap: 12px;+ margin-bottom: 14px;+ margin-left: 8px;+}++.provider-header-actions {+ display: flex;+ gap: 6px;+}++.header-action-button {+ display: flex;+ align-items: center;+ justify-content: center;+ width: 32px;+ height: 32px;+ background: hsl(198 100% 3.5%);+ border: 1px solid hsl(198 100% 10%);+ border-radius: 6px;+ color: #6b8494;+ cursor: pointer;+ transition: all 0.2s ease;+ padding: 0;+}++.header-action-button:hover {+ background: hsl(198 100% 5%);+ border-color: #268bd2;+ color: #5dade2;+}++.header-action-button.delete:hover {+ border-color: #dc322f;+ color: #dc322f;+}++.provider-icon svg {+ width: 18px;+ height: 18px;+}++.provider-header-content {+ flex: 1;+ min-width: 0;+}++.provider-host {+ font-size: 15px;+ font-weight: 600;+ color: #b3c4d1;+ margin-bottom: 2px;+ word-break: break-all;+ line-height: 1.3;+}++.provider-port {+ font-size: 11px;+ font-weight: 500;+ color: #6b8494;+ text-transform: uppercase;+ letter-spacing: 0.5px;+}++.provider-divider {+ height: 1px;+ background: linear-gradient(90deg, transparent 0%, hsl(198 100% 12%) 50%, transparent 100%);+ margin-bottom: 14px;+}++.provider-details {+ display: flex;+ flex-direction: column;+ gap: 10px;+}++.provider-detail-row {+ display: grid;+ grid-template-columns: 1fr 1fr;+ gap: 10px;+}++.provider-detail-item {+ display: flex;+ align-items: center;+ gap: 10px;+ padding: 8px 10px;+ background: hsl(198 100% 3.5%);+ border: 1px solid hsl(198 100% 7%);+ border-radius: 6px;+ position: relative;+}++.provider-detail-icon {+ display: flex;+ align-items: center;+ justify-content: center;+ width: 28px;+ height: 28px;+ min-width: 28px;+ background: linear-gradient(135deg, rgba(38, 139, 210, 0.12) 0%, rgba(42, 161, 152, 0.08) 100%);+ border-radius: 5px;+ color: #4a9ad0;+}++.provider-detail-icon svg {+ width: 13px;+ height: 13px;+}++.provider-detail-content {+ flex: 1;+ display: flex;+ flex-direction: column;+ gap: 2px;+ min-width: 0;+}++.provider-detail-label {+ font-size: 10px;+ font-weight: 600;+ color: #6b8494;+ text-transform: uppercase;+ letter-spacing: 0.6px;+ line-height: 1.2;+}++.provider-detail-value {+ font-size: 13px;+ font-weight: 500;+ color: #a5b8c5;+ word-break: break-all;+ line-height: 1.3;+}++.connection-bar {+ position: absolute;+ top: 0;+ left: 0;+ right: 0;+ height: 1px;+ opacity: 0.5;+ border-radius: 6px 6px 0 0;+ overflow: hidden;+}++.connection-bar-live {+ background-color: green;+ position: absolute;+ height: 100%;+ width: 0%;+ transition: width 0.3s ease;+}++.connection-bar-active {+ background-color: blue;+ position: absolute;+ height: 100%;+ width: 0%;+ transition: width 0.3s ease;+}++.modal-overlay {+ position: fixed;+ top: 0;+ left: 0;+ right: 0;+ bottom: 0;+ background: rgba(0, 0, 0, 0.75);+ display: flex;+ align-items: center;+ justify-content: center;+ z-index: 1050;+ padding: 20px;+ animation: fadeIn 0.2s ease;+}++@keyframes fadeIn {+ from {+ opacity: 0;+ }+ to {+ opacity: 1;+ }+}++.modal-container {+ background: hsl(198 100% 4%);+ border: 1px solid hsl(198 100% 8%);+ border-radius: 8px;+ width: 100%;+ max-width: 800px;+ max-height: 90vh;+ display: flex;+ flex-direction: column;+ box-shadow: 0 20px 60px rgba(0, 0, 0, 0.7);+ animation: slideUp 0.3s ease;+}++@keyframes slideUp {+ from {+ transform: translateY(20px);+ opacity: 0;+ }+ to {+ transform: translateY(0);+ opacity: 1;+ }+}++.modal-header {+ padding: 24px 28px;+ border-bottom: 1px solid hsl(198 100% 8%);+ display: flex;+ align-items: center;+ justify-content: space-between;+}++.modal-title {+ font-size: 20px;+ font-weight: 600;+ color: #93a1a1;+ margin: 0;+}++.modal-close {+ background: transparent;+ border: none;+ color: #657b83;+ font-size: 24px;+ cursor: pointer;+ padding: 0;+ width: 32px;+ height: 32px;+ display: flex;+ align-items: center;+ justify-content: center;+ border-radius: 4px;+ transition: all 0.2s ease;+}++.modal-close:hover {+ background: hsl(198 100% 8%);+ color: #93a1a1;+}++.modal-body {+ padding: 24px 28px;+ overflow-y: auto;+ flex: 1;+}++.modal-footer {+ padding: 20px 28px;+ border-top: 1px solid hsl(198 100% 8%);+ display: flex;+ gap: 12px;+ justify-content: space-between;+ align-items: center;+}++.modal-footer-left {+ display: flex;+ gap: 12px;+}++.modal-footer-right {+ display: flex;+ gap: 12px;+}++.form-grid {+ display: grid;+ grid-template-columns: 1fr 1fr;+ gap: 16px;+ margin-bottom: 0;+}+.form-group {- margin-bottom: 12px;+ margin-bottom: 0;+}++.form-group.full-width {+ grid-column: 1 / -1;+}++.form-label {+ display: block;+ font-size: 13px;+ font-weight: 500;+ color: #839496;+ margin-bottom: 8px;+}++.form-input {+ width: 100%;+ background: hsl(198 100% 2%);+ border: 1px solid hsl(198 100% 8%);+ border-radius: 4px;+ padding: 10px 12px;+ color: #93a1a1;+ font-size: 14px;+ line-height: 1.5;+ height: 42px;+ box-sizing: border-box;+ transition: all 0.2s ease;}-.justify-right{+.form-input:focus {+ outline: none;+ background: hsl(198 100% 3%);+ border-color: #268bd2;+ box-shadow: 0 0 0 2px rgba(38, 139, 210, 0.15);+}++.form-input::placeholder {+ color: #586e75;+}++.form-input.error {+ border-color: #dc322f;+}++.form-input.error:focus {+ border-color: #dc322f;+ box-shadow: 0 0 0 2px rgba(220, 50, 47, 0.15);+}++.form-select {+ width: 100%;+ background-color: hsl(198 100% 2%);+ border: 1px solid hsl(198 100% 8%);+ border-radius: 4px;+ padding: 10px 12px;+ color: #93a1a1;+ font-size: 14px;+ line-height: 1.5;+ height: 42px;+ box-sizing: border-box;+ cursor: pointer;+ transition: background-color 0.2s ease, border-color 0.2s ease, box-shadow 0.2s ease;+ appearance: none;+ background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 12 12'%3E%3Cpath fill='%2393a1a1' d='M6 9L1 4h10z'/%3E%3C/svg%3E");+ background-repeat: no-repeat;+ background-position: right 12px center;+ padding-right: 36px;+}++.form-select:focus {+ outline: none;+ background-color: hsl(198 100% 3%);+ border-color: #268bd2;+ box-shadow: 0 0 0 2px rgba(38, 139, 210, 0.15);+}++.form-checkbox-wrapper {display: flex;- justify-content: end;align-items: center;+ gap: 10px;+ padding: 0;}-.test-connection-button {- margin-top: 12px;+.form-checkbox {+ width: 18px;+ height: 18px;+ cursor: pointer;+ accent-color: #268bd2;+}++.form-checkbox-label {+ font-size: 14px;+ color: #93a1a1;+ cursor: pointer;+ user-select: none;+}++.alert {+ padding: 12px 16px;+ border-radius: 4px;+ font-size: 13px;+ margin-top: 0;+}++.alert-success {+ background: rgba(133, 153, 0, 0.15);+ border: 1px solid #859900;+ color: #859900;+}++.alert-danger {+ background: rgba(220, 50, 47, 0.15);+ border: 1px solid #dc322f;+ color: #dc322f;}.input::placeholder {color: rgba(255, 255, 255, 0.25);+}++@media (max-width: 600px) {+ .form-grid {+ grid-template-columns: 1fr;+ gap: 16px;+ }++ .modal-container {+ max-width: 100%;+ border-radius: 0;+ max-height: 100vh;+ }++ .modal-overlay {+ padding: 0;+ }++ .modal-header,+ .modal-body,+ .modal-footer {+ padding-left: 20px;+ padding-right: 20px;+ }++ .modal-footer {+ flex-direction: column;+ gap: 12px;+ }++ .modal-footer-left,+ .modal-footer-right {+ width: 100%;+ }++ .modal-footer-left button,+ .modal-footer-right button {+ flex: 1;+ }++ .modal-footer-right {+ display: flex;+ gap: 12px;+ }+}++@media (max-width: 600px) {+ .providers-grid {+ grid-template-columns: 1fr;+ gap: 20px;+ }++ .provider-card-inner {+ padding: 20px;+ }++ .provider-header {+ gap: 12px;+ }++ .provider-icon {+ width: 40px;+ height: 40px;+ min-width: 40px;+ }++ .provider-header-actions {+ gap: 6px;+ }++ .provider-detail-row {+ grid-template-columns: 1fr;+ gap: 12px;+ }++ .provider-detail-item {+ padding: 10px;+ }}\ No newline at end of filediff --git a/frontend/app/routes/settings/usenet/usenet.module.css.d.ts b/frontend/app/routes/settings/usenet/usenet.module.css.d.tsindex a30bec0e..faa24d79 100644--- a/frontend/app/routes/settings/usenet/usenet.module.css.d.ts+++ b/frontend/app/routes/settings/usenet/usenet.module.css.d.ts@@ -1,7 +1,57 @@declare const styles: {readonly "container": string;- readonly "input": string;+ readonly "section": string;+ readonly "sectionHeader": string;+ readonly "alertMessage": string;+ readonly "providers-grid": string;+ readonly "provider-card": string;+ readonly "provider-card-inner": string;+ readonly "provider-header": string;+ readonly "provider-header-content": string;+ readonly "provider-header-actions": string;+ readonly "header-action-button": string;+ readonly "delete": string;+ readonly "provider-host": string;+ readonly "provider-port": string;+ readonly "provider-type-badge": string;+ readonly "disabled": string;+ readonly "backup": string;+ readonly "provider-divider": string;+ readonly "provider-details": string;+ readonly "provider-detail-row": string;+ readonly "provider-detail-item": string;+ readonly "provider-detail-icon": string;+ readonly "provider-detail-content": string;+ readonly "provider-detail-label": string;+ readonly "provider-detail-value": string;+ readonly "connection-bar": string;+ readonly "connection-bar-live": string;+ readonly "connection-bar-active": string;+ readonly "provider-actions": string;+ readonly "action-button": string;+ readonly "modal-overlay": string;+ readonly "modal-container": string;+ readonly "modal-header": string;+ readonly "modal-title": string;+ readonly "modal-close": string;+ readonly "modal-body": string;+ readonly "modal-footer": string;+ readonly "modal-footer-left": string;+ readonly "modal-footer-right": string;+ readonly "form-grid": string;readonly "form-group": string;+ readonly "full-width": string;+ readonly "form-label": string;+ readonly "form-input": string;+ readonly "error": string;+ readonly "form-select": string;+ readonly "form-checkbox-wrapper": string;+ readonly "form-checkbox": string;+ readonly "form-checkbox-label": string;+ readonly "alert": string;+ readonly "alert-success": string;+ readonly "alert-danger": string;+ readonly "input": string;readonly "justify-right": string;readonly "test-connection-button": string;};diff --git a/frontend/app/routes/settings/usenet/usenet.tsx b/frontend/app/routes/settings/usenet/usenet.tsxindex 4d29cb9c..9e3fff42 100644--- a/frontend/app/routes/settings/usenet/usenet.tsx+++ b/frontend/app/routes/settings/usenet/usenet.tsx@@ -1,157 +1,570 @@-import { Button, Form } from "react-bootstrap";import styles from "./usenet.module.css"-import { useCallback, useEffect, useState, type Dispatch, type SetStateAction } from "react";+import { type Dispatch, type SetStateAction, useState, useCallback, useEffect, useMemo } from "react";+import { Button } from "react-bootstrap";+import { receiveMessage } from "~/utils/websocket-util";++const usenetConnectionsTopic = {'cxs': 'state'};type UsenetSettingsProps = {config: Record<string, string>setNewConfig: Dispatch<SetStateAction<Record<string, string>>>- onReadyToSave: (isReadyToSave: boolean) => void};-export function UsenetSettings({ config, setNewConfig, onReadyToSave }: UsenetSettingsProps) {- const [isFetching, setIsFetching] = useState(false);- const [isConnectionSuccessful, setIsConnectionSuccessful] = useState(false);- const [testedConfig, setTestedConfig] = useState({});- const isChangedSinceLastTest = isUsenetSettingsUpdated(config, testedConfig);-- const TestButtonLabel = isFetching ? "Testing Connection..."- : !config["usenet.host"] ? "`Host` is required"- : !config["usenet.port"] ? "`Port` is required"- : !isPositiveInteger(config["usenet.port"]) ? "`Port` is invalid"- : !config["usenet.user"] ? "`User` is required"- : !config["usenet.pass"] ? "`Pass` is required"- : !config["usenet.connections"] ? "`Max Connections` is required"- : !config["usenet.connections-per-stream"] ? "`Connections Per Stream` is required"- : !isPositiveInteger(config["usenet.connections"]) ? "`Max Connections` is invalid"- : !config["usenet.connections-per-stream"] ? "`Connections Per Stream` is required"- : !isPositiveInteger(config["usenet.connections-per-stream"]) ? "`Connections Per Stream` is invalid"- : Number(config["usenet.connections-per-stream"]) > Number(config["usenet.connections"]) ? "`Connections Per Stream` is invalid"- : !isChangedSinceLastTest && isConnectionSuccessful ? "Connected ✅"- : !isChangedSinceLastTest && !isConnectionSuccessful ? "Test Connection ❌"- : "Test Connection";- const testButtonVariant = isFetching ? "secondary"- : TestButtonLabel === "Connected ✅" ? "success"- : TestButtonLabel.includes("Test Connection") ? "primary"- : "danger";- const IsTestButtonEnabled = TestButtonLabel == "Test Connection"- || TestButtonLabel == "Test Connection ❌";-- const isReadyToSave = isConnectionSuccessful && !isChangedSinceLastTest;+enum ProviderType {+ Disabled = 0,+ Pooled = 1,+ BackupAndStats = 2,+ BackupOnly = 3,+}++type ConnectionDetails = {+ Type: ProviderType;+ Host: string;+ Port: number;+ UseSsl: boolean;+ User: string;+ Pass: string;+ MaxConnections: number;+};++type ConnectionCounts = {+ live: number;+ active: number;+ max: number;+}++type UsenetProviderConfig = {+ Providers: ConnectionDetails[];+};++const PROVIDER_TYPE_LABELS: Record<ProviderType, string> = {+ [ProviderType.Disabled]: "Disabled",+ [ProviderType.Pooled]: "Pool Connections",+ [ProviderType.BackupAndStats]: "Backup & Health Checks",+ [ProviderType.BackupOnly]: "Backup Only",+};++function parseProviderConfig(jsonString: string): UsenetProviderConfig {+ try {+ if (!jsonString || jsonString.trim() === "") {+ return { Providers: [] };+ }+ return JSON.parse(jsonString);+ } catch {+ return { Providers: [] };+ }+}++function serializeProviderConfig(config: UsenetProviderConfig): string {+ return JSON.stringify(config);+}++export function UsenetSettings({ config, setNewConfig }: UsenetSettingsProps) {+ // state+ const [showModal, setShowModal] = useState(false);+ const [editingIndex, setEditingIndex] = useState<number | null>(null);+ const [connections, setConnections] = useState<{[index: number]: ConnectionCounts}>({});+ const providerConfig = useMemo(() => parseProviderConfig(config["usenet.providers"]), [config]);++ // handlers+ const handleAddProvider = useCallback(() => {+ setEditingIndex(null);+ setShowModal(true);+ }, []);++ const handleEditProvider = useCallback((index: number) => {+ setEditingIndex(index);+ setShowModal(true);+ }, []);++ const handleDeleteProvider = useCallback((index: number) => {+ const newProviderConfig = { ...providerConfig };+ newProviderConfig.Providers = providerConfig.Providers.filter((_, i) => i !== index);+ setNewConfig({ ...config, "usenet.providers": serializeProviderConfig(newProviderConfig) });+ }, [config, providerConfig, setNewConfig]);++ const handleCloseModal = useCallback(() => {+ setShowModal(false);+ setEditingIndex(null);+ }, []);++ const handleSaveProvider = useCallback((provider: ConnectionDetails) => {+ const newProviderConfig = { ...providerConfig };+ if (editingIndex !== null) {+ newProviderConfig.Providers[editingIndex] = provider;+ } else {+ newProviderConfig.Providers.push(provider);+ }+ setNewConfig({ ...config, "usenet.providers": serializeProviderConfig(newProviderConfig) });+ handleCloseModal();+ }, [config, providerConfig, editingIndex, setNewConfig, handleCloseModal]);++ const handleConnectionsMessage = useCallback((message: string) => {+ const parts = (message || "0|0|0|0|1|0").split("|");+ const [index, live, idle, _0, _1, _2] = parts.map((x: any) => Number(x));+ if (showModal) return;+ if (index >= providerConfig.Providers.length) return;+ setConnections(prev => ({...prev, [index]: {+ active: live - idle,+ live: live,+ max: providerConfig.Providers[index]?.MaxConnections || 1+ }}));+ }, [setConnections]);++ // effectsuseEffect(() => {- onReadyToSave && onReadyToSave(isReadyToSave);- }, [isReadyToSave])-- const onTestButtonClicked = useCallback(async () => {- setIsFetching(true);- const response = await fetch("/api/test-usenet-connection", {- method: "POST",- body: (() => {- const form = new FormData();- form.append("host", config["usenet.host"]);- form.append("port", config["usenet.port"]);- form.append("use-ssl", config["usenet.use-ssl"] || "false");- form.append("user", config["usenet.user"]);- form.append("pass", config["usenet.pass"]);- return form;- })()- });- const isConnectionSuccessful = response.ok && ((await response.json())?.connected === true);- setIsFetching(false);- setTestedConfig(config);- setIsConnectionSuccessful(isConnectionSuccessful);- }, [config, setIsFetching, setIsConnectionSuccessful]);+ let ws: WebSocket;+ let disposed = false;+ function connect() {+ ws = new WebSocket(window.location.origin.replace(/^http/, 'ws'));+ ws.onmessage = receiveMessage((_, message) => handleConnectionsMessage(message));+ ws.onopen = () => ws.send(JSON.stringify(usenetConnectionsTopic));+ ws.onerror = () => { ws.close() };+ ws.onclose = onClose;+ return () => { disposed = true; ws.close(); }+ }+ function onClose(e: CloseEvent) {+ !disposed && setTimeout(() => connect(), 1000);+ setConnections({});+ }+ return connect();+ }, [setConnections, handleConnectionsMessage]);+ // viewreturn (<div className={styles.container}>+ <div className={styles.section}>+ <div className={styles.sectionHeader}>+ <div>Usenet Providers</div>+ <Button variant="primary" size="sm" onClick={handleAddProvider}>+ Add+ </Button>+ </div>+ {providerConfig.Providers.length === 0 ? (+ <p className={styles.alertMessage}>+ No Usenet providers configured.+ Click on the "Add" button to get started.+ </p>+ ) : (+ <div className={styles["providers-grid"]}>+ {providerConfig.Providers.map((provider, index) => (+ <div key={index} className={styles["provider-card"]}>+ <div className={styles["provider-card-inner"]}>+ <div className={styles["provider-header"]}>+ <div className={styles["provider-header-content"]}>+ <div className={styles["provider-host"]}>+ {provider.Host}+ </div>+ <div className={styles["provider-port"]}>+ Port {provider.Port}+ </div>+ </div>+ <div className={styles["provider-header-actions"]}>+ <button+ className={styles["header-action-button"]}+ onClick={() => handleEditProvider(index)}+ title="Edit Provider"+ >+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">+ <path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7" />+ <path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z" />+ </svg>+ </button>+ <button+ className={`${styles["header-action-button"]} ${styles["delete"]}`}+ onClick={() => handleDeleteProvider(index)}+ title="Delete Provider"+ >+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">+ <polyline points="3 6 5 6 21 6" />+ <path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2" />+ </svg>+ </button>+ </div>+ </div>++ <div className={styles["provider-details"]}>+ <div className={styles["provider-detail-row"]}>- <Form.Group className={styles["form-group"]}>- <Form.Label>Host</Form.Label>- <Form.Control- type="text"- className={styles.input}- value={config["usenet.host"] || ""}- onChange={e => setNewConfig({ ...config, "usenet.host": e.target.value })} />- </Form.Group>-- <Form.Group className={styles["form-group"]}>- <Form.Label>Port</Form.Label>- <Form.Control- type="text"- className={styles.input}- value={config["usenet.port"] || ""}- onChange={e => setNewConfig({ ...config, "usenet.port": e.target.value })} />- </Form.Group>-- <div className={styles["justify-right"]}>- <Form.Check- id="use-ssl-checkbox"- type="checkbox"- label={`Use SSL`}- checked={config["usenet.use-ssl"] === "true"}- onChange={e => setNewConfig({ ...config, "usenet.use-ssl": "" + e.target.checked })} />+ <div className={styles["provider-detail-item"]}>+ <div className={styles["provider-detail-icon"]}>+ <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">+ <path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2" />+ <circle cx="12" cy="7" r="4" />+ </svg>+ </div>+ <div className={styles["provider-detail-content"]}>+ <span className={styles["provider-detail-label"]}>Username</span>+ <span className={styles["provider-detail-value"]}>{provider.User}</span>+ </div>+ </div>++ <div className={styles["provider-detail-item"]}>+ {connections[index] && (+ <div className={styles["connection-bar"]}>+ <div+ className={styles["connection-bar-live"]}+ style={{ width: `${100 * (connections[index].live / connections[index].max)}%` }}+ />+ <div+ className={styles["connection-bar-active"]}+ style={{ width: `${100 * (connections[index].active / connections[index].max)}%` }}+ />+ </div>+ )}+ <div className={styles["provider-detail-icon"]}>+ <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">+ <path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z" />+ </svg>+ </div>+ <div className={styles["provider-detail-content"]}>+ <span className={styles["provider-detail-label"]}>Max Connections</span>+ <span className={styles["provider-detail-value"]}>{provider.MaxConnections}</span>+ </div>+ </div>++ <div className={styles["provider-detail-item"]}>+ <div className={styles["provider-detail-icon"]}>+ {provider.UseSsl ? (+ // Closed lock icon+ <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">+ <rect x="5" y="11" width="14" height="11" rx="2" ry="2" />+ <path d="M7 11V7a5 5 0 0 1 10 0v4" />+ <circle cx="12" cy="16" r="1" fill="currentColor" />+ </svg>+ ) : (+ // Open lock icon+ <svg width="13" height="13" viewBox="0 -2 24 26" fill="none" stroke="currentColor" strokeWidth="2">+ <rect x="5" y="11" width="14" height="11" rx="2" ry="2" />+ <path d="M7 11V4a5 5 0 0 1 9.9 1" />+ <circle cx="12" cy="16" r="1" fill="currentColor" />+ </svg>+ )}+ </div>+ <div className={styles["provider-detail-content"]}>+ <span className={styles["provider-detail-label"]}>Security</span>+ <span className={styles["provider-detail-value"]}>+ {provider.UseSsl ? "SSL Enabled" : "No SSL"}+ </span>+ </div>+ </div>++ <div className={styles["provider-detail-item"]}>+ <div className={styles["provider-detail-icon"]}>+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.3">+ <text x="12" y="9" fontSize="10" fill="currentColor" textAnchor="middle" fontWeight="600">1</text>+ <text x="6" y="21" fontSize="10" fill="currentColor" textAnchor="middle" fontWeight="600">2</text>+ <text x="18" y="21" fontSize="10" fill="currentColor" textAnchor="middle" fontWeight="600">3</text>+ </svg>+ </div>+ <div className={styles["provider-detail-content"]}>+ <span className={styles["provider-detail-label"]}>Behavior</span>+ <span className={styles["provider-detail-value"]}>{PROVIDER_TYPE_LABELS[provider.Type]}</span>+ </div>+ </div>++ </div>+ </div>+ </div>+ </div>+ ))}+ </div>+ )}</div>- <br />-- <Form.Group className={styles["form-group"]}>- <Form.Label>User</Form.Label>- <Form.Control- type="text"- className={styles.input}- value={config["usenet.user"] || ""}- onChange={e => setNewConfig({ ...config, "usenet.user": e.target.value })} />- </Form.Group>-- <Form.Group className={styles["form-group"]}>- <Form.Label>Pass</Form.Label>- <Form.Control- className={styles.input}- type="password"- value={config["usenet.pass"] || ""}- onChange={e => setNewConfig({ ...config, "usenet.pass": e.target.value })} />- </Form.Group>-- <Form.Group className={styles["form-group"]}>- <Form.Label>Max Connections</Form.Label>- <Form.Control- className={styles.input}- type="text"- placeholder="50"- value={config["usenet.connections"] || ""}- onChange={e => setNewConfig({ ...config, "usenet.connections": e.target.value })} />- </Form.Group>-- <Form.Group className={styles["form-group"]}>- <Form.Label>Connections Per Stream</Form.Label>- <Form.Control- className={styles.input}- type="text"- placeholder="5"- value={config["usenet.connections-per-stream"] || ""}- onChange={e => setNewConfig({ ...config, "usenet.connections-per-stream": e.target.value })} />- </Form.Group>-- <div className={styles["justify-right"]}>- <Button- className={styles["test-connection-button"]}- variant={testButtonVariant}- disabled={!IsTestButtonEnabled}- onClick={() => onTestButtonClicked()}>- {TestButtonLabel}- </Button>+ <ProviderModal+ show={showModal}+ provider={editingIndex !== null ? providerConfig.Providers[editingIndex] : null}+ onClose={handleCloseModal}+ onSave={handleSaveProvider}+ />+ </div>+ );+}++type ProviderModalProps = {+ show: boolean;+ provider: ConnectionDetails | null;+ onClose: () => void;+ onSave: (provider: ConnectionDetails) => void;+};++function ProviderModal({ show, provider, onClose, onSave }: ProviderModalProps) {+ const [host, setHost] = useState(provider?.Host || "");+ const [port, setPort] = useState(provider?.Port?.toString() || "");+ const [useSsl, setUseSsl] = useState(provider?.UseSsl ?? true);+ const [user, setUser] = useState(provider?.User || "");+ const [pass, setPass] = useState(provider?.Pass || "");+ const [maxConnections, setMaxConnections] = useState(provider?.MaxConnections?.toString() || "");+ const [type, setType] = useState<ProviderType>(provider?.Type ?? ProviderType.Pooled);+ const [isTestingConnection, setIsTestingConnection] = useState(false);+ const [connectionTested, setConnectionTested] = useState(false);+ const [testError, setTestError] = useState<string | null>(null);++ // Reset form when modal opens or provider changes+ useEffect(() => {+ if (show) {+ setHost(provider?.Host || "");+ setPort(provider?.Port?.toString() || "");+ setUseSsl(provider?.UseSsl ?? true);+ setUser(provider?.User || "");+ setPass(provider?.Pass || "");+ setMaxConnections(provider?.MaxConnections?.toString() || "");+ setType(provider?.Type ?? ProviderType.Pooled);+ setConnectionTested(false);+ setTestError(null);+ }+ }, [show, provider]);++ // Handle Escape key to close modal+ useEffect(() => {+ const handleEscape = (e: KeyboardEvent) => {+ if (e.key === 'Escape' && show) {+ onClose();+ }+ };++ if (show) {+ document.addEventListener('keydown', handleEscape);+ return () => document.removeEventListener('keydown', handleEscape);+ }+ }, [show, onClose]);++ const handleTestConnection = useCallback(async () => {+ setIsTestingConnection(true);+ setTestError(null);++ try {+ const formData = new FormData();+ formData.append('host', host);+ formData.append('port', port);+ formData.append('use-ssl', useSsl.toString());+ formData.append('user', user);+ formData.append('pass', pass);++ const response = await fetch('/api/test-usenet-connection', {+ method: 'POST',+ body: formData,+ });++ if (response.ok) {+ const data = await response.json();+ if (data.connected) {+ setConnectionTested(true);+ setTestError(null);+ } else {+ setTestError("Connection test failed");+ }+ } else {+ setTestError("Failed to test connection");+ }+ } catch (error) {+ setTestError("Network error: " + (error instanceof Error ? error.message : "Unknown error"));+ } finally {+ setIsTestingConnection(false);+ }+ }, [host, port, useSsl, user, pass]);++ const handleSave = useCallback(() => {+ onSave({+ Type: type,+ Host: host,+ Port: parseInt(port, 10),+ UseSsl: useSsl,+ User: user,+ Pass: pass,+ MaxConnections: parseInt(maxConnections, 10),+ });+ }, [type, host, port, useSsl, user, pass, maxConnections, onSave]);++ const handleOverlayClick = useCallback((e: React.MouseEvent) => {+ if (e.target === e.currentTarget) {+ onClose();+ }+ }, [onClose]);++ const isFormValid = host.trim() !== ""+ && isPositiveInteger(port)+ && user.trim() !== ""+ && pass.trim() !== ""+ && isPositiveInteger(maxConnections);++ const canSave = isFormValid && connectionTested;++ if (!show) return null;++ return (+ <div className={styles["modal-overlay"]} onClick={handleOverlayClick}>+ <div className={styles["modal-container"]}>+ <div className={styles["modal-header"]}>+ <h2 className={styles["modal-title"]}>+ {provider ? "Edit Provider" : "Add Provider"}+ </h2>+ <button className={styles["modal-close"]} onClick={onClose} aria-label="Close">+ ×+ </button>+ </div>++ <div className={styles["modal-body"]}>+ <div className={styles["form-grid"]}>+ <div className={styles["form-group"]}>+ <label htmlFor="provider-host" className={styles["form-label"]}>+ Host+ </label>+ <input+ type="text"+ id="provider-host"+ className={styles["form-input"]}+ placeholder="news.provider.com"+ value={host}+ onChange={(e) => {+ setHost(e.target.value);+ setConnectionTested(false);+ }}+ />+ </div>++ <div className={styles["form-group"]}>+ <label htmlFor="provider-port" className={styles["form-label"]}>+ Port+ </label>+ <input+ type="text"+ id="provider-port"+ className={`${styles["form-input"]} ${!isPositiveInteger(port) && port !== "" ? styles.error : ""}`}+ placeholder="563"+ value={port}+ onChange={(e) => {+ setPort(e.target.value);+ setConnectionTested(false);+ }}+ />+ </div>++ <div className={styles["form-group"]}>+ <label htmlFor="provider-user" className={styles["form-label"]}>+ Username+ </label>+ <input+ type="text"+ id="provider-user"+ className={styles["form-input"]}+ placeholder="username"+ value={user}+ onChange={(e) => {+ setUser(e.target.value);+ setConnectionTested(false);+ }}+ />+ </div>++ <div className={styles["form-group"]}>+ <label htmlFor="provider-pass" className={styles["form-label"]}>+ Password+ </label>+ <input+ type="password"+ id="provider-pass"+ className={styles["form-input"]}+ placeholder="password"+ value={pass}+ onChange={(e) => {+ setPass(e.target.value);+ setConnectionTested(false);+ }}+ />+ </div>++ <div className={styles["form-group"]}>+ <label htmlFor="provider-max-connections" className={styles["form-label"]}>+ Max Connections+ </label>+ <input+ type="text"+ id="provider-max-connections"+ className={`${styles["form-input"]} ${!isPositiveInteger(maxConnections) && maxConnections !== "" ? styles.error : ""}`}+ placeholder="20"+ value={maxConnections}+ onChange={(e) => setMaxConnections(e.target.value)}+ />+ </div>++ <div className={styles["form-group"]}>+ <label htmlFor="provider-type" className={styles["form-label"]}>+ Type+ </label>+ <select+ id="provider-type"+ className={styles["form-select"]}+ value={type}+ onChange={(e) => setType(parseInt(e.target.value, 10) as ProviderType)}+ >+ <option value={ProviderType.Disabled}>Disabled</option>+ <option value={ProviderType.Pooled}>Pool Connections</option>+ <option value={ProviderType.BackupOnly}>Backup Only</option>+ </select>+ </div>++ <div className={`${styles["form-group"]} ${styles["full-width"]}`}>+ <div className={styles["form-checkbox-wrapper"]}>+ <input+ type="checkbox"+ id="provider-ssl"+ className={styles["form-checkbox"]}+ checked={useSsl}+ onChange={(e) => {+ setUseSsl(e.target.checked);+ setConnectionTested(false);+ }}+ />+ <label htmlFor="provider-ssl" className={styles["form-checkbox-label"]}>+ Use SSL+ </label>+ </div>+ </div>+ </div>++ {testError && (+ <div className={`${styles.alert} ${styles["alert-danger"]}`} style={{ marginTop: '16px' }}>+ {testError}+ </div>+ )}++ {connectionTested && (+ <div className={`${styles.alert} ${styles["alert-success"]}`} style={{ marginTop: '16px' }}>+ Connection test successful!+ </div>+ )}+ </div>++ <div className={styles["modal-footer"]}>+ <div className={styles["modal-footer-left"]}></div>+ <div className={styles["modal-footer-right"]}>+ <Button variant="secondary" onClick={onClose}>+ Cancel+ </Button>+ {!connectionTested ? (+ <Button+ variant="primary"+ onClick={handleTestConnection}+ disabled={!isFormValid || isTestingConnection}+ >+ {isTestingConnection ? "Testing..." : "Test Connection"}+ </Button>+ ) : (+ <Button variant="primary" onClick={handleSave} disabled={!canSave}>+ Save Provider+ </Button>+ )}+ </div>+ </div></div></div>);}export function isUsenetSettingsUpdated(config: Record<string, string>, newConfig: Record<string, string>) {- return config["usenet.host"] !== newConfig["usenet.host"]- || config["usenet.port"] !== newConfig["usenet.port"]- || config["usenet.use-ssl"] !== newConfig["usenet.use-ssl"]- || config["usenet.user"] !== newConfig["usenet.user"]- || config["usenet.pass"] !== newConfig["usenet.pass"]- || config["usenet.connections"] !== newConfig["usenet.connections"]- || config["usenet.connections-per-stream"] !== newConfig["usenet.connections-per-stream"]+ return config["usenet.providers"] !== newConfig["usenet.providers"]}export function isPositiveInteger(value: string) {diff --git a/frontend/app/routes/settings/webdav/webdav.tsx b/frontend/app/routes/settings/webdav/webdav.tsxindex 4f81b745..57965a56 100644--- a/frontend/app/routes/settings/webdav/webdav.tsx+++ b/frontend/app/routes/settings/webdav/webdav.tsx@@ -2,6 +2,7 @@ import { Form } from "react-bootstrap";import styles from "./webdav.module.css"import { type Dispatch, type SetStateAction } from "react";import { className } from "~/utils/styling";+import { isPositiveInteger } from "../usenet/usenet";type SabnzbdSettingsProps = {config: Record<string, string>@@ -9,7 +10,6 @@ type SabnzbdSettingsProps = {};export function WebdavSettings({ config, setNewConfig }: SabnzbdSettingsProps) {-return (<div className={styles.container}><Form.Group>@@ -41,6 +41,21 @@ export function WebdavSettings({ config, setNewConfig }: SabnzbdSettingsProps) {</Form.Text></Form.Group><hr />+ <Form.Group>+ <Form.Label htmlFor="connections-per-stream-input">Connections Per Stream</Form.Label>+ <Form.Control+ {...className([styles.input, !isValidConnectionsPerStream(config["usenet.connections-per-stream"]) && styles.error])}+ type="text"+ id="connections-per-stream-input"+ aria-describedby="connections-per-stream-help"+ placeholder="5"+ value={config["usenet.connections-per-stream"]}+ onChange={e => setNewConfig({ ...config, "usenet.connections-per-stream": e.target.value })} />+ <Form.Text id="connections-per-stream-help" muted>+ When a file is requested from the webdav, how many usenet connections should be used to stream that file?+ </Form.Text>+ </Form.Group>+ <hr /><Form.Group><Form.CheckclassName={styles.input}@@ -89,16 +104,22 @@ export function WebdavSettings({ config, setNewConfig }: SabnzbdSettingsProps) {export function isWebdavSettingsUpdated(config: Record<string, string>, newConfig: Record<string, string>) {return config["webdav.user"] !== newConfig["webdav.user"]|| config["webdav.pass"] !== newConfig["webdav.pass"]+ || config["usenet.connections-per-stream"] !== newConfig["usenet.connections-per-stream"]|| config["webdav.show-hidden-files"] !== newConfig["webdav.show-hidden-files"]|| config["webdav.enforce-readonly"] !== newConfig["webdav.enforce-readonly"]|| config["webdav.preview-par2-files"] !== newConfig["webdav.preview-par2-files"]}export function isWebdavSettingsValid(newConfig: Record<string, string>) {- return isValidUser(newConfig["webdav.user"]);+ return isValidUser(newConfig["webdav.user"])+ && isValidConnectionsPerStream(newConfig["usenet.connections-per-stream"]);}function isValidUser(user: string): boolean {const regex = /^[A-Za-z0-9_-]+$/;return regex.test(user);+}++function isValidConnectionsPerStream(value: string): boolean {+ return isPositiveInteger(value);}\ No newline at end of filediff --git a/frontend/package-lock.json b/frontend/package-lock.jsonindex 245871fe..45b995e7 100644--- a/frontend/package-lock.json+++ b/frontend/package-lock.json@@ -83,6 +83,7 @@"version": "7.28.0","resolved": "https://registry.npmjs.org/@babel/core/-/core-7.28.0.tgz","integrity": "sha512-UlLAnTPrFdNGoFtbSXwcGFQBtQZJCNjaN6hQNP3UPvuNXT1i82N26KL3dZeIpNalWywr9IuQuncaAfUaS1g6sQ==",+ "peer": true,"dependencies": {"@ampproject/remapping": "^2.2.0","@babel/code-frame": "^7.27.1",@@ -1016,6 +1017,7 @@"version": "2.11.8","resolved": "https://registry.npmjs.org/@popperjs/core/-/core-2.11.8.tgz","integrity": "sha512-P1st0aksCrn9sGZhp8GMYwBnQsbvAWsZAX44oXNNvLHGqAOcoVxmjZiohstwQ7SqKnbR47akdNi+uleWD8+g6A==",+ "peer": true,"funding": {"type": "opencollective","url": "https://opencollective.com/popperjs"@@ -1039,6 +1041,7 @@"version": "7.8.0","resolved": "https://registry.npmjs.org/@react-router/dev/-/dev-7.8.0.tgz","integrity": "sha512-5NA9yLZComM+kCD3zNPL3rjrAFjzzODY8hjAJlpz/6jpyXoF28W8QTSo8rxc56XVNLONM75Y5nq1wzeEcWFFKA==",+ "peer": true,"dependencies": {"@babel/core": "^7.27.7","@babel/generator": "^7.27.5",@@ -1879,6 +1882,7 @@"version": "19.1.9","resolved": "https://registry.npmjs.org/@types/react/-/react-19.1.9.tgz","integrity": "sha512-WmdoynAX8Stew/36uTSVMcLJJ1KRh6L3IZRx1PZ7qJtBqT3dYTgyDTx8H1qoRghErydW7xw9mSJ3wS//tCRpFA==",+ "peer": true,"dependencies": {"csstype": "^3.0.2"}@@ -2175,6 +2179,7 @@"url": "https://github.com/sponsors/ai"}],+ "peer": true,"dependencies": {"caniuse-lite": "^1.0.30001726","electron-to-chromium": "^1.5.173",@@ -2780,6 +2785,7 @@"version": "5.1.0","resolved": "https://registry.npmjs.org/express/-/express-5.1.0.tgz","integrity": "sha512-DT9ck5YIRU+8GYzzU5kT3eHGA5iL+1Zd0EutOmTE9Dtk+Tvuzd23VBU+ec7HPNSTxXYO55gPV/hq4pSBJDjFpA==",+ "peer": true,"dependencies": {"accepts": "^2.0.0","body-parser": "^2.2.0",@@ -4001,6 +4007,7 @@"url": "https://github.com/sponsors/ai"}],+ "peer": true,"dependencies": {"nanoid": "^3.3.11","picocolors": "^1.1.1",@@ -4201,6 +4208,7 @@"version": "19.1.1","resolved": "https://registry.npmjs.org/react/-/react-19.1.1.tgz","integrity": "sha512-w8nqGImo45dmMIfljjMwOGtbmC/mk4CMYhWIicdSflH91J9TyCyczcPFXJzrZ/ZXcgGRFeP6BU0BEJTw6tZdfQ==",+ "peer": true,"engines": {"node": ">=0.10.0"}@@ -4239,6 +4247,7 @@"version": "19.1.1","resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.1.1.tgz","integrity": "sha512-Dlq/5LAZgF0Gaz6yiqZCf6VCcZs1ghAJyrsu84Q/GT0gV+mCxbfmKNoGRKBYMJ8IEdGPqu49YWXD02GCknEDkw==",+ "peer": true,"dependencies": {"scheduler": "^0.26.0"},@@ -4284,6 +4293,7 @@"version": "7.8.0","resolved": "https://registry.npmjs.org/react-router/-/react-router-7.8.0.tgz","integrity": "sha512-r15M3+LHKgM4SOapNmsH3smAizWds1vJ0Z9C4mWaKnT9/wD7+d/0jYcj6LmOvonkrO4Rgdyp4KQ/29gWN2i1eg==",+ "peer": true,"dependencies": {"cookie": "^1.0.1","set-cookie-parser": "^2.6.0"@@ -4343,6 +4353,7 @@"funding": ["https://github.com/sponsors/sergiodxa"],+ "peer": true,"engines": {"node": ">=20.0.0"}@@ -4845,6 +4856,7 @@"version": "4.0.3","resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.3.tgz","integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==",+ "peer": true,"engines": {"node": ">=12"},@@ -4901,6 +4913,7 @@"resolved": "https://registry.npmjs.org/tsx/-/tsx-4.20.3.tgz","integrity": "sha512-qjbnuR9Tr+FJOMBqJCW5ehvIo/buZq7vH7qD7JziU98h6l3qGy0a/yPFjwO+y0/T7GFpNgNAvEcPPVfyT8rrPQ==","devOptional": true,+ "peer": true,"dependencies": {"esbuild": "~0.25.0","get-tsconfig": "^4.7.5"@@ -5001,6 +5014,7 @@"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.2.tgz","integrity": "sha512-CWBzXQrc/qOkhidw1OzBTQuYRbfyxDXJMVJ1XNwUHGROVmuaeiEm3OslpZ1RV96d7SKKjZKrSJu3+t/xlw3R9A==","devOptional": true,+ "peer": true,"bin": {"tsc": "bin/tsc","tsserver": "bin/tsserver"@@ -5113,6 +5127,7 @@"version": "6.3.5","resolved": "https://registry.npmjs.org/vite/-/vite-6.3.5.tgz","integrity": "sha512-cZn6NDFE7wdTpINgs++ZJ4N49W2vRp8LCKrn3Ob1kYNtOo21vfDoaV5GzBfLU4MovSAB8uNRm4jgzVQZ+mBzPQ==",+ "peer": true,"dependencies": {"esbuild": "^0.25.0","fdir": "^6.4.4",@@ -5244,6 +5259,7 @@"version": "4.0.3","resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.3.tgz","integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==",+ "peer": true,"engines": {"node": ">=12"},