Usenet streaming with a WebDAV server and a SABnzbd-compatible API
C#
Added rclone client.
nzbdav-dev31551582a6e9
diff --git a/backend/Clients/RadarrSonarr/ArrClient.cs b/backend/Clients/RadarrSonarr/ArrClient.csindex 4d54f987..ca36efc3 100644--- a/backend/Clients/RadarrSonarr/ArrClient.cs+++ b/backend/Clients/RadarrSonarr/ArrClient.cs@@ -8,7 +8,7 @@ namespace NzbWebDAV.Clients.RadarrSonarr;public class ArrClient(string host, string apiKey){- protected static readonly HttpClient HttpClient = new HttpClient();+ protected static readonly HttpClient HttpClient = new();public string Host { get; } = host;private string ApiKey { get; } = apiKey;diff --git a/backend/Clients/Rclone/Models/CoreVersionResponse.cs b/backend/Clients/Rclone/Models/CoreVersionResponse.csnew file mode 100644index 00000000..6e92c7f3--- /dev/null+++ b/backend/Clients/Rclone/Models/CoreVersionResponse.cs@@ -0,0 +1,36 @@+using System.Text.Json.Serialization;++namespace NzbWebDAV.Clients.Rclone.Models;++/// <summary>+/// Response from core/version endpoint.+/// </summary>+public class CoreVersionResponse : RcloneResponse+{+ [JsonPropertyName("version")]+ public string? Version { get; set; }++ [JsonPropertyName("decomposed")]+ public List<int>? Decomposed { get; set; }++ [JsonPropertyName("isGit")]+ public bool IsGit { get; set; }++ [JsonPropertyName("isBeta")]+ public bool IsBeta { get; set; }++ [JsonPropertyName("os")]+ public string? Os { get; set; }++ [JsonPropertyName("arch")]+ public string? Arch { get; set; }++ [JsonPropertyName("goVersion")]+ public string? GoVersion { get; set; }++ [JsonPropertyName("linking")]+ public string? Linking { get; set; }++ [JsonPropertyName("goTags")]+ public string? GoTags { get; set; }+}diff --git a/backend/Clients/Rclone/Models/RcloneErrorResponse.cs b/backend/Clients/Rclone/Models/RcloneErrorResponse.csnew file mode 100644index 00000000..1cc298d3--- /dev/null+++ b/backend/Clients/Rclone/Models/RcloneErrorResponse.cs@@ -0,0 +1,21 @@+using System.Text.Json.Serialization;++namespace NzbWebDAV.Clients.Rclone.Models;++/// <summary>+/// Error response returned by rclone when a request fails.+/// </summary>+public class RcloneErrorResponse+{+ [JsonPropertyName("error")]+ public string? Error { get; set; }++ [JsonPropertyName("input")]+ public object? Input { get; set; }++ [JsonPropertyName("status")]+ public int Status { get; set; }++ [JsonPropertyName("path")]+ public string? Path { get; set; }+}diff --git a/backend/Clients/Rclone/Models/RcloneResponse.cs b/backend/Clients/Rclone/Models/RcloneResponse.csnew file mode 100644index 00000000..3c943573--- /dev/null+++ b/backend/Clients/Rclone/Models/RcloneResponse.cs@@ -0,0 +1,22 @@+using System.Text.Json.Serialization;++namespace NzbWebDAV.Clients.Rclone.Models;++/// <summary>+/// Base response class for all rclone RC API responses.+/// </summary>+public class RcloneResponse+{+ /// <summary>+ /// Indicates if the request was successful.+ /// This is set by the client based on HTTP status, not returned by rclone.+ /// </summary>+ [JsonIgnore]+ public bool Success { get; set; }++ /// <summary>+ /// Error message if the request failed.+ /// </summary>+ [JsonIgnore]+ public string? Error { get; set; }+}diff --git a/backend/Clients/Rclone/Models/VfsForgetResponse.cs b/backend/Clients/Rclone/Models/VfsForgetResponse.csnew file mode 100644index 00000000..de662851--- /dev/null+++ b/backend/Clients/Rclone/Models/VfsForgetResponse.cs@@ -0,0 +1,12 @@+using System.Text.Json.Serialization;++namespace NzbWebDAV.Clients.Rclone.Models;++/// <summary>+/// Response from vfs/forget endpoint.+/// </summary>+public class VfsForgetResponse : RcloneResponse+{+ [JsonPropertyName("forgotten")]+ public List<string>? Forgotten { get; set; }+}diff --git a/backend/Clients/Rclone/Models/VfsStatsResponse.cs b/backend/Clients/Rclone/Models/VfsStatsResponse.csnew file mode 100644index 00000000..4183bbab--- /dev/null+++ b/backend/Clients/Rclone/Models/VfsStatsResponse.cs@@ -0,0 +1,75 @@+using System.Text.Json.Serialization;++namespace NzbWebDAV.Clients.Rclone.Models;++/// <summary>+/// Response from vfs/stats endpoint.+/// </summary>+public class VfsStatsResponse : RcloneResponse+{+ [JsonPropertyName("diskCache")]+ public VfsDiskCache? DiskCache { get; set; }++ [JsonPropertyName("metadataCache")]+ public VfsMetadataCache? MetadataCache { get; set; }++ [JsonPropertyName("opt")]+ public VfsOptions? Options { get; set; }+}++public class VfsDiskCache+{+ [JsonPropertyName("bytesUsed")]+ public long BytesUsed { get; set; }++ [JsonPropertyName("erroredFiles")]+ public int ErroredFiles { get; set; }++ [JsonPropertyName("hashType")]+ public int HashType { get; set; }++ [JsonPropertyName("outOfSpace")]+ public bool OutOfSpace { get; set; }++ [JsonPropertyName("uploadsInProgress")]+ public int UploadsInProgress { get; set; }++ [JsonPropertyName("uploadsQueued")]+ public int UploadsQueued { get; set; }+}++public class VfsMetadataCache+{+ [JsonPropertyName("dirs")]+ public int Dirs { get; set; }++ [JsonPropertyName("files")]+ public int Files { get; set; }+}++public class VfsOptions+{+ [JsonPropertyName("CacheMode")]+ public string? CacheMode { get; set; }++ [JsonPropertyName("CacheMaxAge")]+ public long CacheMaxAge { get; set; }++ [JsonPropertyName("CachePollInterval")]+ public long CachePollInterval { get; set; }++ [JsonPropertyName("ChunkSize")]+ public long ChunkSize { get; set; }++ [JsonPropertyName("ChunkSizeLimit")]+ public long ChunkSizeLimit { get; set; }++ [JsonPropertyName("DirCacheTime")]+ public long DirCacheTime { get; set; }++ [JsonPropertyName("ReadAhead")]+ public long ReadAhead { get; set; }++ [JsonPropertyName("ReadOnly")]+ public bool ReadOnly { get; set; }+}diff --git a/backend/Clients/Rclone/RcloneClient.cs b/backend/Clients/Rclone/RcloneClient.csnew file mode 100644index 00000000..ea32ef31--- /dev/null+++ b/backend/Clients/Rclone/RcloneClient.cs@@ -0,0 +1,205 @@+using System.Net;+using System.Net.Http.Headers;+using System.Text;+using System.Text.Json;+using System.Text.Json.Serialization;+using NzbWebDAV.Clients.Rclone.Models;+using NzbWebDAV.Extensions;+using NzbWebDAV.Utils;+using Serilog;++namespace NzbWebDAV.Clients.Rclone;++/// <summary>+/// Client for interacting with rclone's remote control (RC) API.+/// See https://rclone.org/rc/ for API documentation.+/// </summary>+public class RcloneClient+{+ private static readonly HttpClient HttpClient = new();++ private static readonly JsonSerializerOptions JsonOptions = new()+ {+ PropertyNamingPolicy = JsonNamingPolicy.CamelCase,+ DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull+ };++ public string? Host { get; } = EnvironmentUtil.GetEnvironmentVariable("RCLONE_HOST")?.TrimEnd('/');+ private string? User { get; } = EnvironmentUtil.GetEnvironmentVariable("RCLONE_USER");+ private string? Pass { get; } = EnvironmentUtil.GetEnvironmentVariable("RCLONE_PASS");++ /// <summary>+ /// Refresh the VFS directory cache for multiple paths in a single request.+ /// </summary>+ /// <param name="paths">The paths to refresh</param>+ /// <param name="recursive">Whether to refresh recursively</param>+ /// <param name="fs">Optional VFS name if multiple VFS instances exist</param>+ public async Task<RcloneResponse> RefreshVfsPaths(IEnumerable<string> paths, bool recursive = false,+ string? fs = null)+ {+ var pathList = paths.ToList();+ if (pathList.Count == 0)+ return new RcloneResponse { Success = true };++ var request = new Dictionary<string, object?>();++ // Add paths using numbered keys: dir, dir2, dir3, etc.+ for (int i = 0; i < pathList.Count; i++)+ {+ var key = i == 0 ? "dir" : $"dir{i + 1}";+ request[key] = pathList[i];+ }++ if (recursive)+ request["recursive"] = true;++ if (fs != null)+ request["fs"] = fs;++ Log.Information("Rclone vfs/refresh: {0}", paths.ToIndentedJson());+ return await Post<RcloneResponse>("vfs/refresh", request);+ }++ /// <summary>+ /// Forget (clear) VFS directory cache entries for multiple paths in a single request.+ /// </summary>+ /// <param name="paths">The paths to forget</param>+ /// <param name="fs">Optional VFS name if multiple VFS instances exist</param>+ public async Task<VfsForgetResponse> ForgetVfsPaths(IEnumerable<string> paths, string? fs = null)+ {+ var pathList = paths.ToList();+ if (pathList.Count == 0)+ return new VfsForgetResponse { Success = true, Forgotten = new List<string>() };++ var request = new Dictionary<string, object?>();++ // Add paths using numbered keys: dir, dir2, dir3, etc.+ for (int i = 0; i < pathList.Count; i++)+ {+ var key = i == 0 ? "dir" : $"dir{i + 1}";+ request[key] = pathList[i];+ }++ if (fs != null)+ request["fs"] = fs;++ Log.Information("Rclone vfs/forget: {0}", paths.ToIndentedJson());+ return await Post<VfsForgetResponse>("vfs/forget", request);+ }++ /// <summary>+ /// Get VFS statistics including cache information.+ /// </summary>+ /// <param name="fs">Optional VFS name if multiple VFS instances exist</param>+ public async Task<VfsStatsResponse> GetVfsStats(string? fs = null)+ {+ var request = fs != null ? new { fs } : null;+ return await Post<VfsStatsResponse>("vfs/stats", request);+ }++ /// <summary>+ /// Get rclone version information.+ /// </summary>+ public async Task<CoreVersionResponse> GetVersion()+ {+ return await Post<CoreVersionResponse>("core/version", null);+ }++ /// <summary>+ /// Test connectivity - a no-operation call.+ /// </summary>+ public async Task<RcloneResponse> NoOp()+ {+ return await Post<RcloneResponse>("rc/noop", null);+ }++ /// <summary>+ /// Check if the rclone RC server is reachable and authenticated.+ /// </summary>+ public async Task<bool> IsAvailable()+ {+ try+ {+ await NoOp();+ return true;+ }+ catch+ {+ return false;+ }+ }++ private async Task<T> Post<T>(string endpoint, object? body) where T : RcloneResponse, new()+ {+ var url = $"{Host}/{endpoint}";+ var request = new HttpRequestMessage(HttpMethod.Post, url);++ if (body != null)+ {+ var jsonBody = JsonSerializer.Serialize(body, JsonOptions);+ request.Content = new StringContent(jsonBody, Encoding.UTF8, "application/json");+ }+ else+ {+ request.Content = new StringContent("{}", Encoding.UTF8, "application/json");+ }++ AddAuthHeader(request);++ try+ {+ using var response = await HttpClient.SendAsync(request);+ var content = await response.Content.ReadAsStringAsync();++ if (!response.IsSuccessStatusCode)+ {+ Log.Warning("Rclone RC request to {Endpoint} failed with status {StatusCode}: {Content}",+ endpoint, response.StatusCode, content);++ if (response.StatusCode == HttpStatusCode.Unauthorized)+ {+ return new T { Success = false, Error = "Authentication failed" };+ }++ try+ {+ var errorResponse = JsonSerializer.Deserialize<RcloneErrorResponse>(content, JsonOptions);+ return new T { Success = false, Error = errorResponse?.Error ?? $"HTTP {response.StatusCode}" };+ }+ catch+ {+ return new T { Success = false, Error = $"HTTP {response.StatusCode}: {content}" };+ }+ }++ if (string.IsNullOrWhiteSpace(content) || content == "{}")+ {+ return new T { Success = true };+ }++ var result = JsonSerializer.Deserialize<T>(content, JsonOptions) ?? new T();+ result.Success = true;+ return result;+ }+ catch (HttpRequestException ex)+ {+ Log.Warning(ex, "Rclone RC request to {Endpoint} failed", endpoint);+ return new T { Success = false, Error = ex.Message };+ }+ catch (TaskCanceledException ex)+ {+ Log.Warning(ex, "Rclone RC request to {Endpoint} timed out", endpoint);+ return new T { Success = false, Error = "Request timed out" };+ }+ }++ private void AddAuthHeader(HttpRequestMessage request)+ {+ if (string.IsNullOrEmpty(User) && string.IsNullOrEmpty(Pass))+ return;++ var credentials = $"{User ?? ""}:{Pass ?? ""}";+ var encodedCredentials = Convert.ToBase64String(Encoding.UTF8.GetBytes(credentials));+ request.Headers.Authorization = new AuthenticationHeaderValue("Basic", encodedCredentials);+ }+}\ No newline at end of file