Skip to content

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

C#

Added backend support for strm-based import strategy.

nzbdav-devc32dd560c646
diff --git a/backend/Api/Controllers/GetWebdavItem/GetWebdavItemController.cs b/backend/Api/Controllers/GetWebdavItem/GetWebdavItemController.cs
index 8f2bf63b..965d6268 100644
--- a/backend/Api/Controllers/GetWebdavItem/GetWebdavItemController.cs
+++ b/backend/Api/Controllers/GetWebdavItem/GetWebdavItemController.cs
@@ -62,6 +62,7 @@ public class ListWebdavDirectoryController(DatabaseStore store, ConfigManager co
{
try
{
+ 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);
diff --git a/backend/Api/Controllers/GetWebdavItem/GetWebdavItemRequest.cs b/backend/Api/Controllers/GetWebdavItem/GetWebdavItemRequest.cs
index 3aa1444a..f4639363 100644
--- a/backend/Api/Controllers/GetWebdavItem/GetWebdavItemRequest.cs
+++ b/backend/Api/Controllers/GetWebdavItem/GetWebdavItemRequest.cs
@@ -1,6 +1,7 @@
using System.Security.Cryptography;
using System.Text;
using Microsoft.AspNetCore.Http;
+using NzbWebDAV.Config;
using NzbWebDAV.Utils;
namespace NzbWebDAV.Api.Controllers.GetWebdavItem;
@@ -20,12 +21,12 @@ public class GetWebdavItemRequest
if (path.StartsWith("/")) path = path[1..];
Item = path;
- // skip auth check for now
+ // authenticate the downloadKey
var downloadKey = context.Request.Query["downloadKey"];
- if (!VerifyDownloadKey(downloadKey, Item))
+ var configManager = (ConfigManager)context.Items["configManager"]!;
+ if (!VerifyDownloadKey(downloadKey, Item, configManager))
throw new UnauthorizedAccessException("Invalid download key");
-
// parse range header
var rangeHeader = context.Request.Headers["Range"].FirstOrDefault() ?? "";
if (!rangeHeader.StartsWith("bytes=")) return;
@@ -34,14 +35,27 @@ public class GetWebdavItemRequest
if (parts.Length > 1) RangeEnd = long.Parse(parts[1]);
}
-
- public static bool VerifyDownloadKey(string? downloadKey, string path)
+ private static bool VerifyDownloadKey(string? downloadKey, string path, ConfigManager configManager)
{
+ if (path.StartsWith(".ids"))
+ {
+ // strm streams link items by id and use a different download key
+ var strmKey = configManager.GetStrmKey();
+ var expectedDownloadKey = GenerateDownloadKey(strmKey, path);
+ if (downloadKey == expectedDownloadKey)
+ return true;
+ }
+
var apiKey = EnvironmentUtil.GetVariable("FRONTEND_BACKEND_API_KEY");
+ return downloadKey == GenerateDownloadKey(apiKey, path);
+ }
+
+ public static string GenerateDownloadKey(string apiKey, string path)
+ {
var input = $"{path}_{apiKey}";
var inputBytes = Encoding.UTF8.GetBytes(input);
var hashBytes = SHA256.HashData(inputBytes);
var hash = Convert.ToHexStringLower(hashBytes);
- return downloadKey == hash;
+ return hash;
}
}
\ No newline at end of file
diff --git a/backend/Api/SabControllers/GetConfig/GetConfigController.cs b/backend/Api/SabControllers/GetConfig/GetConfigController.cs
index 6b884208..b1896497 100644
--- a/backend/Api/SabControllers/GetConfig/GetConfigController.cs
+++ b/backend/Api/SabControllers/GetConfig/GetConfigController.cs
@@ -24,8 +24,7 @@ public class GetConfigController(
var root = JsonNode.Parse(config)!;
// update the complete_dir
- var completeDir = Path.Join(configManager.GetRcloneMountDir(), DavItem.SymlinkFolder.Name);
- root["config"]!["misc"]!["complete_dir"] = completeDir;
+ root["config"]!["misc"]!["complete_dir"] = GetCompletedDir();
// update the categories
var categoriesRoot = root["config"]?["categories"]?.AsArray()!;
@@ -52,4 +51,11 @@ public class GetConfigController(
var response = root.ToJsonString(options);
return Content(response, "application/json");
}
+
+ private string GetCompletedDir()
+ {
+ return configManager.GetImportStrategy() == "strm"
+ ? configManager.GetStrmCompletedDownloadDir()
+ : Path.Join(configManager.GetRcloneMountDir(), DavItem.SymlinkFolder.Name);
+ }
}
\ No newline at end of file
diff --git a/backend/Api/SabControllers/GetHistory/GetHistoryController.cs b/backend/Api/SabControllers/GetHistory/GetHistoryController.cs
index 1f490feb..485ec0d0 100644
--- a/backend/Api/SabControllers/GetHistory/GetHistoryController.cs
+++ b/backend/Api/SabControllers/GetHistory/GetHistoryController.cs
@@ -51,7 +51,7 @@ public class GetHistoryController(
GetHistoryResponse.HistorySlot.FromHistoryItem(
x,
x.DownloadDirId != null ? davItemsDict.GetValueOrDefault(x.DownloadDirId.Value) : null,
- configManager.GetRcloneMountDir()
+ configManager
)
)
.ToList();
diff --git a/backend/Api/SabControllers/GetHistory/GetHistoryResponse.cs b/backend/Api/SabControllers/GetHistory/GetHistoryResponse.cs
index 395385be..6467db9b 100644
--- a/backend/Api/SabControllers/GetHistory/GetHistoryResponse.cs
+++ b/backend/Api/SabControllers/GetHistory/GetHistoryResponse.cs
@@ -1,4 +1,5 @@
using System.Text.Json.Serialization;
+using NzbWebDAV.Config;
using NzbWebDAV.Database.Models;
namespace NzbWebDAV.Api.SabControllers.GetHistory;
@@ -47,7 +48,12 @@ public class GetHistoryResponse : SabBaseResponse
[JsonPropertyName("fail_message")]
public string FailMessage { get; set; }
- public static HistorySlot FromHistoryItem(HistoryItem historyItem, DavItem? downloadFolder, string mountDir)
+ public static HistorySlot FromHistoryItem
+ (
+ HistoryItem historyItem,
+ DavItem? downloadFolder,
+ ConfigManager configManager
+ )
{
return new HistorySlot()
{
@@ -57,16 +63,47 @@ public class GetHistoryResponse : SabBaseResponse
Category = historyItem.Category,
Status = historyItem.DownloadStatus,
SizeInBytes = historyItem.TotalSegmentBytes,
- DownloadPath = downloadFolder == null ? null : Path.Join(new[]
+ DownloadPath = GetDownloadPath(historyItem, downloadFolder, configManager),
+ DownloadTimeSeconds = historyItem.DownloadTimeSeconds,
+ FailMessage = historyItem.FailMessage ?? "",
+ };
+ }
+
+ private static string? GetDownloadPath
+ (
+ HistoryItem historyItem,
+ DavItem? downloadFolder,
+ ConfigManager configManager
+ )
+ {
+ // return null for null download folder
+ if (downloadFolder == null) return null;
+ var importStrategy = configManager.GetImportStrategy();
+
+ // return completed-downloads path
+ if (importStrategy == "strm")
+ {
+ return Path.Join(new[]
{
- mountDir,
+ configManager.GetStrmCompletedDownloadDir(),
+ historyItem.Category,
+ downloadFolder.Name
+ });
+ }
+
+ // return completed-symlinks path
+ if (importStrategy == "symlinks")
+ {
+ return Path.Join(new[]
+ {
+ configManager.GetRcloneMountDir(),
DavItem.SymlinkFolder.Name,
historyItem.Category,
downloadFolder.Name
- }),
- DownloadTimeSeconds = historyItem.DownloadTimeSeconds,
- FailMessage = historyItem.FailMessage ?? "",
- };
+ });
+ }
+
+ throw new Exception("Unknown import strategy");
}
}
}
\ No newline at end of file
diff --git a/backend/Config/ConfigManager.cs b/backend/Config/ConfigManager.cs
index e17d0ea5..df0f8be0 100644
--- a/backend/Config/ConfigManager.cs
+++ b/backend/Config/ConfigManager.cs
@@ -58,9 +58,11 @@ public class ConfigManager
public string GetRcloneMountDir()
{
- return StringUtil.EmptyToNull(GetConfigValue("rclone.mount-dir"))
+ var mountDir = StringUtil.EmptyToNull(GetConfigValue("rclone.mount-dir"))
?? StringUtil.EmptyToNull(Environment.GetEnvironmentVariable("MOUNT_DIR"))
?? "/mnt/nzbdav";
+ if (mountDir.EndsWith('/')) mountDir = mountDir.TrimEnd('/');
+ return mountDir;
}
public string GetApiKey()
@@ -69,6 +71,12 @@ public class ConfigManager
?? EnvironmentUtil.GetVariable("FRONTEND_BACKEND_API_KEY");
}
+ public string GetStrmKey()
+ {
+ return GetConfigValue("api.strm-key")
+ ?? throw new InvalidOperationException("The `api.strm-key` config does not exist.");
+ }
+
public string GetApiCategories()
{
return StringUtil.EmptyToNull(GetConfigValue("api.categories"))
@@ -211,6 +219,21 @@ public class ConfigManager
.ToHashSet();
}
+ public string GetImportStrategy()
+ {
+ return GetConfigValue("api.import-strategy") ?? "symlinks";
+ }
+
+ public string GetStrmCompletedDownloadDir()
+ {
+ return GetConfigValue("api.completed-downloads-dir") ?? "/data/completed-downloads";
+ }
+
+ public string GetBaseUrl()
+ {
+ return GetConfigValue("general.base-url") ?? "http://localhost:3000";
+ }
+
public class ConfigEventArgs : EventArgs
{
public Dictionary<string, string> ChangedConfig { get; set; } = new();
diff --git a/backend/Queue/PostProcessors/CreateStrmFilesPostProcessor.cs b/backend/Queue/PostProcessors/CreateStrmFilesPostProcessor.cs
new file mode 100644
index 00000000..e762ae95
--- /dev/null
+++ b/backend/Queue/PostProcessors/CreateStrmFilesPostProcessor.cs
@@ -0,0 +1,55 @@
+using Microsoft.EntityFrameworkCore;
+using NzbWebDAV.Api.Controllers.GetWebdavItem;
+using NzbWebDAV.Config;
+using NzbWebDAV.Database;
+using NzbWebDAV.Database.Models;
+using NzbWebDAV.Utils;
+using NzbWebDAV.WebDav;
+using Serilog;
+
+namespace NzbWebDAV.Queue.PostProcessors;
+
+public class CreateStrmFilesPostProcessor(ConfigManager configManager, DavDatabaseClient dbClient)
+{
+ public void CreateStrmFiles()
+ {
+ // Add strm files to the download dir
+ var videoItems = dbClient.Ctx.ChangeTracker.Entries<DavItem>()
+ .Where(x => x.State == EntityState.Added)
+ .Select(x => x.Entity)
+ .Where(x => x.Type != DavItem.ItemType.Directory)
+ .Where(x => FilenameUtil.IsVideoFile(x.Name));
+ foreach (var videoItem in videoItems)
+ CreateStrmFile(videoItem);
+ }
+
+ private void CreateStrmFile(DavItem davItem)
+ {
+ // create necessary directories if they don't already exist
+ var strmFilePath = GetStrmFilePath(davItem);
+ var directoryName = Path.GetDirectoryName(strmFilePath);
+ if (directoryName != null) Directory.CreateDirectory(directoryName);
+
+ // create the strm file
+ var targetUrl = GetStrmTargetUrl(davItem);
+ File.WriteAllText(strmFilePath, targetUrl);
+ }
+
+ private string GetStrmFilePath(DavItem davItem)
+ {
+ var path = davItem.Path + ".strm";
+ var parts = path.Split(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
+ return Path.Join(configManager.GetStrmCompletedDownloadDir(), Path.Join(parts[2..]));
+ }
+
+ private string GetStrmTargetUrl(DavItem davItem)
+ {
+ var baseUrl = configManager.GetBaseUrl();
+ if (baseUrl.EndsWith('/')) baseUrl = baseUrl.TrimEnd('/');
+ var pathUrl = DatabaseStoreSymlinkFile.GetTargetPath(davItem, "", '/');
+ if (pathUrl.StartsWith('/')) pathUrl = pathUrl.TrimStart('/');
+ var strmKey = configManager.GetStrmKey();
+ var downloadKey = GetWebdavItemRequest.GenerateDownloadKey(strmKey, pathUrl);
+ return $"{baseUrl}/view/{pathUrl}?downloadKey={downloadKey}";
+ }
+}
\ No newline at end of file
diff --git a/backend/Queue/QueueItemProcessor.cs b/backend/Queue/QueueItemProcessor.cs
index 70a8f011..a9a13675 100644
--- a/backend/Queue/QueueItemProcessor.cs
+++ b/backend/Queue/QueueItemProcessor.cs
@@ -183,6 +183,10 @@ public class QueueItemProcessor(
if (configManager.IsEnsureImportableVideoEnabled())
new EnsureImportableVideoValidator(dbClient).ThrowIfValidationFails();
+ // create strm files, if necessary
+ if (configManager.GetImportStrategy() == "strm")
+ new CreateStrmFilesPostProcessor(configManager, dbClient).CreateStrmFiles();
+
return mountFolder;
});
}
@@ -333,9 +337,8 @@ public class QueueItemProcessor(
{
dbClient.Ctx.ChangeTracker.Clear();
var mountFolder = databaseOperations != null ? await databaseOperations.Invoke() : null;
- var mountDirectory = configManager.GetRcloneMountDir();
var historyItem = CreateHistoryItem(mountFolder, startTime, error);
- var historySlot = GetHistoryResponse.HistorySlot.FromHistoryItem(historyItem, mountFolder, mountDirectory);
+ var historySlot = GetHistoryResponse.HistorySlot.FromHistoryItem(historyItem, mountFolder, configManager);
dbClient.Ctx.QueueItems.Remove(queueItem);
dbClient.Ctx.HistoryItems.Add(historyItem);
await dbClient.Ctx.SaveChangesAsync(ct);
diff --git a/backend/WebDav/DatabaseStoreSymlinkFile.cs b/backend/WebDav/DatabaseStoreSymlinkFile.cs
index 6b9da271..6031cabb 100644
--- a/backend/WebDav/DatabaseStoreSymlinkFile.cs
+++ b/backend/WebDav/DatabaseStoreSymlinkFile.cs
@@ -24,7 +24,7 @@ public class DatabaseStoreSymlinkFile(DavItem davFile, ConfigManager configManag
return GetTargetPath(davFile, configManager.GetRcloneMountDir());
}
- public static string GetTargetPath(DavItem davFile, string mountDir)
+ public static string GetTargetPath(DavItem davFile, string mountDir, char? pathSeparator = null)
{
var pathParts = davFile.IdPrefix
.Select(x => x.ToString())
@@ -32,6 +32,6 @@ public class DatabaseStoreSymlinkFile(DavItem davFile, ConfigManager configManag
.Prepend(mountDir)
.Append(davFile.Id.ToString())
.ToArray();
- return Path.Join(pathParts);
+ return string.Join(pathSeparator ?? Path.DirectorySeparatorChar, pathParts);
}
}
\ No newline at end of file