Skip to content

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

C#

Provide maintenance and repair support for strm files.

nzbdav-deva85a4af91c12
diff --git a/backend/Clients/RadarrSonarr/ArrClient.cs b/backend/Clients/RadarrSonarr/ArrClient.cs
index 4c0fa36a..382c674a 100644
--- a/backend/Clients/RadarrSonarr/ArrClient.cs
+++ b/backend/Clients/RadarrSonarr/ArrClient.cs
@@ -15,7 +15,7 @@ public class ArrClient(string host, string apiKey)
public Task<ArrApiInfoResponse> GetApiInfo() =>
GetRoot<ArrApiInfoResponse>($"/api");
- public virtual Task<bool> RemoveAndSearch(string symlinkPath) =>
+ public virtual Task<bool> RemoveAndSearch(string symlinkOrStrmPath) =>
throw new InvalidOperationException();
public Task<List<ArrRootFolder>> GetRootFolders() =>
diff --git a/backend/Clients/RadarrSonarr/RadarrClient.cs b/backend/Clients/RadarrSonarr/RadarrClient.cs
index 8c16dbbd..a9a744e6 100644
--- a/backend/Clients/RadarrSonarr/RadarrClient.cs
+++ b/backend/Clients/RadarrSonarr/RadarrClient.cs
@@ -6,7 +6,7 @@ namespace NzbWebDAV.Clients.RadarrSonarr;
public class RadarrClient(string host, string apiKey) : ArrClient(host, apiKey)
{
- private static readonly Dictionary<string, int> SymlinkToMovieIdCache = new();
+ private static readonly Dictionary<string, int> SymlinkOrStrmToMovieIdCache = new();
public Task<RadarrMovie> GetMovieAsync(int id) =>
Get<RadarrMovie>($"/movie/{id}");
@@ -24,26 +24,26 @@ public class RadarrClient(string host, string apiKey) : ArrClient(host, apiKey)
CommandAsync(new { name = "MoviesSearch", movieIds = new List<int> { id } });
- public override async Task<bool> RemoveAndSearch(string symlinkPath)
+ public override async Task<bool> RemoveAndSearch(string symlinkOrStrmPath)
{
- var mediaIds = await GetMediaIds(symlinkPath);
+ var mediaIds = await GetMediaIds(symlinkOrStrmPath);
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}`.");
+ throw new Exception($"Failed to delete movie file `{symlinkOrStrmPath}` from radarr instance `{Host}`.");
await SearchMovieAsync(mediaIds.Value.movieId);
return true;
}
- private async Task<(int movieFileId, int movieId)?> GetMediaIds(string symlinkPath)
+ private async Task<(int movieFileId, int movieId)?> GetMediaIds(string symlinkOrStrmPath)
{
// 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))
+ if (SymlinkOrStrmToMovieIdCache.TryGetValue(symlinkOrStrmPath, out var movieId))
{
var movie = await GetMovieAsync(movieId);
- if (movie.MovieFile?.Path == symlinkPath)
+ if (movie.MovieFile?.Path == symlinkOrStrmPath)
return (movie.MovieFile.Id!, movieId);
}
@@ -55,8 +55,8 @@ public class RadarrClient(string host, string apiKey) : ArrClient(host, apiKey)
{
var movieFile = movie.MovieFile;
if (movieFile?.Path != null)
- SymlinkToMovieIdCache[movieFile.Path] = movie.Id;
- if (movieFile?.Path == symlinkPath)
+ SymlinkOrStrmToMovieIdCache[movieFile.Path] = movie.Id;
+ if (movieFile?.Path == symlinkOrStrmPath)
result = (movieFile.Id!, movie.Id);
}
diff --git a/backend/Clients/RadarrSonarr/SonarrClient.cs b/backend/Clients/RadarrSonarr/SonarrClient.cs
index 1dc08135..0366f28d 100644
--- a/backend/Clients/RadarrSonarr/SonarrClient.cs
+++ b/backend/Clients/RadarrSonarr/SonarrClient.cs
@@ -8,7 +8,7 @@ namespace NzbWebDAV.Clients.RadarrSonarr;
public class SonarrClient(string host, string apiKey) : ArrClient(host, apiKey)
{
private static readonly Dictionary<string, int> SeriesPathToSeriesIdCache = new();
- private static readonly Dictionary<string, int> SymlinkToEpisodeFileIdCache = new();
+ private static readonly Dictionary<string, int> SymlinkOrStrmToEpisodeFileIdCache = new();
public Task<SonarrQueue> GetSonarrQueueAsync() =>
Get<SonarrQueue>($"/queue?protocol=usenet&pageSize=5000");
@@ -34,25 +34,25 @@ public class SonarrClient(string host, string apiKey) : ArrClient(host, apiKey)
public Task<ArrCommand> SearchEpisodesAsync(List<int> episodeIds) =>
CommandAsync(new { name = "EpisodeSearch", episodeIds });
- public override async Task<bool> RemoveAndSearch(string symlinkPath)
+ public override async Task<bool> RemoveAndSearch(string symlinkOrStrmPath)
{
// get episode-file-id and episode-ids
- var mediaIds = await GetMediaIds(symlinkPath);
+ var mediaIds = await GetMediaIds(symlinkOrStrmPath);
if (mediaIds == null) return false;
// delete the episode-file
if (await DeleteEpisodeFile(mediaIds.Value.episodeFileId) != HttpStatusCode.OK)
- throw new Exception($"Failed to delete episode file `{symlinkPath}` from sonarr instance `{Host}`.");
+ throw new Exception($"Failed to delete episode file `{symlinkOrStrmPath}` from sonarr instance `{Host}`.");
// trigger a new search for each episode
await SearchEpisodesAsync(mediaIds.Value.episodeIds);
return true;
}
- private async Task<(int episodeFileId, List<int> episodeIds)?> GetMediaIds(string symlinkPath)
+ private async Task<(int episodeFileId, List<int> episodeIds)?> GetMediaIds(string symlinkOrStrmPath)
{
// get episode-file-id
- var episodeFileId = await GetEpisodeFileId(symlinkPath);
+ var episodeFileId = await GetEpisodeFileId(symlinkOrStrmPath);
if (episodeFileId == null) return null;
// get episode-ids
@@ -64,25 +64,25 @@ public class SonarrClient(string host, string apiKey) : ArrClient(host, apiKey)
return (episodeFileId.Value, episodeIds);
}
- private async Task<int?> GetEpisodeFileId(string symlinkPath)
+ private async Task<int?> GetEpisodeFileId(string symlinkOrStrmPath)
{
// if episode-file-id is found in the cache, verify it and return it
- if (SymlinkToEpisodeFileIdCache.TryGetValue(symlinkPath, out var episodeFileId))
+ if (SymlinkOrStrmToEpisodeFileIdCache.TryGetValue(symlinkOrStrmPath, out var episodeFileId))
{
var episodeFile = await GetEpisodeFile(episodeFileId);
- if (episodeFile.Path == symlinkPath) return episodeFileId;
+ if (episodeFile.Path == symlinkOrStrmPath) return episodeFileId;
}
// otherwise, find the series-id
- var seriesId = await GetSeriesId(symlinkPath);
+ var seriesId = await GetSeriesId(symlinkOrStrmPath);
if (seriesId == null) return null;
// then use it to find all episode-files and repopulate the cache
int? result = null;
foreach (var episodeFile in await GetAllEpisodeFiles(seriesId.Value))
{
- SymlinkToEpisodeFileIdCache[episodeFile.Path!] = episodeFile.Id;
- if (episodeFile.Path == symlinkPath)
+ SymlinkOrStrmToEpisodeFileIdCache[episodeFile.Path!] = episodeFile.Id;
+ if (episodeFile.Path == symlinkOrStrmPath)
result = episodeFile.Id;
}
@@ -90,10 +90,10 @@ public class SonarrClient(string host, string apiKey) : ArrClient(host, apiKey)
return result;
}
- private async Task<int?> GetSeriesId(string symlinkPath)
+ private async Task<int?> GetSeriesId(string symlinkOrStrmPath)
{
// get series-id from cache
- var cachedSeriesId = PathUtil.GetAllParentDirectories(symlinkPath)
+ var cachedSeriesId = PathUtil.GetAllParentDirectories(symlinkOrStrmPath)
.Where(x => SeriesPathToSeriesIdCache.ContainsKey(x))
.Select(x => SeriesPathToSeriesIdCache[x])
.Select(x => (int?)x)
@@ -103,9 +103,8 @@ public class SonarrClient(string host, string apiKey) : ArrClient(host, apiKey)
if (cachedSeriesId != null)
{
var series = await GetSeries(cachedSeriesId.Value);
- if (symlinkPath.StartsWith(series.Path!))
- return
- cachedSeriesId;
+ if (symlinkOrStrmPath.StartsWith(series.Path!))
+ return cachedSeriesId;
}
// otherwise, fetch all series and repopulate the cache
@@ -113,7 +112,7 @@ public class SonarrClient(string host, string apiKey) : ArrClient(host, apiKey)
foreach (var series in await GetAllSeries())
{
SeriesPathToSeriesIdCache[series.Path!] = series.Id;
- if (symlinkPath.StartsWith(series.Path!))
+ if (symlinkOrStrmPath.StartsWith(series.Path!))
result = series.Id;
}
diff --git a/backend/Services/HealthCheckService.cs b/backend/Services/HealthCheckService.cs
index bfe483ed..b71b50ea 100644
--- a/backend/Services/HealthCheckService.cs
+++ b/backend/Services/HealthCheckService.cs
@@ -227,8 +227,8 @@ public class HealthCheckService
// if the unhealthy item is unlinked/orphaned,
// then we can simply delete it.
- var symlink = OrganizedSymlinksUtil.GetSymlink(davItem, _configManager);
- if (symlink == null)
+ var symlinkOrStrmPath = OrganizedLinksUtil.GetLink(davItem, _configManager);
+ if (symlinkOrStrmPath == null)
{
dbClient.Ctx.Items.Remove(davItem);
dbClient.Ctx.HealthCheckResults.Add(SendStatus(new HealthCheckResult()
@@ -241,7 +241,7 @@ public class HealthCheckService
RepairStatus = HealthCheckResult.RepairAction.Deleted,
Message = string.Join(" ", [
"File had missing articles.",
- "Could not find corresponding symlink within Library Dir.",
+ "Could not find corresponding symlink or strm-file within Library Dir.",
"Deleted file."
])
}));
@@ -249,16 +249,17 @@ public class HealthCheckService
return;
}
- // if the unhealthy item is symlinked within the organized media-library
+ // if the unhealthy item is linked within the organized media-library
// then we must find the corresponding arr instance and trigger a new search.
+ var linkType = symlinkOrStrmPath.ToLower().EndsWith("strm") ? "strm-file" : "symlink";
foreach (var arrClient in _configManager.GetArrConfig().GetArrClients())
{
var rootFolders = await arrClient.GetRootFolders();
- if (!rootFolders.Any(x => symlink.StartsWith(x.Path!))) continue;
+ if (!rootFolders.Any(x => symlinkOrStrmPath.StartsWith(x.Path!))) continue;
// if we found a corresponding arr instance,
// then remove and search.
- if (await arrClient.RemoveAndSearch(symlink))
+ if (await arrClient.RemoveAndSearch(symlinkOrStrmPath))
{
dbClient.Ctx.Items.Remove(davItem);
dbClient.Ctx.HealthCheckResults.Add(SendStatus(new HealthCheckResult()
@@ -271,7 +272,7 @@ public class HealthCheckService
RepairStatus = HealthCheckResult.RepairAction.Repaired,
Message = string.Join(" ", [
"File had missing articles.",
- "Corresponding symlink found within Library Dir.",
+ $"Corresponding {linkType} found within Library Dir.",
"Triggered new Arr search."
])
}));
@@ -281,14 +282,14 @@ public class HealthCheckService
// 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
+ // we can fall back to the behavior below of deleting both the link-file
// 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);
+ // then we can delete both the item and the link-file.
+ File.Delete(symlinkOrStrmPath);
dbClient.Ctx.Items.Remove(davItem);
dbClient.Ctx.HealthCheckResults.Add(SendStatus(new HealthCheckResult()
{
@@ -300,9 +301,9 @@ public class HealthCheckService
RepairStatus = HealthCheckResult.RepairAction.Deleted,
Message = string.Join(" ", [
"File had missing articles.",
- "Corresponding symlink found within Library Dir.",
+ $"Corresponding {linkType} found within Library Dir.",
"Could not find corresponding Radarr/Sonarr media-item to trigger a new search.",
- "Deleted file."
+ $"Deleted the webdav-file and {linkType}."
])
}));
await dbClient.Ctx.SaveChangesAsync(ct);
diff --git a/backend/Tasks/RemoveUnlinkedFilesTask.cs b/backend/Tasks/RemoveUnlinkedFilesTask.cs
index 0fbbd1f7..dc18da54 100644
--- a/backend/Tasks/RemoveUnlinkedFilesTask.cs
+++ b/backend/Tasks/RemoveUnlinkedFilesTask.cs
@@ -40,12 +40,12 @@ public class RemoveUnlinkedFilesTask(
var allDavItems = await dbClient.Ctx.Items.ToListAsync();
// get linked file paths
- Report(dryRun + $"Found {allDavItems.Count} webdav files.\nEnumerating all symlinked files...");
+ Report(dryRun + $"Found {allDavItems.Count} webdav files.\nEnumerating all linked files...");
var linkedIds = GetLinkedIds();
if (linkedIds.Count < 5)
{
Report($"Aborted: " +
- $"There are less than five symlinked files found in your library. " +
+ $"There are less than five linked files found in your library. " +
$"Cancelling operation to prevent accidental bulk deletion.");
return;
}
@@ -109,7 +109,7 @@ public class RemoveUnlinkedFilesTask(
private HashSet<Guid> GetLinkedIds()
{
- return OrganizedSymlinksUtil.GetLibrarySymlinkTargets(configManager)
+ return OrganizedLinksUtil.GetLibraryDavItemLinks(configManager)
.Select(x => x.DavItemId)
.ToHashSet();
}
diff --git a/backend/Utils/OrganizedLinksUtil.cs b/backend/Utils/OrganizedLinksUtil.cs
new file mode 100644
index 00000000..49b1770f
--- /dev/null
+++ b/backend/Utils/OrganizedLinksUtil.cs
@@ -0,0 +1,133 @@
+using NzbWebDAV.Config;
+using NzbWebDAV.Database.Models;
+using NzbWebDAV.Extensions;
+
+namespace NzbWebDAV.Utils;
+
+/// <summary>
+/// Note: In this class, a `Link` refers to either a symlink or strm file.
+/// </summary>
+public static class OrganizedLinksUtil
+{
+ private static readonly Dictionary<Guid, string> Cache = new();
+
+ /// <summary>
+ /// Searches organized media library for a symlink or strm pointing to the given target
+ /// </summary>
+ /// <param name="targetDavItem">The given target</param>
+ /// <param name="configManager">The application config</param>
+ /// <returns>The path to a symlink or strm in the organized media library that points to the given target.</returns>
+ public static string? GetLink(DavItem targetDavItem, ConfigManager configManager)
+ {
+ return !TryGetLinkFromCache(targetDavItem, configManager, out var linkFromCache)
+ ? SearchForLink(targetDavItem, configManager)
+ : linkFromCache;
+ }
+
+ /// <summary>
+ /// Enumerates all DavItemLinks within the organized media library that point to nzbdav dav-items.
+ /// </summary>
+ /// <param name="configManager">The application config</param>
+ /// <returns>All DavItemLinks within the organized media library that point to nzbdav dav-items.</returns>
+ public static IEnumerable<DavItemLink> GetLibraryDavItemLinks(ConfigManager configManager)
+ {
+ var libraryRoot = configManager.GetLibraryDir()!;
+ var allSymlinksAndStrms = SymlinkAndStrmUtil.GetAllSymlinksAndStrms(libraryRoot);
+ return GetDavItemLinks(allSymlinksAndStrms, configManager);
+ }
+
+ private static bool TryGetLinkFromCache
+ (
+ DavItem targetDavItem,
+ ConfigManager configManager,
+ out string? linkFromCache
+ )
+ {
+ return Cache.TryGetValue(targetDavItem.Id, out linkFromCache)
+ && Verify(linkFromCache, targetDavItem, configManager);
+ }
+
+ private static bool Verify(string linkFromCache, DavItem targetDavItem, ConfigManager configManager)
+ {
+ var mountDir = configManager.GetRcloneMountDir();
+ var fileInfo = new FileInfo(linkFromCache);
+ var symlinkOrStrmInfo = SymlinkAndStrmUtil.GetSymlinkOrStrmInfo(fileInfo);
+ if (symlinkOrStrmInfo == null) return false;
+ var davItemLink = GetDavItemLink(symlinkOrStrmInfo, mountDir);
+ return davItemLink?.DavItemId == targetDavItem.Id;
+ }
+
+ private static string? SearchForLink(DavItem targetDavItem, ConfigManager configManager)
+ {
+ string? result = null;
+ foreach (var davItemLink in GetLibraryDavItemLinks(configManager))
+ {
+ Cache[targetDavItem.Id] = davItemLink.LinkPath;
+ if (davItemLink.DavItemId == targetDavItem.Id)
+ result = davItemLink.LinkPath;
+ }
+
+ return result;
+ }
+
+ private static IEnumerable<DavItemLink> GetDavItemLinks
+ (
+ IEnumerable<SymlinkAndStrmUtil.ISymlinkOrStrmInfo> symlinkOrStrmInfos,
+ ConfigManager configManager
+ )
+ {
+ var mountDir = configManager.GetRcloneMountDir();
+ return symlinkOrStrmInfos
+ .Select(x => GetDavItemLink(x, mountDir))
+ .Where(x => x != null)
+ .Select(x => x!.Value);
+ }
+
+ private static DavItemLink? GetDavItemLink
+ (
+ SymlinkAndStrmUtil.ISymlinkOrStrmInfo symlinkOrStrmInfo,
+ string mountDir
+ )
+ {
+ return symlinkOrStrmInfo switch
+ {
+ SymlinkAndStrmUtil.SymlinkInfo symlinkInfo => GetDavItemLink(symlinkInfo, mountDir),
+ SymlinkAndStrmUtil.StrmInfo strmInfo => GetDavItemLink(strmInfo),
+ _ => throw new Exception("Unknown link type")
+ };
+ }
+
+ private static DavItemLink? GetDavItemLink(SymlinkAndStrmUtil.SymlinkInfo symlinkInfo, string mountDir)
+ {
+ var targetPath = symlinkInfo.TargetPath;
+ if (!targetPath.StartsWith(mountDir)) return null;
+ targetPath = targetPath.RemovePrefix(mountDir);
+ targetPath = targetPath.StartsWith('/') ? targetPath : $"/{targetPath}";
+ if (!targetPath.StartsWith("/.ids")) return null;
+ var guid = Path.GetFileNameWithoutExtension(targetPath);
+ return new DavItemLink()
+ {
+ LinkPath = symlinkInfo.SymlinkPath,
+ DavItemId = Guid.Parse(guid)
+ };
+ }
+
+ private static DavItemLink? GetDavItemLink(SymlinkAndStrmUtil.StrmInfo strmInfo)
+ {
+ var targetUrl = strmInfo.TargetUrl;
+ var absolutePath = new Uri(targetUrl).AbsolutePath;
+ if (!absolutePath.StartsWith("/view/.ids")) return null;
+ var guid = Path.GetFileNameWithoutExtension(absolutePath);
+ return new DavItemLink()
+ {
+ LinkPath = strmInfo.StrmPath,
+ DavItemId = Guid.Parse(guid)
+ };
+ }
+
+ public struct DavItemLink
+ {
+ public string LinkPath; // Path to either a symlink or strm file.
+ public Guid DavItemId;
+ }
+}
\ No newline at end of file
diff --git a/backend/Utils/OrganizedSymlinksUtil.cs b/backend/Utils/OrganizedSymlinksUtil.cs
deleted file mode 100644
index 5db9b5e3..00000000
--- a/backend/Utils/OrganizedSymlinksUtil.cs
+++ /dev/null
@@ -1,94 +0,0 @@
-using NzbWebDAV.Config;
-using NzbWebDAV.Database.Models;
-using NzbWebDAV.Extensions;
-
-namespace NzbWebDAV.Utils;
-
-public static class OrganizedSymlinksUtil
-{
- private static readonly Dictionary<Guid, string> Cache = new();
-
- /// <summary>
- /// Searches organized media library for a symlink pointing to the given target
- /// </summary>
- /// <param name="targetDavItem">The given target</param>
- /// <param name="configManager">The application config</param>
- /// <returns>The path to a symlink in the organized media library that points to the given target.</returns>
- public static string? GetSymlink(DavItem targetDavItem, ConfigManager configManager)
- {
- return !TryGetSymlinkFromCache(targetDavItem, configManager, out var symlinkFromCache)
- ? SearchForSymlink(targetDavItem, configManager)
- : symlinkFromCache;
- }
-
- /// <summary>
- /// Enumerates all symlinks within the organized media library that point to nzbdav dav-items.
- /// </summary>
- /// <param name="configManager">The application config</param>
- /// <returns>All symlinks within the organized media library that point to nzbdav dav-items.</returns>
- public static IEnumerable<DavItemSymlink> GetLibrarySymlinkTargets(ConfigManager configManager)
- {
- var libraryRoot = configManager.GetLibraryDir()!;
- var allSymlinks = SymlinkUtil.GetAllSymlinks(libraryRoot);
- return GetDavItemSymlinks(allSymlinks, configManager);
- }
-
- private static bool TryGetSymlinkFromCache
- (
- DavItem targetDavItem,
- ConfigManager configManager,
- out string? symlink
- )
- {
- return Cache.TryGetValue(targetDavItem.Id, out symlink)
- && Verify(symlink, targetDavItem, configManager);
- }
-
- private static bool Verify(string symlink, DavItem targetDavItem, ConfigManager configManager)
- {
- var fileInfo = new FileInfo(symlink);
- var symlinkInfo = new SymlinkUtil.SymlinkInfo()
- {
- SymlinkPath = symlink,
- TargetPath = fileInfo.LinkTarget ?? "",
- };
- return GetDavItemSymlinks([symlinkInfo], configManager)
- .Select(x => x.DavItemId)
- .FirstOrDefault() == targetDavItem.Id;
- }
-
- private static string? SearchForSymlink(DavItem targetDavItem, ConfigManager configManager)
- {
- string? result = null;
- foreach (var symlink in GetLibrarySymlinkTargets(configManager))
- {
- Cache[targetDavItem.Id] = symlink.SymlinkPath;
- if (symlink.DavItemId == targetDavItem.Id)
- result = symlink.SymlinkPath;
- }
-
- return result;
- }
-
- private static IEnumerable<DavItemSymlink> GetDavItemSymlinks
- (
- IEnumerable<SymlinkUtil.SymlinkInfo> symlinkInfos,
- ConfigManager configManager
- )
- {
- var mountDir = configManager.GetRcloneMountDir();
- return symlinkInfos
- .Where(x => x.TargetPath.StartsWith(mountDir))
- .Select(x => x with { TargetPath = x.TargetPath.RemovePrefix(mountDir) })
- .Select(x => x with { TargetPath = x.TargetPath.StartsWith('/') ? x.TargetPath : $"/{x.TargetPath}" })
- .Where(x => x.TargetPath.StartsWith("/.ids"))
- .Select(x => x with { TargetPath = Path.GetFileNameWithoutExtension(x.TargetPath) })
- .Select(x => new DavItemSymlink() { SymlinkPath = x.SymlinkPath, DavItemId = Guid.Parse(x.TargetPath) });
- }
-
- public struct DavItemSymlink
- {
- public string SymlinkPath;
- public Guid DavItemId;
- }
-}
\ No newline at end of file
diff --git a/backend/Utils/SymlinkAndStrmUtil.cs b/backend/Utils/SymlinkAndStrmUtil.cs
new file mode 100644
index 00000000..36237497
--- /dev/null
+++ b/backend/Utils/SymlinkAndStrmUtil.cs
@@ -0,0 +1,106 @@
+using System.Diagnostics;
+using System.Runtime.InteropServices;
+
+namespace NzbWebDAV.Utils;
+
+public static class SymlinkAndStrmUtil
+{
+ private static readonly bool IsLinux = RuntimeInformation.IsOSPlatform(OSPlatform.Linux);
+
+ public static IEnumerable<ISymlinkOrStrmInfo> GetAllSymlinksAndStrms(string directoryPath)
+ {
+ return IsLinux
+ ? GetAllSymlinksAndStrmsLinux(directoryPath)
+ : GetAllSymlinksAndStrmsWindows(directoryPath);
+ }
+
+ private static IEnumerable<ISymlinkOrStrmInfo> GetAllSymlinksAndStrmsLinux(string directoryPath)
+ {
+ const string command =
+ """
+ find . \( -type l -o -name '*.strm' \) -print0 | xargs -0 sh -c '
+ for path in \"$@\"; do
+ echo \"$path\"
+ if [ \"${path##*.}\" = \"strm\" ]; then
+ echo \"$(cat \"$path\")\"
+ else
+ echo \"$(readlink \"$path\")\"
+ fi
+ done
+ ' sh
+ """;
+
+ var escapedDirectory = directoryPath.Replace("'", "'\"'\"'");
+ var startInfo = new ProcessStartInfo
+ {
+ FileName = "sh",
+ Arguments = $"-c \"cd '{escapedDirectory}' && {command}\"",
+ RedirectStandardOutput = true,
+ RedirectStandardError = true,
+ UseShellExecute = false,
+ CreateNoWindow = true
+ };
+
+ using var process = Process.Start(startInfo)!;
+ while (process.StandardOutput.EndOfStream == false)
+ {
+ var filePath = process.StandardOutput.ReadLine();
+ if (filePath == null) break;
+ var target = process.StandardOutput.ReadLine();
+ if (target == null) break;
+
+ if (filePath.ToLower().EndsWith(".strm"))
+ {
+ yield return new StrmInfo()
+ {
+ StrmPath = Path.GetFullPath(filePath, directoryPath),
+ TargetUrl = target
+ };
+ }
+ else
+ {
+ yield return new SymlinkInfo()
+ {
+ SymlinkPath = Path.GetFullPath(filePath, directoryPath),
+ TargetPath = target
+ };
+ }
+ }
+ }
+
+ private static IEnumerable<ISymlinkOrStrmInfo> GetAllSymlinksAndStrmsWindows(string directoryPath)
+ {
+ return Directory.EnumerateFileSystemEntries(directoryPath, "*", SearchOption.AllDirectories)
+ .Select(x => new FileInfo(x))
+ .Select(GetSymlinkOrStrmInfo)
+ .Where(x => x != null)
+ .Select(x => x!);
+ }
+
+ public static ISymlinkOrStrmInfo? GetSymlinkOrStrmInfo(FileInfo x)
+ {
+ return IsStrm(x) ? new StrmInfo() { StrmPath = x.FullName, TargetUrl = File.ReadAllText(x.FullName) }
+ : IsSymLink(x) ? new SymlinkInfo() { SymlinkPath = x.FullName, TargetPath = x.LinkTarget! }
+ : null;
+ }
+
+ private static bool IsStrm(FileInfo x) =>
+ x.Extension.Equals(".strm", StringComparison.CurrentCultureIgnoreCase);
+
+ private static bool IsSymLink(FileInfo x) =>
+ x.Attributes.HasFlag(FileAttributes.ReparsePoint) && x.LinkTarget is not null;
+
+ public interface ISymlinkOrStrmInfo;
+
+ public struct SymlinkInfo : ISymlinkOrStrmInfo
+ {
+ public required string SymlinkPath;
+ public required string TargetPath;
+ }
+
+ public struct StrmInfo : ISymlinkOrStrmInfo
+ {
+ public required string StrmPath;
+ public required string TargetUrl;
+ }
+}
\ No newline at end of file
diff --git a/backend/Utils/SymlinkUtil.cs b/backend/Utils/SymlinkUtil.cs
deleted file mode 100644
index cb284393..00000000
--- a/backend/Utils/SymlinkUtil.cs
+++ /dev/null
@@ -1,70 +0,0 @@
-using System.Diagnostics;
-using System.Runtime.InteropServices;
-
-namespace NzbWebDAV.Utils;
-
-public static class SymlinkUtil
-{
- private static readonly bool IsLinux = RuntimeInformation.IsOSPlatform(OSPlatform.Linux);
-
- public static IEnumerable<SymlinkInfo> GetAllSymlinks(string directoryPath)
- {
- return IsLinux
- ? GetAllSymlinksLinux(directoryPath)
- : GetAllSymlinksWindows(directoryPath);
- }
-
- private static IEnumerable<SymlinkInfo> GetAllSymlinksLinux(string directoryPath)
- {
- const string command =
- """
- find . -type l -print0 | xargs -0 sh -c '
- for link_path in \"$@\"; do
- echo \"$link_path\"
- echo \"$(readlink \"$link_path\")\"
- done
- ' sh
- """;
-
- var escapedDirectory = directoryPath.Replace("'", "'\"'\"'");
- var startInfo = new ProcessStartInfo
- {
- FileName = "sh",
- Arguments = $"-c \"cd '{escapedDirectory}' && {command}\"",
- RedirectStandardOutput = true,
- RedirectStandardError = true,
- UseShellExecute = false,
- CreateNoWindow = true
- };
-
- using var process = Process.Start(startInfo)!;
- while (process.StandardOutput.EndOfStream == false)
- {
- var symlinkPath = process.StandardOutput.ReadLine();
- if (symlinkPath == null) break;
- var targetPath = process.StandardOutput.ReadLine();
- if (targetPath == null) break;
-
- yield return new SymlinkInfo()
- {
- SymlinkPath = Path.GetFullPath(symlinkPath, directoryPath),
- TargetPath = targetPath
- };
- }
- }
-
- private static IEnumerable<SymlinkInfo> GetAllSymlinksWindows(string directoryPath)
- {
- return Directory.EnumerateFileSystemEntries(directoryPath, "*", SearchOption.AllDirectories)
- .Select(x => new FileInfo(x))
- .Where(x => x.Attributes.HasFlag(FileAttributes.ReparsePoint))
- .Where(x => x.LinkTarget is not null)
- .Select(x => new SymlinkInfo() { SymlinkPath = x.FullName, TargetPath = x.LinkTarget! });
- }
-
- public struct SymlinkInfo
- {
- public string SymlinkPath;
- public string TargetPath;
- }
-}
\ No newline at end of file