Skip to content

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

C#

Added websocket handler to backend.

nzbdav-deve609f7a8a1ed
diff --git a/backend/Clients/UsenetStreamingClient.cs b/backend/Clients/UsenetStreamingClient.cs
index 68d4e96a..dc5f0233 100644
--- a/backend/Clients/UsenetStreamingClient.cs
+++ b/backend/Clients/UsenetStreamingClient.cs
@@ -1,9 +1,12 @@
-using Microsoft.Extensions.Caching.Memory;
+using System.Text.Json;
+using Microsoft.EntityFrameworkCore.Storage.Json;
+using Microsoft.Extensions.Caching.Memory;
using NzbWebDAV.Clients.Connections;
using NzbWebDAV.Config;
using NzbWebDAV.Exceptions;
using NzbWebDAV.Extensions;
using NzbWebDAV.Streams;
+using NzbWebDAV.Websocket;
using Usenet.Nntp.Responses;
using Usenet.Nzb;
using Usenet.Yenc;
@@ -13,9 +16,13 @@ namespace NzbWebDAV.Clients;
public class UsenetStreamingClient
{
private readonly INntpClient _client;
+ private readonly WebsocketManager _websocketManager;
- public UsenetStreamingClient(ConfigManager configManager)
+ public UsenetStreamingClient(ConfigManager configManager, WebsocketManager websocketManager)
{
+ // initialize private members
+ _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");
@@ -26,7 +33,7 @@ public class UsenetStreamingClient
// initialize the nntp-client
var createNewConnection = (CancellationToken ct) => CreateNewConnection(host, port, useSsl, user, pass, ct);
- ConnectionPool<INntpClient> connectionPool = new(connections, createNewConnection);
+ var connectionPool = CreateNewConnectionPool(connections, createNewConnection);
var multiConnectionClient = new MultiConnectionNntpClient(connectionPool);
var cache = new MemoryCache(new MemoryCacheOptions() { SizeLimit = 8192 });
_client = new CachingNntpClient(multiConnectionClient, cache);
@@ -49,8 +56,9 @@ public class UsenetStreamingClient
var newUseSsl = bool.Parse(configEventArgs.NewConfig.GetValueOrDefault("usenet.use-ssl", "false"));
var newUser = configEventArgs.NewConfig["usenet.user"];
var newPass = configEventArgs.NewConfig["usenet.pass"];
- multiConnectionClient.UpdateConnectionPool(new(connectionCount, cancellationToken =>
- CreateNewConnection(newHost, newPort, newUseSsl, newUser, newPass, cancellationToken)));
+ var newConnectionPool = CreateNewConnectionPool(connectionCount, cancellationToken =>
+ CreateNewConnection(newHost, newPort, newUseSsl, newUser, newPass, cancellationToken));
+ multiConnectionClient.UpdateConnectionPool(newConnectionPool);
};
}
@@ -100,6 +108,25 @@ public class UsenetStreamingClient
return _client.GetFileSizeAsync(file, cancellationToken);
}
+ private ConnectionPool<INntpClient> CreateNewConnectionPool
+ (
+ int maxConnections,
+ Func<CancellationToken, ValueTask<INntpClient>> connectionFactory
+ )
+ {
+ var connectionPool = new ConnectionPool<INntpClient>(maxConnections, connectionFactory);
+ connectionPool.OnConnectionPoolChanged += OnConnectionPoolChanged;
+ var args = new ConnectionPool<INntpClient>.ConnectionPoolChangedEventArgs(0, 0, maxConnections);
+ OnConnectionPoolChanged(connectionPool, args);
+ return connectionPool;
+ }
+
+ private void OnConnectionPoolChanged(object? _, ConnectionPool<INntpClient>.ConnectionPoolChangedEventArgs args)
+ {
+ var message = $"{args.Live}|{args.Max}|{args.Idle}";
+ _websocketManager.SendMessage(WebsocketTopic.UsenetConnections, message);
+ }
+
public static async ValueTask<INntpClient> CreateNewConnection
(
string host,
diff --git a/backend/Extensions/NWebDavOptionsExtensions.cs b/backend/Extensions/NWebDavOptionsExtensions.cs
index 3c4b6c70..95e65b7a 100644
--- a/backend/Extensions/NWebDavOptionsExtensions.cs
+++ b/backend/Extensions/NWebDavOptionsExtensions.cs
@@ -9,6 +9,7 @@ public static class NWebDavOptionsExtensions
{
return context => !context.Request.Path.StartsWithSegments("/api") &&
!context.Request.Path.StartsWithSegments("/view") &&
- !context.Request.Path.StartsWithSegments("/health");
+ !context.Request.Path.StartsWithSegments("/health") &&
+ !context.Request.Path.StartsWithSegments("/ws");
}
}
\ No newline at end of file
diff --git a/backend/Program.cs b/backend/Program.cs
index 1d6bc006..2e54482c 100644
--- a/backend/Program.cs
+++ b/backend/Program.cs
@@ -16,6 +16,7 @@ using NzbWebDAV.Queue;
using NzbWebDAV.Utils;
using NzbWebDAV.WebDav;
using NzbWebDAV.WebDav.Base;
+using NzbWebDAV.Websocket;
using Serilog;
using Serilog.Events;
using Serilog.Sinks.SystemConsole.Themes;
@@ -47,6 +48,9 @@ class Program
var configManager = new ConfigManager();
await configManager.LoadConfig();
+ // initialize websocket-manager
+ var websocketManager = new WebsocketManager();
+
// initialize webapp
var builder = WebApplication.CreateBuilder(args);
builder.Host.UseSerilog();
@@ -54,6 +58,7 @@ class Program
builder.Services.AddHealthChecks();
builder.Services
.AddSingleton(configManager)
+ .AddSingleton(websocketManager)
.AddSingleton<UsenetStreamingClient>()
.AddSingleton<QueueManager>()
.AddScoped<DavDatabaseContext>()
@@ -86,11 +91,13 @@ class Program
// run
var app = builder.Build();
- app.MapHealthChecks("/health");
app.UseSerilogRequestLogging();
app.UseMiddleware<ExceptionMiddleware>();
- app.UseAuthentication();
+ app.UseWebSockets();
+ app.MapHealthChecks("/health");
+ app.Map("/ws", websocketManager.HandleRoute);
app.MapControllers();
+ app.UseAuthentication();
app.UseNWebDav();
await app.RunAsync();
}
diff --git a/backend/Websocket/WebsocketManager.cs b/backend/Websocket/WebsocketManager.cs
new file mode 100644
index 00000000..aa100f52
--- /dev/null
+++ b/backend/Websocket/WebsocketManager.cs
@@ -0,0 +1,158 @@
+using System.Net.WebSockets;
+using System.Text;
+using System.Text.Json;
+using Microsoft.AspNetCore.Http;
+using NzbWebDAV.Utils;
+using Serilog;
+
+namespace NzbWebDAV.Websocket;
+
+public class WebsocketManager
+{
+ private readonly HashSet<WebSocket> _authenticatedSockets = [];
+ private readonly Dictionary<string, string> _lastMessage = new();
+
+ public async Task HandleRoute(HttpContext context)
+ {
+ if (context.WebSockets.IsWebSocketRequest)
+ {
+ using var webSocket = await context.WebSockets.AcceptWebSocketAsync();
+ if (!await Authenticate(webSocket))
+ {
+ Log.Warning($"Closing unauthenticated websocket connection from {context.Connection.RemoteIpAddress}");
+ await CloseUnauthorizedConnection(webSocket);
+ return;
+ }
+
+ // mark the socket as authenticated
+ lock (_authenticatedSockets)
+ _authenticatedSockets.Add(webSocket);
+
+ // send current state for all topics
+ List<KeyValuePair<string, string>>? lastMessage = null;
+ lock (_lastMessage) lastMessage = _lastMessage.ToList();
+ foreach (var message in lastMessage)
+ await SendMessage(webSocket, message.Key, message.Value);
+
+ // wait for the socket to disconnect
+ await WaitForDisconnected(webSocket);
+ lock (_authenticatedSockets)
+ _authenticatedSockets.Remove(webSocket);
+ }
+ else
+ {
+ context.Response.StatusCode = 400;
+ }
+ }
+
+ /// <summary>
+ /// Send a message to all authenticated websockets.
+ /// </summary>
+ /// <param name="topic">The topic of the message to send</param>
+ /// <param name="message">The message to send</param>
+ public Task SendMessage(string topic, string message)
+ {
+ lock (_lastMessage) _lastMessage[topic] = message;
+ List<WebSocket>? authenticatedSockets;
+ lock (_authenticatedSockets) authenticatedSockets = _authenticatedSockets.ToList();
+ var topicMessage = new TopicMessage(topic, message);
+ var bytes = new ArraySegment<byte>(Encoding.UTF8.GetBytes(topicMessage.ToString()));
+ return Task.WhenAll(authenticatedSockets.Select(x => SendMessage(x, bytes)));
+ }
+
+ /// <summary>
+ /// Ensure a websocket sends a valid api key.
+ /// </summary>
+ /// <param name="socket">The websocket to authenticate.</param>
+ /// <returns>True if authenticated, False otherwise.</returns>
+ private static async Task<bool> Authenticate(WebSocket socket)
+ {
+ var apiKey = await ReceiveAuthToken(socket);
+ return apiKey == EnvironmentUtil.GetVariable("FRONTEND_BACKEND_API_KEY");
+ }
+
+ /// <summary>
+ /// Ignore all messages from the websocket and
+ /// wait for it to disconnect.
+ /// </summary>
+ /// <param name="socket">The websocket to wait for disconnect.</param>
+ private static async Task WaitForDisconnected(WebSocket socket)
+ {
+ var buffer = new byte[1024];
+ WebSocketReceiveResult? result = null;
+ while (result is not { CloseStatus: not null })
+ result = await socket.ReceiveAsync(new ArraySegment<byte>(buffer), default);
+ await socket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, default);
+ }
+
+ /// <summary>
+ /// Send a message to a connected websocket.
+ /// </summary>
+ /// <param name="socket">The websocket to send the message to.</param>
+ /// <param name="topic">The topic of the message to send</param>
+ /// <param name="message">The message to send</param>
+ private static async Task SendMessage(WebSocket socket, string topic, string message)
+ {
+ var topicMessage = new TopicMessage(topic, message);
+ var bytes = new ArraySegment<byte>(Encoding.UTF8.GetBytes(topicMessage.ToString()));
+ await SendMessage(socket, bytes);
+ }
+
+ /// <summary>
+ /// Send a message to a connected websocket.
+ /// </summary>
+ /// <param name="socket">The websocket to send the message to.</param>
+ /// <param name="message">The message to send.</param>
+ private static async Task SendMessage(WebSocket socket, ArraySegment<byte> message)
+ {
+ try
+ {
+ await socket.SendAsync(message, WebSocketMessageType.Text, true, default);
+ }
+ catch (Exception e)
+ {
+ Log.Debug($"Failed to send message to websocket. {e.Message}");
+ }
+ }
+
+ /// <summary>
+ /// Receive an authentication token from a connected websocket.
+ /// With timeout after five seconds.
+ /// </summary>
+ /// <param name="socket">The websocket to receive from.</param>
+ /// <returns>The authentication token. Or null if none provided.</returns>
+ private static async Task<string?> ReceiveAuthToken(WebSocket socket)
+ {
+ try
+ {
+ var buffer = new byte[1024];
+ using var cts = new CancellationTokenSource();
+ cts.CancelAfter(TimeSpan.FromSeconds(5));
+ var result = await socket.ReceiveAsync(new ArraySegment<byte>(buffer), cts.Token);
+ return result.MessageType == WebSocketMessageType.Text
+ ? Encoding.UTF8.GetString(buffer, 0, result.Count)
+ : null;
+ }
+ catch (OperationCanceledException)
+ {
+ return null;
+ }
+ }
+
+ /// <summary>
+ /// Close a websocket connection as unauthorized.
+ /// </summary>
+ /// <param name="socket">The websocket whose connection to close.</param>
+ private static async Task CloseUnauthorizedConnection(WebSocket socket)
+ {
+ if (socket.State == WebSocketState.Open)
+ await socket.CloseAsync(WebSocketCloseStatus.PolicyViolation, "Unauthorized", CancellationToken.None);
+ }
+
+ private sealed class TopicMessage(string topic, string message)
+ {
+ public string Topic { get; } = topic;
+ public string Message { get; } = message;
+ public override string ToString() => JsonSerializer.Serialize(this);
+ }
+}
\ No newline at end of file
diff --git a/backend/Websocket/WebsocketTopic.cs b/backend/Websocket/WebsocketTopic.cs
new file mode 100644
index 00000000..c1529e5d
--- /dev/null
+++ b/backend/Websocket/WebsocketTopic.cs
@@ -0,0 +1,6 @@
+namespace NzbWebDAV.Websocket;
+
+public static class WebsocketTopic
+{
+ public const string UsenetConnections = "cxs";
+}
\ No newline at end of file