Skip to content

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

C#

Repair symlinked radarr items when unhealthy.

nzbdav-devf999ef3d1e11
diff --git a/backend/Clients/RadarrSonarr/ArrClient.cs b/backend/Clients/RadarrSonarr/ArrClient.cs
index c7724545..426f290a 100644
--- a/backend/Clients/RadarrSonarr/ArrClient.cs
+++ b/backend/Clients/RadarrSonarr/ArrClient.cs
@@ -1,4 +1,5 @@
using System.Net;
+using System.Net.Http.Json;
using System.Text.Json;
using NzbWebDAV.Clients.RadarrSonarr.BaseModels;
using NzbWebDAV.Config;
@@ -11,9 +12,14 @@ public abstract class ArrClient(string host, string apiKey)
private string ApiKey { get; } = apiKey;
private const string BasePath = "/api/v3";
+ public abstract Task<bool> RemoveAndSearch(string symlinkPath);
+
public Task<List<ArrRootFolder>> GetRootFolders() =>
Get<List<ArrRootFolder>>($"/rootfolder");
+ public Task<ArrCommand> RefreshMonitoredDownloads() =>
+ CommandAsync(new { name = "RefreshMonitoredDownloads" });
+
public Task<ArrQueueStatus> GetQueueStatusAsync() =>
Get<ArrQueueStatus>($"/queue/status");
@@ -28,6 +34,9 @@ public abstract class ArrClient(string host, string apiKey)
? Delete($"/queue/{id}", new DeleteQueueRecordRequest(request).GetQueryParams())
: Task.FromResult(HttpStatusCode.OK);
+ public Task<ArrCommand> CommandAsync(object command) =>
+ Post<ArrCommand>($"/command", command);
+
protected async Task<T> Get<T>(string path)
{
using var httpClient = GetHttpClient();
@@ -35,7 +44,15 @@ public abstract class ArrClient(string host, string apiKey)
return await JsonSerializer.DeserializeAsync<T>(response) ?? throw new NullReferenceException();
}
- private async Task<HttpStatusCode> Delete(string path, Dictionary<string, string>? queryParams = null)
+ protected async Task<T> Post<T>(string path, object body)
+ {
+ using var httpClient = GetHttpClient();
+ using var response = await httpClient.PostAsJsonAsync(GetRequestUri(path), body);
+ 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));
diff --git a/backend/Clients/RadarrSonarr/BaseModels/ArrCommand.cs b/backend/Clients/RadarrSonarr/BaseModels/ArrCommand.cs
new file mode 100644
index 00000000..14f4ce9f
--- /dev/null
+++ b/backend/Clients/RadarrSonarr/BaseModels/ArrCommand.cs
@@ -0,0 +1,24 @@
+using System.Text.Json.Serialization;
+
+namespace NzbWebDAV.Clients.RadarrSonarr.BaseModels;
+
+public class ArrCommand
+{
+ [JsonPropertyName("id")]
+ public int Id { get; set; }
+
+ [JsonPropertyName("name")]
+ public string Name { get; set; }
+
+ [JsonPropertyName("commandName")]
+ public string CommandName { get; set; }
+
+ [JsonPropertyName("result")]
+ public string Result { get; set; }
+
+ [JsonPropertyName("status")]
+ public string Status { get; set; }
+
+ [JsonPropertyName("priority")]
+ public string Priority { get; set; }
+}
\ No newline at end of file
diff --git a/backend/Clients/RadarrSonarr/RadarrClient.cs b/backend/Clients/RadarrSonarr/RadarrClient.cs
index 3474ef6f..8c16dbbd 100644
--- a/backend/Clients/RadarrSonarr/RadarrClient.cs
+++ b/backend/Clients/RadarrSonarr/RadarrClient.cs
@@ -1,12 +1,65 @@
-using NzbWebDAV.Clients.RadarrSonarr.RadarrModels;
+using System.Net;
+using NzbWebDAV.Clients.RadarrSonarr.BaseModels;
+using NzbWebDAV.Clients.RadarrSonarr.RadarrModels;
namespace NzbWebDAV.Clients.RadarrSonarr;
public class RadarrClient(string host, string apiKey) : ArrClient(host, apiKey)
{
+ private static readonly Dictionary<string, int> SymlinkToMovieIdCache = new();
+
+ public Task<RadarrMovie> GetMovieAsync(int id) =>
+ Get<RadarrMovie>($"/movie/{id}");
+
public Task<List<RadarrMovie>> GetMoviesAsync() =>
Get<List<RadarrMovie>>($"/movie");
public Task<RadarrQueue> GetRadarrQueueAsync() =>
Get<RadarrQueue>($"/queue?protocol=usenet&pageSize=5000");
+
+ public Task<HttpStatusCode> DeleteMovieFile(int id) =>
+ Delete($"/moviefile/{id}");
+
+ public Task<ArrCommand> SearchMovieAsync(int id) =>
+ CommandAsync(new { name = "MoviesSearch", movieIds = new List<int> { id } });
+
+
+ public override async Task<bool> RemoveAndSearch(string symlinkPath)
+ {
+ var mediaIds = await GetMediaIds(symlinkPath);
+ if (mediaIds == null) return false;
+
+ if (await DeleteMovieFile(mediaIds.Value.movieFileId) != HttpStatusCode.OK)
+ throw new Exception($"Failed to delete movie file `{symlinkPath}` from radarr instance `{Host}`.");
+
+ await SearchMovieAsync(mediaIds.Value.movieId);
+ return true;
+ }
+
+ private async Task<(int movieFileId, int movieId)?> GetMediaIds(string symlinkPath)
+ {
+ // if we already have the movie-id cached
+ // then let's use it to find and return the corresponding movie-file-id
+ if (SymlinkToMovieIdCache.TryGetValue(symlinkPath, out var movieId))
+ {
+ var movie = await GetMovieAsync(movieId);
+ if (movie.MovieFile?.Path == symlinkPath)
+ return (movie.MovieFile.Id!, movieId);
+ }
+
+ // otherwise, let's fetch all movies, cache all movie files
+ // and return the matching movie-id and movie-file-id
+ var allMovies = await GetMoviesAsync();
+ (int movieFileId, int movieId)? result = null;
+ foreach (var movie in allMovies)
+ {
+ var movieFile = movie.MovieFile;
+ if (movieFile?.Path != null)
+ SymlinkToMovieIdCache[movieFile.Path] = movie.Id;
+ if (movieFile?.Path == symlinkPath)
+ result = (movieFile.Id!, movie.Id);
+ }
+
+ return result;
+ }
}
\ No newline at end of file
diff --git a/backend/Clients/RadarrSonarr/RadarrModels/RadarrMovieFile.cs b/backend/Clients/RadarrSonarr/RadarrModels/RadarrMovieFile.cs
index 4860be26..46db7735 100644
--- a/backend/Clients/RadarrSonarr/RadarrModels/RadarrMovieFile.cs
+++ b/backend/Clients/RadarrSonarr/RadarrModels/RadarrMovieFile.cs
@@ -4,6 +4,9 @@ namespace NzbWebDAV.Clients.RadarrSonarr.RadarrModels;
public class RadarrMovieFile
{
+ [JsonPropertyName("id")]
+ public int Id { get; set; }
+
[JsonPropertyName("path")]
public string? Path { get; set; }
diff --git a/backend/Clients/RadarrSonarr/SonarrClient.cs b/backend/Clients/RadarrSonarr/SonarrClient.cs
index 052b6f43..49b8c7c3 100644
--- a/backend/Clients/RadarrSonarr/SonarrClient.cs
+++ b/backend/Clients/RadarrSonarr/SonarrClient.cs
@@ -6,4 +6,9 @@ public class SonarrClient(string host, string apiKey) : ArrClient(host, apiKey)
{
public Task<SonarrQueue> GetSonarrQueueAsync() =>
Get<SonarrQueue>($"/queue?protocol=usenet&pageSize=5000");
+
+ public override Task<bool> RemoveAndSearch(string symlinkPath)
+ {
+ return Task.FromResult(true);
+ }
}
\ No newline at end of file
diff --git a/backend/Services/HealthCheckService.cs b/backend/Services/HealthCheckService.cs
index 77660f93..1ad42cc9 100644
--- a/backend/Services/HealthCheckService.cs
+++ b/backend/Services/HealthCheckService.cs
@@ -1,4 +1,5 @@
using Microsoft.EntityFrameworkCore;
+using NzbWebDAV.Clients.RadarrSonarr;
using NzbWebDAV.Clients.Usenet;
using NzbWebDAV.Clients.Usenet.Connections;
using NzbWebDAV.Config;
@@ -22,6 +23,10 @@ public class HealthCheckService
private readonly WebsocketManager _websocketManager;
private readonly CancellationToken _cancellationToken = SigtermUtil.GetCancellationToken();
+ private const string NoCorrespondingArrInstance =
+ "Deleted unhealthy symlink and webdav-item. " +
+ "Could not find a corresponding Radarr/Sonarr instance to trigger a new search.";
+
public HealthCheckService
(
ConfigManager configManager,
@@ -75,7 +80,7 @@ public class HealthCheckService
}
catch (Exception e)
{
- Log.Error($"Unexpected error performing background health checks: {e.Message}");
+ Log.Error(e, $"Unexpected error performing background health checks: {e.Message}");
await Task.Delay(TimeSpan.FromSeconds(5), _cancellationToken);
}
}
@@ -126,7 +131,7 @@ public class HealthCheckService
davItem.NextHealthCheck = davItem.ReleaseDate + 2 * (davItem.LastHealthCheck - davItem.ReleaseDate);
dbClient.Ctx.HealthCheckResults.Add(new HealthCheckResult()
{
- Id = new Guid(),
+ Id = Guid.NewGuid(),
DavItemId = davItem.Id,
Path = davItem.Path,
CreatedAt = DateTimeOffset.UtcNow,
@@ -139,6 +144,7 @@ public class HealthCheckService
}
catch (UsenetArticleNotFoundException)
{
+ // when usenet article is missing, perform repairs
_ = _websocketManager.SendMessage(WebsocketTopic.HealthItemProgress, $"{davItem.Id}|100");
_ = _websocketManager.SendMessage(WebsocketTopic.HealthItemStatus, $"{davItem.Id}|unhealthy");
await Repair(davItem, dbClient, ct);
@@ -175,27 +181,104 @@ public class HealthCheckService
private async Task Repair(DavItem davItem, DavDatabaseClient dbClient, CancellationToken ct)
{
- Log.Warning($"Repairing database item: {davItem.Path}");
- var symlink = OrganizedSymlinksUtil.GetSymlink(davItem, _configManager);
-
- // for unlinked files, we can simply delete the unhealthy item
- if (symlink == null)
+ try
{
+ var symlink = OrganizedSymlinksUtil.GetSymlink(davItem, _configManager);
+
+ // if the unhealthy item is unlinked/orphaned,
+ // then we can simply delete it.
+ if (symlink == null)
+ {
+ dbClient.Ctx.Items.Remove(davItem);
+ dbClient.Ctx.HealthCheckResults.Add(new HealthCheckResult()
+ {
+ Id = Guid.NewGuid(),
+ DavItemId = davItem.Id,
+ Path = davItem.Path,
+ CreatedAt = DateTimeOffset.UtcNow,
+ Result = HealthCheckResult.HealthResult.Unhealthy,
+ RepairStatus = HealthCheckResult.RepairAction.Deleted,
+ Message = null
+ });
+ await dbClient.Ctx.SaveChangesAsync(ct);
+ return;
+ }
+
+ // if the unhealthy item is symlinked within the organized media-library
+ // then we must find the corresponding arr instance and trigger a new search.
+ foreach (var arrClient in _configManager.GetArrConfig().GetArrClients())
+ {
+ var rootFolders = await arrClient.GetRootFolders();
+ if (!rootFolders.Any(x => symlink.StartsWith(x.Path!))) continue;
+
+ // if we found corresponding sonarr instance,
+ // then do nothing for now. It is not yet implemented.
+ if (arrClient is SonarrClient)
+ {
+ Log.Warning($"Found corresponding arr instance for repair: {arrClient.Host}");
+ return;
+ }
+
+ // if we found a corresponding radarr instance,
+ // then remove and search.
+ if (await arrClient.RemoveAndSearch(symlink))
+ {
+ dbClient.Ctx.Items.Remove(davItem);
+ dbClient.Ctx.HealthCheckResults.Add(new HealthCheckResult()
+ {
+ Id = Guid.NewGuid(),
+ DavItemId = davItem.Id,
+ Path = davItem.Path,
+ CreatedAt = DateTimeOffset.UtcNow,
+ Result = HealthCheckResult.HealthResult.Unhealthy,
+ RepairStatus = HealthCheckResult.RepairAction.Repaired,
+ Message = null
+ });
+ await dbClient.Ctx.SaveChangesAsync(ct);
+ return;
+ }
+
+ // if we could not find corresponding media-item to remove-and-search
+ // within the found arr instance, then break out of this loop so that
+ // we can fall back to the behavior below of deleting both the symlink
+ // and the dav-item.
+ break;
+ }
+
+ // if we could not find a corresponding arr instance
+ // then we can delete both the item and the symlink.
+ File.Delete(symlink);
dbClient.Ctx.Items.Remove(davItem);
dbClient.Ctx.HealthCheckResults.Add(new HealthCheckResult()
{
- Id = new Guid(),
+ Id = Guid.NewGuid(),
DavItemId = davItem.Id,
Path = davItem.Path,
CreatedAt = DateTimeOffset.UtcNow,
Result = HealthCheckResult.HealthResult.Unhealthy,
RepairStatus = HealthCheckResult.RepairAction.Deleted,
- Message = null
+ Message = NoCorrespondingArrInstance
+ });
+ await dbClient.Ctx.SaveChangesAsync(ct);
+ }
+ catch (Exception e)
+ {
+ // if an error is encountered during repairs,
+ // then mark the item as unhealthy
+ var utcNow = DateTimeOffset.UtcNow;
+ davItem.LastHealthCheck = utcNow;
+ davItem.NextHealthCheck = null;
+ dbClient.Ctx.HealthCheckResults.Add(new HealthCheckResult()
+ {
+ Id = Guid.NewGuid(),
+ DavItemId = davItem.Id,
+ Path = davItem.Path,
+ CreatedAt = utcNow,
+ Result = HealthCheckResult.HealthResult.Unhealthy,
+ RepairStatus = HealthCheckResult.RepairAction.ActionNeeded,
+ Message = e.Message
});
await dbClient.Ctx.SaveChangesAsync(ct);
- return;
}
-
- Log.Warning($"Symlink found in organized media library: {symlink}");
}
}
\ No newline at end of file