Compare commits
No commits in common. "main" and "v2.0.131" have entirely different histories.
57 changed files with 672 additions and 2193 deletions
|
|
@ -1,14 +0,0 @@
|
|||
FROM mcr.microsoft.com/devcontainers/dotnet:2-10.0-noble
|
||||
|
||||
ARG NODE_MAJOR=22
|
||||
ARG ANGULAR_CLI_VERSION=21
|
||||
|
||||
RUN curl -fsSL "https://deb.nodesource.com/setup_${NODE_MAJOR}.x" | bash - \
|
||||
&& apt-get update \
|
||||
&& apt-get install -y --no-install-recommends nodejs sqlite3 \
|
||||
&& npm install -g "@angular/cli@^${ANGULAR_CLI_VERSION}" \
|
||||
&& apt-get clean \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
RUN mkdir -p /data/db /data/downloads \
|
||||
&& chown -R vscode:vscode /data
|
||||
|
|
@ -1,51 +0,0 @@
|
|||
{
|
||||
"name": "rdt-client",
|
||||
"build": {
|
||||
"dockerfile": "Dockerfile",
|
||||
"args": {
|
||||
"NODE_MAJOR": "22"
|
||||
}
|
||||
},
|
||||
"remoteUser": "vscode",
|
||||
"runArgs": ["--init"],
|
||||
"containerEnv": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development",
|
||||
"BASE_PATH": "",
|
||||
"DOTNET_USE_POLLING_FILE_WATCHER": "1",
|
||||
"CHOKIDAR_USEPOLLING": "true"
|
||||
},
|
||||
"forwardPorts": [4200, 6500],
|
||||
"portsAttributes": {
|
||||
"4200": {
|
||||
"label": "Angular client",
|
||||
"onAutoForward": "notify"
|
||||
},
|
||||
"6500": {
|
||||
"label": "RdtClient backend",
|
||||
"onAutoForward": "silent"
|
||||
}
|
||||
},
|
||||
"mounts": [
|
||||
"source=rdtclient-data-db,target=/data/db,type=volume",
|
||||
"source=rdtclient-data-downloads,target=/data/downloads,type=volume",
|
||||
"source=rdtclient-nuget,target=/home/vscode/.nuget,type=volume",
|
||||
"source=rdtclient-npm-cache,target=/home/vscode/.npm,type=volume"
|
||||
],
|
||||
"postCreateCommand": "/bin/bash .devcontainer/post-create.sh",
|
||||
"postStartCommand": "/bin/bash .devcontainer/post-start.sh",
|
||||
"customizations": {
|
||||
"vscode": {
|
||||
"extensions": [
|
||||
"ms-dotnettools.csharp",
|
||||
"ms-dotnettools.csdevkit",
|
||||
"Angular.ng-template",
|
||||
"dbaeumer.vscode-eslint",
|
||||
"esbenp.prettier-vscode"
|
||||
],
|
||||
"settings": {
|
||||
"dotnet.defaultSolution": "server/RdtClient.sln",
|
||||
"terminal.integrated.defaultProfile.linux": "zsh"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,16 +0,0 @@
|
|||
#!/usr/bin/env bash
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
sudo install -d -m 0775 -o vscode -g vscode \
|
||||
/data/db \
|
||||
/data/downloads \
|
||||
/home/vscode/.nuget \
|
||||
/home/vscode/.nuget/NuGet \
|
||||
/home/vscode/.nuget/packages \
|
||||
/home/vscode/.npm
|
||||
|
||||
sudo chown -R vscode:vscode /data /home/vscode/.nuget /home/vscode/.npm
|
||||
|
||||
dotnet restore server/RdtClient.sln
|
||||
npm install --prefix client
|
||||
|
|
@ -1,13 +0,0 @@
|
|||
#!/usr/bin/env bash
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
sudo install -d -m 0775 -o vscode -g vscode \
|
||||
/data/db \
|
||||
/data/downloads \
|
||||
/home/vscode/.nuget \
|
||||
/home/vscode/.nuget/NuGet \
|
||||
/home/vscode/.nuget/packages \
|
||||
/home/vscode/.npm
|
||||
|
||||
sudo chown -R vscode:vscode /data /home/vscode/.nuget /home/vscode/.npm
|
||||
1
.gitignore
vendored
1
.gitignore
vendored
|
|
@ -8,4 +8,3 @@ server/RdtClient.Web/appsettings.Development.json
|
|||
data
|
||||
Dockerfile.dev
|
||||
test.bat
|
||||
.DS_Store
|
||||
|
|
|
|||
34
CHANGELOG.md
34
CHANGELOG.md
|
|
@ -6,40 +6,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|||
|
||||
## [Unreleased
|
||||
|
||||
## [2.0.138] - 2026-06-05
|
||||
### Fixed
|
||||
- SABnzbd fixes.
|
||||
|
||||
## [2.0.137] - 2026-06-05
|
||||
### Fixed
|
||||
- Fix torbox save path mapping for single file downloads.
|
||||
|
||||
## [2.0.136] - 2026-05-30
|
||||
### Added
|
||||
- Added devcontainer development workflow.
|
||||
|
||||
### Changed
|
||||
- Upgraded torbox.net dependency.
|
||||
|
||||
## [2.0.135] - 2026-05-27
|
||||
### Changed
|
||||
- When adding a torrent through the qBittorrent endpoints, it will wait to see if the torrent gets added properly or errors out, resulting in a better experience for infringing files and Sonarr / Radarr.
|
||||
- Upgraded torbox.net dependency.
|
||||
- Support SABnzbd API key auth, thanks to @ALenfant!
|
||||
|
||||
## [2.0.134] - 2026-05-22
|
||||
### Changed
|
||||
- Upgraded torbox.net dependency.
|
||||
|
||||
## [2.0.133] - 2026-05-17
|
||||
### Added
|
||||
- Added NZB support for Premiumize, thanks to @ALenfant!
|
||||
|
||||
## [2.0.132] - 2026-05-17
|
||||
### Changed
|
||||
- Fixed for Cleanuparr
|
||||
- Upgrade Torbox.NET dependency
|
||||
|
||||
## [2.0.131] - 2026-05-14
|
||||
### Changed
|
||||
- Fixes to the rate limiting.
|
||||
|
|
|
|||
35
README.md
35
README.md
|
|
@ -3,7 +3,7 @@
|
|||
This is a web interface to manage your torrents on Real-Debrid, AllDebrid, Premiumize, TorBox or DebridLink. It supports the following features:
|
||||
|
||||
- Add new torrents through magnets or files
|
||||
- Add usenet downloads through NZB files (TorBox and Premiumize only)
|
||||
- Add usenet downloads through NZB files (TorBox only)
|
||||
- Download all files from Real-Debrid, AllDebrid, Premiumize or TorBox to your local machine automatically
|
||||
- Unpack all files when finished downloading
|
||||
- Implements a fake qBittorrent API so you can hook up other applications like Sonarr, Radarr or Couchpotato.
|
||||
|
|
@ -166,9 +166,7 @@ It has the following options:
|
|||
|
||||
### Connecting Sonarr/Radarr
|
||||
|
||||
RdtClient emulates the qBittorrent web protocol and allows applications to use those APIs. This way you can use Sonarr and Radarr to download directly from RealDebrid.
|
||||
|
||||
#### Torrents
|
||||
RdtClient emulates the qBittorrent web protocol and allow applications to use those APIs. This way you can use Sonarr and Radarr to download directly from RealDebrid.
|
||||
|
||||
1. Login to Sonarr or Radarr and click `Settings`.
|
||||
1. Go to the `Download Client` tab and click the plus to add.
|
||||
|
|
@ -185,24 +183,6 @@ When downloading files it will append the `category` setting in the Sonarr/Radar
|
|||
|
||||
Notice: the progress and ETA reported in Sonarr's Activity tab will not be accurate, but it will report the torrent as completed so it can be processed after it is done downloading.
|
||||
|
||||
#### Usenet/NZB
|
||||
|
||||
RdtClient also emulates part of the SABnzbd API so Sonarr and Radarr can add NZB downloads. This requires a provider that supports Usenet/NZB downloads, currently TorBox or Premiumize.
|
||||
|
||||
1. Login to Sonarr or Radarr and click `Settings`.
|
||||
1. Go to the `Download Client` tab and click the plus to add.
|
||||
1. Click `SABnzbd` in the list.
|
||||
1. Enter the IP or hostname of RdtClient in the `Host` field.
|
||||
1. Enter `6500` in the `Port` field.
|
||||
1. Enable `Use SSL` only if you access RdtClient through HTTPS.
|
||||
1. Leave `URL Base` empty unless RdtClient is configured with a `BasePath`, for example `/rdt`.
|
||||
1. If RdtClient authentication is enabled, leave `API Key` empty and enter your RdtClient username and password. If your client only supports an API key, enter `{username}:{password}` in `API Key`.
|
||||
1. If RdtClient authentication is disabled, enter any value in `API Key`, for example `rdtclient`, and leave username/password empty.
|
||||
1. Set the category to `sonarr` for Sonarr or `radarr` for Radarr.
|
||||
1. Hit `Test` and then `Save` if all is well.
|
||||
|
||||
When importing completed NZB downloads, Sonarr/Radarr must be able to access the path reported by RdtClient. In Docker setups this may require a Remote Path Mapping from the RdtClient download path to the path mounted inside Sonarr/Radarr.
|
||||
|
||||
### Running within a folder
|
||||
|
||||
By default the application runs in the root of your hosted address (i.e. https://rdt.myserver.com/), but if you want to run it as a relative folder (i.e. https://myserver.com/rdt) you will have to change the `BasePath` setting in the `appsettings.json` file. You can set the `BASE_PATH` environment variable for docker enviroments.
|
||||
|
|
@ -218,17 +198,6 @@ By default the application runs in the root of your hosted address (i.e. https:/
|
|||
- Visual Studio 2025
|
||||
- (optional) Resharper
|
||||
|
||||
### Dev Container
|
||||
|
||||
The repository includes a dev container under `.devcontainer/` for the split development workflow used by this project.
|
||||
|
||||
It installs .NET 10 and Node 22, forwards ports `4200` and `6500`, and persists `/data/db` and `/data/downloads` in named volumes so the local SQLite database, logs, and downloads survive container rebuilds.
|
||||
|
||||
1. Open the repository in the dev container.
|
||||
1. In one terminal run `dotnet watch run --project server/RdtClient.Web`.
|
||||
1. In another terminal run `cd client && npm start`.
|
||||
1. Open `http://localhost:4200`. The Angular dev server proxies `/Api` and `/hub` to the backend running on `6500`.
|
||||
|
||||
1. Open the client folder project in VS Code and run `npm install`.
|
||||
1. To debug run `ng serve`, to build run `ng build -c production`.
|
||||
1. Open the Visual Studio 2025 project `RdtClient.sln` and `Publish` the `RdtClient.Web` to the given `PublishFolder` target.
|
||||
|
|
|
|||
|
|
@ -98,8 +98,6 @@ export function getTorrentStatus(torrent: Torrent): string {
|
|||
return 'Finished';
|
||||
}
|
||||
|
||||
const prefix = torrent.type === 1 ? 'NZB' : 'Torrent';
|
||||
|
||||
switch (torrent.rdStatus) {
|
||||
case RealDebridStatus.Queued:
|
||||
return 'Not Yet Added to Provider';
|
||||
|
|
@ -108,17 +106,17 @@ export function getTorrentStatus(torrent: Torrent): string {
|
|||
return 'Torrent stalled';
|
||||
}
|
||||
|
||||
return `${prefix} downloading (${torrent.rdProgress}% - ${fileSizePipe.transform(torrent.rdSpeed, 'filesize') as string}/s)`;
|
||||
return `Torrent downloading (${torrent.rdProgress}% - ${fileSizePipe.transform(torrent.rdSpeed, 'filesize') as string}/s)`;
|
||||
case RealDebridStatus.Processing:
|
||||
return `${prefix} processing`;
|
||||
return 'Torrent processing';
|
||||
case RealDebridStatus.WaitingForFileSelection:
|
||||
return `${prefix} waiting for file selection`;
|
||||
return 'Torrent waiting for file selection';
|
||||
case RealDebridStatus.Error:
|
||||
return `${prefix} error: ${torrent.rdStatusRaw}`;
|
||||
return `Torrent error: ${torrent.rdStatusRaw}`;
|
||||
case RealDebridStatus.Finished:
|
||||
return `${prefix} finished, waiting for download links`;
|
||||
return 'Torrent finished, waiting for download links';
|
||||
case RealDebridStatus.Uploading:
|
||||
return `${prefix} uploading`;
|
||||
return 'Torrent uploading';
|
||||
default:
|
||||
return 'Unknown status';
|
||||
}
|
||||
|
|
|
|||
|
|
@ -74,7 +74,6 @@ public class DownloadData(DataContext dataContext, ILogger<DownloadData>? logger
|
|||
|
||||
return DownloadAddResult.Added;
|
||||
}
|
||||
|
||||
// These shouldn't be possible any longer, but added for safety and until confirmed.
|
||||
catch (DbUpdateException ex)
|
||||
{
|
||||
|
|
@ -89,9 +88,7 @@ public class DownloadData(DataContext dataContext, ILogger<DownloadData>? logger
|
|||
|
||||
if (IsForeignKeyViolation(ex) && !await dataContext.Torrents.AsNoTracking().AnyAsync(m => m.TorrentId == torrentId))
|
||||
{
|
||||
logger?.LogDebug("Skipped download creation after the torrent was deleted concurrently. TorrentId: {torrentId}, Path: {path}",
|
||||
torrentId,
|
||||
downloadInfo.RestrictedLink);
|
||||
logger?.LogDebug("Skipped download creation after the torrent was deleted concurrently. TorrentId: {torrentId}, Path: {path}", torrentId, downloadInfo.RestrictedLink);
|
||||
|
||||
return DownloadAddResult.TorrentMissing;
|
||||
}
|
||||
|
|
@ -276,7 +273,7 @@ public class DownloadData(DataContext dataContext, ILogger<DownloadData>? logger
|
|||
await dataContext.SaveChangesAsync();
|
||||
}
|
||||
|
||||
public async Task Reset(Guid downloadId, DateTimeOffset? downloadQueued = null)
|
||||
public async Task Reset(Guid downloadId)
|
||||
{
|
||||
var dbDownload = await dataContext.Downloads
|
||||
.FirstOrDefaultAsync(m => m.DownloadId == downloadId)
|
||||
|
|
@ -285,7 +282,7 @@ public class DownloadData(DataContext dataContext, ILogger<DownloadData>? logger
|
|||
dbDownload.RetryCount = 0;
|
||||
dbDownload.Link = null;
|
||||
dbDownload.Added = DateTimeOffset.UtcNow;
|
||||
dbDownload.DownloadQueued = downloadQueued ?? DateTimeOffset.UtcNow;
|
||||
dbDownload.DownloadQueued = DateTimeOffset.UtcNow;
|
||||
dbDownload.DownloadStarted = null;
|
||||
dbDownload.DownloadFinished = null;
|
||||
dbDownload.UnpackingQueued = null;
|
||||
|
|
|
|||
|
|
@ -10,11 +10,11 @@ public class TorrentData(DataContext dataContext, ILogger<TorrentData>? logger =
|
|||
public async Task<IList<Torrent>> Get()
|
||||
{
|
||||
var torrents = await dataContext.Torrents
|
||||
.AsNoTracking()
|
||||
.AsSplitQuery()
|
||||
.Include(m => m.Downloads)
|
||||
.OrderBy(m => m.Priority ?? 9999)
|
||||
.ToListAsync();
|
||||
.AsNoTracking()
|
||||
.AsSplitQuery()
|
||||
.Include(m => m.Downloads)
|
||||
.OrderBy(m => m.Priority ?? 9999)
|
||||
.ToListAsync();
|
||||
|
||||
return torrents.OrderBy(m => m.Priority ?? 9999)
|
||||
.ThenBy(m => m.Added)
|
||||
|
|
|
|||
|
|
@ -63,7 +63,6 @@ public class Torrent
|
|||
public DateTimeOffset? RdEnded { get; set; }
|
||||
public Int64? RdSpeed { get; set; }
|
||||
public Int64? RdSeeders { get; set; }
|
||||
|
||||
public String? RdFiles
|
||||
{
|
||||
get => _rdFiles;
|
||||
|
|
|
|||
|
|
@ -8,11 +8,11 @@
|
|||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="10.0.8" />
|
||||
<PackageReference Include="Microsoft.Data.Sqlite" Version="10.0.8" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="10.0.8" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite.Core" Version="10.0.8" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="10.0.8">
|
||||
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="10.0.7" />
|
||||
<PackageReference Include="Microsoft.Data.Sqlite" Version="10.0.7" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="10.0.7" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite.Core" Version="10.0.7" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="10.0.7">
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
</PackageReference>
|
||||
|
|
|
|||
|
|
@ -2,7 +2,9 @@ using System.Reflection;
|
|||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Moq;
|
||||
using RdtClient.Data.Data;
|
||||
using RdtClient.Data.Models.Data;
|
||||
using RdtClient.Data.Models.Internal;
|
||||
using RdtClient.Service.BackgroundServices;
|
||||
using RdtClient.Service.Services;
|
||||
|
||||
|
|
@ -15,7 +17,6 @@ public class WatchFolderCheckerTests : IDisposable
|
|||
private readonly Mock<IServiceProvider> _serviceProviderMock;
|
||||
private readonly Mock<IServiceScope> _serviceScopeMock;
|
||||
private readonly String _testPath;
|
||||
private readonly TestSettings _settings;
|
||||
private readonly Mock<Torrents> _torrentsServiceMock;
|
||||
|
||||
public WatchFolderCheckerTests()
|
||||
|
|
@ -24,18 +25,7 @@ public class WatchFolderCheckerTests : IDisposable
|
|||
_serviceProviderMock = new();
|
||||
_serviceScopeMock = new();
|
||||
_scopeServiceProviderMock = new();
|
||||
|
||||
_settings = new(new()
|
||||
{
|
||||
Watch = new()
|
||||
{
|
||||
Interval = 0,
|
||||
Default = new()
|
||||
},
|
||||
DownloadClient = new()
|
||||
});
|
||||
|
||||
_torrentsServiceMock = new(null!, null!, null!, null!, null!, null!, null!, null!, null!, null!, null!, _settings, new TorrentRunnerState());
|
||||
_torrentsServiceMock = new(null!, null!, null!, null!, null!, null!, null!, null!, null!, null!, null!);
|
||||
|
||||
_serviceProviderMock
|
||||
.Setup(x => x.GetService(typeof(IServiceScopeFactory)))
|
||||
|
|
@ -52,8 +42,10 @@ public class WatchFolderCheckerTests : IDisposable
|
|||
_testPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
|
||||
Directory.CreateDirectory(_testPath);
|
||||
|
||||
// Reset Settings and Startup
|
||||
SetStartupReady(true);
|
||||
_settings.Current.Watch.Path = _testPath;
|
||||
ResetSettings();
|
||||
Settings.Get.Watch.Path = _testPath;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
|
|
@ -70,6 +62,22 @@ public class WatchFolderCheckerTests : IDisposable
|
|||
property?.SetValue(null, ready);
|
||||
}
|
||||
|
||||
private static void ResetSettings()
|
||||
{
|
||||
var settings = new DbSettings
|
||||
{
|
||||
Watch = new()
|
||||
{
|
||||
Interval = 0,
|
||||
Default = new()
|
||||
},
|
||||
DownloadClient = new()
|
||||
};
|
||||
|
||||
var property = typeof(SettingData).GetProperty("Get", BindingFlags.Public | BindingFlags.Static);
|
||||
property?.SetValue(null, settings);
|
||||
}
|
||||
|
||||
private static void ResetPrevCheck(WatchFolderChecker checker)
|
||||
{
|
||||
var field = typeof(WatchFolderChecker).GetField("_prevCheck", BindingFlags.NonPublic | BindingFlags.Instance);
|
||||
|
|
@ -84,7 +92,7 @@ public class WatchFolderCheckerTests : IDisposable
|
|||
var content = "torrent content"u8.ToArray();
|
||||
await File.WriteAllBytesAsync(filePath, content);
|
||||
|
||||
var checker = new WatchFolderChecker(_loggerMock.Object, _serviceProviderMock.Object, _settings);
|
||||
var checker = new WatchFolderChecker(_loggerMock.Object, _serviceProviderMock.Object);
|
||||
ResetPrevCheck(checker);
|
||||
|
||||
var cts = new CancellationTokenSource();
|
||||
|
|
@ -123,7 +131,7 @@ public class WatchFolderCheckerTests : IDisposable
|
|||
var content = "magnet:?xt=urn:btih:123";
|
||||
await File.WriteAllTextAsync(filePath, content);
|
||||
|
||||
var checker = new WatchFolderChecker(_loggerMock.Object, _serviceProviderMock.Object, _settings);
|
||||
var checker = new WatchFolderChecker(_loggerMock.Object, _serviceProviderMock.Object);
|
||||
ResetPrevCheck(checker);
|
||||
|
||||
var cts = new CancellationTokenSource();
|
||||
|
|
@ -162,7 +170,7 @@ public class WatchFolderCheckerTests : IDisposable
|
|||
var content = "nzb content"u8.ToArray();
|
||||
await File.WriteAllBytesAsync(filePath, content);
|
||||
|
||||
var checker = new WatchFolderChecker(_loggerMock.Object, _serviceProviderMock.Object, _settings);
|
||||
var checker = new WatchFolderChecker(_loggerMock.Object, _serviceProviderMock.Object);
|
||||
ResetPrevCheck(checker);
|
||||
|
||||
var cts = new CancellationTokenSource();
|
||||
|
|
@ -201,7 +209,7 @@ public class WatchFolderCheckerTests : IDisposable
|
|||
var filePath = Path.Combine(_testPath, "test.txt");
|
||||
await File.WriteAllTextAsync(filePath, "ignore me");
|
||||
|
||||
var checker = new WatchFolderChecker(_loggerMock.Object, _serviceProviderMock.Object, _settings);
|
||||
var checker = new WatchFolderChecker(_loggerMock.Object, _serviceProviderMock.Object);
|
||||
ResetPrevCheck(checker);
|
||||
|
||||
var cts = new CancellationTokenSource();
|
||||
|
|
|
|||
|
|
@ -1 +0,0 @@
|
|||
[assembly: CollectionBehavior(DisableTestParallelization = true)]
|
||||
|
|
@ -5,24 +5,23 @@
|
|||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<IsPackable>false</IsPackable>
|
||||
<IsTestProject>true</IsTestProject>
|
||||
<AssemblyName>RdtClient.Service.Test</AssemblyName>
|
||||
<RootNamespace>RdtClient.Service.Test</RootNamespace>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="AllDebrid.NET" Version="1.0.18" />
|
||||
<PackageReference Include="coverlet.collector" Version="10.0.1">
|
||||
<PackageReference Include="coverlet.collector" Version="10.0.0">
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.6.0" />
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.4.0" />
|
||||
<PackageReference Include="Moq" Version="4.20.72" />
|
||||
<PackageReference Include="SharpCompress" Version="[0.42.1]" />
|
||||
<PackageReference Include="TestableIO.System.IO.Abstractions" Version="22.1.1" />
|
||||
<PackageReference Include="TestableIO.System.IO.Abstractions.TestingHelpers" Version="22.1.1" />
|
||||
<PackageReference Include="TestableIO.System.IO.Abstractions.Wrappers" Version="22.1.1" />
|
||||
<PackageReference Include="TorBox.NET" Version="2.1.0" />
|
||||
<PackageReference Include="TorBox.NET" Version="1.6.2" />
|
||||
<PackageReference Include="xunit" Version="2.9.3" />
|
||||
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.5">
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
|
|
@ -38,4 +37,10 @@
|
|||
<ProjectReference Include="..\RdtClient.Service\RdtClient.Service.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Reference Include="TorBoxNET">
|
||||
<HintPath>..\..\..\torbox-net\TorBoxNET\bin\Release\netstandard2.0\TorBoxNET.dll</HintPath>
|
||||
</Reference>
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
|
|
|||
|
|
@ -162,7 +162,6 @@ public class TorrentDownloadRaceTests : IAsyncLifetime
|
|||
var torrentId = Guid.NewGuid();
|
||||
|
||||
await using var context = CreateContext();
|
||||
|
||||
context.Torrents.Add(new()
|
||||
{
|
||||
TorrentId = torrentId,
|
||||
|
|
|
|||
|
|
@ -3,7 +3,6 @@ using System.Text;
|
|||
using Moq;
|
||||
using RdtClient.Data.Enums;
|
||||
using RdtClient.Data.Models.Data;
|
||||
using TorrentRunnerState = RdtClient.Service.Services.TorrentRunnerState;
|
||||
using TorrentsService = RdtClient.Service.Services.Torrents;
|
||||
|
||||
namespace RdtClient.Service.Test.Services;
|
||||
|
|
@ -29,9 +28,7 @@ public class NzbTorrentsTest
|
|||
null!,
|
||||
null!,
|
||||
null!,
|
||||
null!,
|
||||
new TestSettings(),
|
||||
new TorrentRunnerState());
|
||||
null!);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
|
|
|
|||
|
|
@ -1,10 +1,10 @@
|
|||
using Microsoft.Extensions.Logging;
|
||||
using Moq;
|
||||
using System.Text.Json;
|
||||
using RdtClient.Data.Enums;
|
||||
using RdtClient.Data.Models.Data;
|
||||
using RdtClient.Data.Models.DebridClient;
|
||||
using RdtClient.Service.Services;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace RdtClient.Service.Test.Services;
|
||||
|
||||
|
|
@ -13,19 +13,15 @@ public class QBittorrentTest
|
|||
private readonly Mock<Authentication> _authenticationMock;
|
||||
private readonly Mock<ILogger<QBittorrent>> _loggerMock;
|
||||
private readonly QBittorrent _qBittorrent;
|
||||
private readonly TestSettings _settings;
|
||||
private readonly TorrentRunnerState _runnerState;
|
||||
private readonly Mock<Torrents> _torrentsMock;
|
||||
|
||||
public QBittorrentTest()
|
||||
{
|
||||
_loggerMock = new();
|
||||
_settings = new();
|
||||
_runnerState = new();
|
||||
_torrentsMock = new(null!, null!, null!, null!, null!, null!, null!, null!, null!, null!, null!, _settings, _runnerState);
|
||||
_torrentsMock = new(null!, null!, null!, null!, null!, null!, null!, null!, null!, null!, null!);
|
||||
_authenticationMock = new(null!, null!, null!);
|
||||
|
||||
_qBittorrent = new(_loggerMock.Object, _settings, _authenticationMock.Object, _torrentsMock.Object, null!, _runnerState);
|
||||
_qBittorrent = new(_loggerMock.Object, null!, _authenticationMock.Object, _torrentsMock.Object, null!);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
|
|
@ -177,20 +173,19 @@ public class QBittorrentTest
|
|||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
|
||||
Assert.Collection(result!,
|
||||
first =>
|
||||
{
|
||||
Assert.Equal(0, first.Index);
|
||||
Assert.Equal("good.mkv", first.Name);
|
||||
Assert.Equal(1, first.Priority);
|
||||
},
|
||||
second =>
|
||||
{
|
||||
Assert.Equal(1, second.Index);
|
||||
Assert.Equal("dangerous.exe", second.Name);
|
||||
Assert.Equal(0, second.Priority);
|
||||
});
|
||||
first =>
|
||||
{
|
||||
Assert.Equal(0, first.Index);
|
||||
Assert.Equal("good.mkv", first.Name);
|
||||
Assert.Equal(1, first.Priority);
|
||||
},
|
||||
second =>
|
||||
{
|
||||
Assert.Equal(1, second.Index);
|
||||
Assert.Equal("dangerous.exe", second.Name);
|
||||
Assert.Equal(0, second.Priority);
|
||||
});
|
||||
}
|
||||
|
||||
[Fact]
|
||||
|
|
@ -213,197 +208,4 @@ public class QBittorrentTest
|
|||
Assert.NotNull(result);
|
||||
Assert.False(result!.IsPrivate);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task TorrentInfo_ShouldUseSelectedTopLevelFileName_WhenRootFileAddsOnlyTheExtension()
|
||||
{
|
||||
// Arrange
|
||||
var previousMappedPath = _settings.Current.DownloadClient.MappedPath;
|
||||
_settings.Current.DownloadClient.MappedPath = "/data/downloads";
|
||||
|
||||
try
|
||||
{
|
||||
var torrentRootName = "Sample.Show.S01E01.1080p.WEB-DL-GROUP";
|
||||
var selectedFileName = $"{torrentRootName}.mkv";
|
||||
|
||||
var torrent = new Torrent
|
||||
{
|
||||
Hash = "hash1",
|
||||
Category = "tv",
|
||||
Completed = DateTimeOffset.UtcNow,
|
||||
RdName = torrentRootName,
|
||||
RdFiles = JsonSerializer.Serialize(new List<DebridClientFile>
|
||||
{
|
||||
new()
|
||||
{
|
||||
Id = 1,
|
||||
Path = $"/{selectedFileName}",
|
||||
Bytes = 1000,
|
||||
Selected = true
|
||||
},
|
||||
new()
|
||||
{
|
||||
Id = 2,
|
||||
Path = $"/{torrentRootName}.nfo",
|
||||
Bytes = 10,
|
||||
Selected = false
|
||||
}
|
||||
}),
|
||||
Type = DownloadType.Torrent
|
||||
};
|
||||
|
||||
_torrentsMock.Setup(m => m.Get())
|
||||
.ReturnsAsync(new List<Torrent>
|
||||
{
|
||||
torrent
|
||||
});
|
||||
|
||||
// Act
|
||||
var result = await _qBittorrent.TorrentInfo();
|
||||
|
||||
// Assert
|
||||
Assert.Single(result);
|
||||
Assert.Equal(Path.Combine("/data/downloads", "tv", selectedFileName) + Path.DirectorySeparatorChar, result[0].ContentPath);
|
||||
Assert.Equal(torrentRootName, result[0].Name);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_settings.Current.DownloadClient.MappedPath = previousMappedPath;
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task TorrentInfo_ShouldUseExistingCompletedContentRoot_WhenSingleFileDirectoryDiffersFromRdName()
|
||||
{
|
||||
var previousMappedPath = _settings.Current.DownloadClient.MappedPath;
|
||||
var mappedPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N"));
|
||||
_settings.Current.DownloadClient.MappedPath = mappedPath;
|
||||
|
||||
try
|
||||
{
|
||||
var category = "tv";
|
||||
var selectedFileName = "Sample.Show.S01E02.1080p.WEB-DL-GROUP.mkv";
|
||||
var contentRoot = Path.Combine(mappedPath, category, selectedFileName);
|
||||
Directory.CreateDirectory(contentRoot);
|
||||
await File.WriteAllTextAsync(Path.Combine(contentRoot, selectedFileName), "test");
|
||||
|
||||
var torrent = new Torrent
|
||||
{
|
||||
Hash = "hash1",
|
||||
Category = category,
|
||||
Completed = DateTimeOffset.UtcNow,
|
||||
Downloads = new List<Download>
|
||||
{
|
||||
new()
|
||||
{
|
||||
DownloadId = Guid.NewGuid(),
|
||||
FileName = selectedFileName,
|
||||
Link = "https://fake.url/Sample.Show.S01E02.1080p.WEB-DL-GROUP.mkv",
|
||||
Completed = DateTimeOffset.UtcNow
|
||||
}
|
||||
},
|
||||
RdName = "tracker.example - Sample.Show.S01E02.1080p.WEB-DL-GROUP",
|
||||
RdFiles = JsonSerializer.Serialize(new List<DebridClientFile>
|
||||
{
|
||||
new()
|
||||
{
|
||||
Id = 1,
|
||||
Path = $"/{selectedFileName}",
|
||||
Bytes = 1000,
|
||||
Selected = true
|
||||
}
|
||||
}),
|
||||
Type = DownloadType.Torrent
|
||||
};
|
||||
|
||||
_torrentsMock.Setup(m => m.Get())
|
||||
.ReturnsAsync(new List<Torrent>
|
||||
{
|
||||
torrent
|
||||
});
|
||||
|
||||
var result = await _qBittorrent.TorrentInfo();
|
||||
|
||||
Assert.Single(result);
|
||||
Assert.Equal(contentRoot + Path.DirectorySeparatorChar, result[0].ContentPath);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_settings.Current.DownloadClient.MappedPath = previousMappedPath;
|
||||
|
||||
if (Directory.Exists(mappedPath))
|
||||
{
|
||||
Directory.Delete(mappedPath, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task TorrentInfo_ShouldUseExistingCompletedContentRoot_WhenSelectedFileIsNestedUnderDifferentRoot()
|
||||
{
|
||||
var previousMappedPath = _settings.Current.DownloadClient.MappedPath;
|
||||
var mappedPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N"));
|
||||
_settings.Current.DownloadClient.MappedPath = mappedPath;
|
||||
|
||||
try
|
||||
{
|
||||
var category = "tv";
|
||||
var rootDirectoryName = "tracker.example - Sample.Show.S01E03.1080p.x265-GROUP.mkv";
|
||||
var nestedDirectoryName = "Sample.Show.S01E03.1080p.x265-GROUP";
|
||||
var fileName = "Sample.Show.S01E03.1080p.x265-GROUP.mkv";
|
||||
var contentRoot = Path.Combine(mappedPath, category, rootDirectoryName);
|
||||
var nestedDirectory = Path.Combine(contentRoot, nestedDirectoryName);
|
||||
Directory.CreateDirectory(nestedDirectory);
|
||||
await File.WriteAllTextAsync(Path.Combine(nestedDirectory, fileName), "test");
|
||||
|
||||
var torrent = new Torrent
|
||||
{
|
||||
Hash = "hash1",
|
||||
Category = category,
|
||||
Completed = DateTimeOffset.UtcNow,
|
||||
Downloads = new List<Download>
|
||||
{
|
||||
new()
|
||||
{
|
||||
DownloadId = Guid.NewGuid(),
|
||||
FileName = fileName,
|
||||
Link = "https://fake.url/Sample.Show.S01E03.1080p.x265-GROUP.mkv",
|
||||
Completed = DateTimeOffset.UtcNow
|
||||
}
|
||||
},
|
||||
RdName = "tracker.example - Sample.Show.S01E03.1080p.x265-GROUP",
|
||||
RdFiles = JsonSerializer.Serialize(new List<DebridClientFile>
|
||||
{
|
||||
new()
|
||||
{
|
||||
Id = 1,
|
||||
Path = $"/{nestedDirectoryName}/{fileName}",
|
||||
Bytes = 1000,
|
||||
Selected = true
|
||||
}
|
||||
}),
|
||||
Type = DownloadType.Torrent
|
||||
};
|
||||
|
||||
_torrentsMock.Setup(m => m.Get())
|
||||
.ReturnsAsync(new List<Torrent>
|
||||
{
|
||||
torrent
|
||||
});
|
||||
|
||||
var result = await _qBittorrent.TorrentInfo();
|
||||
|
||||
Assert.Single(result);
|
||||
Assert.Equal(contentRoot + Path.DirectorySeparatorChar, result[0].ContentPath);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_settings.Current.DownloadClient.MappedPath = previousMappedPath;
|
||||
|
||||
if (Directory.Exists(mappedPath))
|
||||
{
|
||||
Directory.Delete(mappedPath, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
using Microsoft.Extensions.Logging;
|
||||
using Moq;
|
||||
using RdtClient.Data.Data;
|
||||
using RdtClient.Data.Enums;
|
||||
using RdtClient.Data.Models.Data;
|
||||
using RdtClient.Data.Models.Internal;
|
||||
|
|
@ -15,13 +16,11 @@ public class SabnzbdTest
|
|||
};
|
||||
|
||||
private readonly Mock<ILogger<Sabnzbd>> _loggerMock = new();
|
||||
private readonly TestSettings _settings;
|
||||
private readonly Mock<Torrents> _torrentsMock;
|
||||
|
||||
public SabnzbdTest()
|
||||
{
|
||||
_settings = new();
|
||||
_torrentsMock = new(null!, null!, null!, null!, null!, null!, null!, null!, null!, null!, null!, _settings, new TorrentRunnerState());
|
||||
_torrentsMock = new(null!, null!, null!, null!, null!, null!, null!, null!, null!, null!, null!);
|
||||
_torrentsMock.Setup(t => t.Get()).ReturnsAsync(new List<Torrent>());
|
||||
}
|
||||
|
||||
|
|
@ -51,7 +50,7 @@ public class SabnzbdTest
|
|||
_torrentsMock.Setup(t => t.Get()).ReturnsAsync(torrentList);
|
||||
_torrentsMock.Setup(t => t.GetDownloadStats(It.IsAny<Guid>())).Returns((0, 1000, 500));
|
||||
|
||||
var sabnzbd = new Sabnzbd(_loggerMock.Object, _torrentsMock.Object, _appSettings, _settings);
|
||||
var sabnzbd = new Sabnzbd(_loggerMock.Object, _torrentsMock.Object, _appSettings);
|
||||
|
||||
// Act
|
||||
var result = await sabnzbd.GetQueue();
|
||||
|
|
@ -91,7 +90,7 @@ public class SabnzbdTest
|
|||
|
||||
_torrentsMock.Setup(t => t.Get()).ReturnsAsync(torrentList);
|
||||
|
||||
var sabnzbd = new Sabnzbd(_loggerMock.Object, _torrentsMock.Object, _appSettings, _settings);
|
||||
var sabnzbd = new Sabnzbd(_loggerMock.Object, _torrentsMock.Object, _appSettings);
|
||||
|
||||
// Act
|
||||
var result = await sabnzbd.GetQueue();
|
||||
|
|
@ -135,7 +134,7 @@ public class SabnzbdTest
|
|||
|
||||
_torrentsMock.Setup(t => t.Get()).ReturnsAsync(torrentList);
|
||||
|
||||
var sabnzbd = new Sabnzbd(_loggerMock.Object, _torrentsMock.Object, _appSettings, _settings);
|
||||
var sabnzbd = new Sabnzbd(_loggerMock.Object, _torrentsMock.Object, _appSettings);
|
||||
|
||||
// Act
|
||||
var result = await sabnzbd.GetQueue();
|
||||
|
|
@ -187,7 +186,7 @@ public class SabnzbdTest
|
|||
|
||||
_torrentsMock.Setup(t => t.Get()).ReturnsAsync(torrentList);
|
||||
|
||||
var sabnzbd = new Sabnzbd(_loggerMock.Object, _torrentsMock.Object, _appSettings, _settings);
|
||||
var sabnzbd = new Sabnzbd(_loggerMock.Object, _torrentsMock.Object, _appSettings);
|
||||
|
||||
// Act
|
||||
var result = await sabnzbd.GetQueue();
|
||||
|
|
@ -225,7 +224,7 @@ public class SabnzbdTest
|
|||
|
||||
_torrentsMock.Setup(t => t.Get()).ReturnsAsync(torrentList);
|
||||
|
||||
var sabnzbd = new Sabnzbd(_loggerMock.Object, _torrentsMock.Object, _appSettings, _settings);
|
||||
var sabnzbd = new Sabnzbd(_loggerMock.Object, _torrentsMock.Object, _appSettings);
|
||||
|
||||
// Act
|
||||
var result = await sabnzbd.GetQueue();
|
||||
|
|
@ -261,7 +260,7 @@ public class SabnzbdTest
|
|||
|
||||
_torrentsMock.Setup(t => t.Get()).ReturnsAsync(torrentList);
|
||||
|
||||
var sabnzbd = new Sabnzbd(_loggerMock.Object, _torrentsMock.Object, _appSettings, _settings);
|
||||
var sabnzbd = new Sabnzbd(_loggerMock.Object, _torrentsMock.Object, _appSettings);
|
||||
|
||||
// Act
|
||||
var result = await sabnzbd.GetHistory();
|
||||
|
|
@ -276,7 +275,7 @@ public class SabnzbdTest
|
|||
{
|
||||
// Arrange
|
||||
var savePath = @"C:\Downloads";
|
||||
_settings.Current.DownloadClient.MappedPath = savePath;
|
||||
SettingData.Get.DownloadClient.MappedPath = savePath;
|
||||
|
||||
var torrentList = new List<Torrent>
|
||||
{
|
||||
|
|
@ -293,7 +292,7 @@ public class SabnzbdTest
|
|||
|
||||
_torrentsMock.Setup(t => t.Get()).ReturnsAsync(torrentList);
|
||||
|
||||
var sabnzbd = new Sabnzbd(_loggerMock.Object, _torrentsMock.Object, _appSettings, _settings);
|
||||
var sabnzbd = new Sabnzbd(_loggerMock.Object, _torrentsMock.Object, _appSettings);
|
||||
|
||||
// Act
|
||||
var result = await sabnzbd.GetHistory();
|
||||
|
|
@ -309,7 +308,7 @@ public class SabnzbdTest
|
|||
{
|
||||
// Arrange
|
||||
var savePath = @"C:\Downloads";
|
||||
_settings.Current.DownloadClient.MappedPath = savePath;
|
||||
SettingData.Get.DownloadClient.MappedPath = savePath;
|
||||
|
||||
var torrentList = new List<Torrent>
|
||||
{
|
||||
|
|
@ -326,7 +325,7 @@ public class SabnzbdTest
|
|||
|
||||
_torrentsMock.Setup(t => t.Get()).ReturnsAsync(torrentList);
|
||||
|
||||
var sabnzbd = new Sabnzbd(_loggerMock.Object, _torrentsMock.Object, _appSettings, _settings);
|
||||
var sabnzbd = new Sabnzbd(_loggerMock.Object, _torrentsMock.Object, _appSettings);
|
||||
|
||||
// Act
|
||||
var result = await sabnzbd.GetHistory();
|
||||
|
|
@ -356,7 +355,7 @@ public class SabnzbdTest
|
|||
|
||||
_torrentsMock.Setup(t => t.Get()).ReturnsAsync(torrentList);
|
||||
|
||||
var sabnzbd = new Sabnzbd(_loggerMock.Object, _torrentsMock.Object, _appSettings, _settings);
|
||||
var sabnzbd = new Sabnzbd(_loggerMock.Object, _torrentsMock.Object, _appSettings);
|
||||
|
||||
// Act
|
||||
var result = await sabnzbd.GetHistory();
|
||||
|
|
@ -366,69 +365,11 @@ public class SabnzbdTest
|
|||
Assert.Equal("Failed", result.Slots[0].Status);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(TorrentFinishedAction.RemoveAllTorrents, true, true, true, true)]
|
||||
[InlineData(TorrentFinishedAction.RemoveAllTorrents, false, true, true, false)]
|
||||
[InlineData(TorrentFinishedAction.RemoveRealDebrid, true, false, true, true)]
|
||||
[InlineData(TorrentFinishedAction.RemoveRealDebrid, false, false, true, false)]
|
||||
[InlineData(TorrentFinishedAction.RemoveClient, true, true, false, true)]
|
||||
[InlineData(TorrentFinishedAction.RemoveClient, false, true, false, false)]
|
||||
public async Task Delete_ShouldRespectFinishedActionAndDeleteFiles(
|
||||
TorrentFinishedAction finishedAction,
|
||||
Boolean deleteFiles,
|
||||
Boolean expectedDeleteData,
|
||||
Boolean expectedDeleteRdTorrent,
|
||||
Boolean expectedDeleteLocalFiles)
|
||||
{
|
||||
// Arrange
|
||||
var torrentId = Guid.NewGuid();
|
||||
_settings.Current.Integrations.Default.FinishedAction = finishedAction;
|
||||
|
||||
_torrentsMock.Setup(t => t.GetByHash("hash1"))
|
||||
.ReturnsAsync(new Torrent
|
||||
{
|
||||
TorrentId = torrentId,
|
||||
Hash = "hash1",
|
||||
Type = DownloadType.Nzb
|
||||
});
|
||||
|
||||
var sabnzbd = new Sabnzbd(_loggerMock.Object, _torrentsMock.Object, _appSettings, _settings);
|
||||
|
||||
// Act
|
||||
await sabnzbd.Delete("hash1", deleteFiles);
|
||||
|
||||
// Assert
|
||||
_torrentsMock.Verify(t => t.Delete(torrentId, expectedDeleteData, expectedDeleteRdTorrent, expectedDeleteLocalFiles), Times.Once);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Delete_ShouldNotDelete_WhenFinishedActionIsNone()
|
||||
{
|
||||
// Arrange
|
||||
_settings.Current.Integrations.Default.FinishedAction = TorrentFinishedAction.None;
|
||||
|
||||
_torrentsMock.Setup(t => t.GetByHash("hash1"))
|
||||
.ReturnsAsync(new Torrent
|
||||
{
|
||||
TorrentId = Guid.NewGuid(),
|
||||
Hash = "hash1",
|
||||
Type = DownloadType.Nzb
|
||||
});
|
||||
|
||||
var sabnzbd = new Sabnzbd(_loggerMock.Object, _torrentsMock.Object, _appSettings, _settings);
|
||||
|
||||
// Act
|
||||
await sabnzbd.Delete("hash1", true);
|
||||
|
||||
// Assert
|
||||
_torrentsMock.Verify(t => t.Delete(It.IsAny<Guid>(), It.IsAny<Boolean>(), It.IsAny<Boolean>(), It.IsAny<Boolean>()), Times.Never);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetConfig_ShouldReturnCorrectConfig()
|
||||
{
|
||||
// Arrange
|
||||
var sabnzbd = new Sabnzbd(_loggerMock.Object, _torrentsMock.Object, _appSettings, _settings);
|
||||
var sabnzbd = new Sabnzbd(_loggerMock.Object, _torrentsMock.Object, _appSettings);
|
||||
|
||||
// Act
|
||||
var result = sabnzbd.GetConfig();
|
||||
|
|
@ -458,9 +399,9 @@ public class SabnzbdTest
|
|||
|
||||
_torrentsMock.Setup(t => t.Get()).ReturnsAsync(torrentList);
|
||||
|
||||
_settings.Current.General.Categories = "TV, Music, *";
|
||||
SettingData.Get.General.Categories = "TV, Music, *";
|
||||
|
||||
var sabnzbd = new Sabnzbd(_loggerMock.Object, _torrentsMock.Object, _appSettings, _settings);
|
||||
var sabnzbd = new Sabnzbd(_loggerMock.Object, _torrentsMock.Object, _appSettings);
|
||||
|
||||
// Act
|
||||
var result = sabnzbd.GetCategories();
|
||||
|
|
|
|||
|
|
@ -1,225 +0,0 @@
|
|||
using System.Net;
|
||||
using System.Text;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Moq;
|
||||
using RdtClient.Data.Models.Internal;
|
||||
using RdtClient.Service.Services;
|
||||
using RdtClient.Service.Services.DebridClients;
|
||||
|
||||
namespace RdtClient.Service.Test.Services.TorrentClients;
|
||||
|
||||
public class PremiumizeDebridClientTest
|
||||
{
|
||||
private readonly Mock<IDownloadableFileFilter> _fileFilterMock;
|
||||
private readonly Mock<IHttpClientFactory> _httpClientFactoryMock;
|
||||
private readonly Mock<ILogger<PremiumizeDebridClient>> _loggerMock;
|
||||
private readonly TestSettings _settings;
|
||||
|
||||
public PremiumizeDebridClientTest()
|
||||
{
|
||||
_loggerMock = new();
|
||||
_httpClientFactoryMock = new();
|
||||
_fileFilterMock = new();
|
||||
_settings = new();
|
||||
_settings.Current.Provider.ApiKey = "test-api-key";
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddNzbLink_UsesPremiumizeNetTransferCreate_ReturnsTransferId()
|
||||
{
|
||||
// Arrange
|
||||
var handler = new RecordingHttpMessageHandler(_ => JsonResponse("""{"status":"success","id":"transfer-id","name":"test.nzb"}"""));
|
||||
var client = CreateClient(handler);
|
||||
|
||||
// Act
|
||||
var result = await client.AddNzbLink("http://example.com/test.nzb");
|
||||
|
||||
// Assert
|
||||
Assert.Equal("transfer-id", result);
|
||||
Assert.Equal(HttpMethod.Post, handler.Request!.Method);
|
||||
Assert.Equal("https://www.premiumize.me/api/transfer/create?apikey=test-api-key", handler.Request.RequestUri!.ToString());
|
||||
Assert.Null(handler.Request.Headers.Authorization);
|
||||
Assert.Equal("application/x-www-form-urlencoded", handler.Request.Content!.Headers.ContentType!.MediaType);
|
||||
Assert.Equal("src=http%3A%2F%2Fexample.com%2Ftest.nzb&folder_id=", handler.RequestBody);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddNzbFile_SubmitsMultipartTransferCreateRequest_ReturnsTransferId()
|
||||
{
|
||||
// Arrange
|
||||
var handler = new RecordingHttpMessageHandler(_ => JsonResponse("""{"status":"success","id":"file-transfer-id","name":"test.nzb"}"""));
|
||||
var client = CreateClient(handler);
|
||||
|
||||
// Act
|
||||
var result = await client.AddNzbFile(Encoding.UTF8.GetBytes("nzb body"), "test.nzb");
|
||||
|
||||
// Assert
|
||||
Assert.Equal("file-transfer-id", result);
|
||||
Assert.Equal(HttpMethod.Post, handler.Request!.Method);
|
||||
Assert.Equal("https://www.premiumize.me/api/transfer/create", handler.Request.RequestUri!.ToString());
|
||||
Assert.Equal("Bearer", handler.Request.Headers.Authorization!.Scheme);
|
||||
Assert.Equal("test-api-key", handler.Request.Headers.Authorization.Parameter);
|
||||
Assert.Equal("multipart/form-data", handler.Request.Content!.Headers.ContentType!.MediaType);
|
||||
Assert.Contains("Content-Disposition: form-data", handler.RequestBody);
|
||||
Assert.Contains("src", handler.RequestBody);
|
||||
Assert.Contains("test.nzb", handler.RequestBody);
|
||||
Assert.Contains("nzb body", handler.RequestBody);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddNzbFile_WhenNameIsMissing_UsesDefaultFilename()
|
||||
{
|
||||
// Arrange
|
||||
var handler = new RecordingHttpMessageHandler(_ => JsonResponse("""{"status":"success","id":"file-transfer-id","name":"upload.nzb"}"""));
|
||||
var client = CreateClient(handler);
|
||||
|
||||
// Act
|
||||
await client.AddNzbFile(Encoding.UTF8.GetBytes("nzb body"), null);
|
||||
|
||||
// Assert
|
||||
Assert.Contains("upload.nzb", handler.RequestBody);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddNzbFile_WhenNameHasNoNzbExtension_AppendsNzbExtension()
|
||||
{
|
||||
// Arrange
|
||||
var handler = new RecordingHttpMessageHandler(_ => JsonResponse("""{"status":"success","id":"file-transfer-id","name":"release-title.nzb"}"""));
|
||||
var client = CreateClient(handler);
|
||||
|
||||
// Act
|
||||
await client.AddNzbFile(Encoding.UTF8.GetBytes("nzb body"), "release-title");
|
||||
|
||||
// Assert
|
||||
Assert.Contains("release-title.nzb", handler.RequestBody);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddNzbLink_WhenSuccessResponseHasNoId_Throws()
|
||||
{
|
||||
// Arrange
|
||||
var handler = new RecordingHttpMessageHandler(_ => JsonResponse("""{"status":"success","name":"test.nzb"}"""));
|
||||
var client = CreateClient(handler);
|
||||
|
||||
// Act
|
||||
var ex = await Assert.ThrowsAsync<Exception>(() => client.AddNzbLink("http://example.com/test.nzb"));
|
||||
|
||||
// Assert
|
||||
Assert.Contains("Unable to add NZB link", ex.Message);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddNzbLink_WhenPremiumizeReturnsRateLimitError_ThrowsRateLimitException()
|
||||
{
|
||||
// Arrange
|
||||
var handler = new RecordingHttpMessageHandler(_ => JsonResponse("""{"status":"error","code":"slow_down","message":"rate limit exceeded"}"""));
|
||||
var client = CreateClient(handler);
|
||||
|
||||
// Act
|
||||
var ex = await Assert.ThrowsAsync<RateLimitException>(() => client.AddNzbLink("http://example.com/test.nzb"));
|
||||
|
||||
// Assert
|
||||
Assert.Equal(TimeSpan.FromMinutes(2), ex.RetryAfter);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("You've made too many API requests too quickly.")]
|
||||
[InlineData("Your fair-use points, booster points, or active-job count is exhausted.")]
|
||||
[InlineData("This account's usage limit for this service has been reached.")]
|
||||
[InlineData("The target service is unreachable right now. Retry after a delay.")]
|
||||
public async Task AddNzbLink_WhenPremiumizeNetReturnsDocumentedRetryMessage_ThrowsRateLimitException(String message)
|
||||
{
|
||||
// Arrange
|
||||
var handler = new RecordingHttpMessageHandler(_ => JsonResponse($$"""{"status":"error","message":"{{message}}","code":"rate_limit_reached"}"""));
|
||||
var client = CreateClient(handler);
|
||||
|
||||
// Act
|
||||
var ex = await Assert.ThrowsAsync<RateLimitException>(() => client.AddNzbLink("http://example.com/test.nzb"));
|
||||
|
||||
// Assert
|
||||
Assert.Equal(TimeSpan.FromMinutes(2), ex.RetryAfter);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("rate_limit_reached")]
|
||||
[InlineData("account_limit_reached")]
|
||||
[InlineData("service_limit_reached")]
|
||||
[InlineData("service_down")]
|
||||
[InlineData("semi_permanent_error")]
|
||||
public async Task AddNzbFile_WhenPremiumizeReturnsDocumentedRetryCode_ThrowsRateLimitException(String code)
|
||||
{
|
||||
// Arrange
|
||||
var handler = new RecordingHttpMessageHandler(_ => JsonResponse($$"""{"status":"error","code":"{{code}}","message":"retry later"}"""));
|
||||
var client = CreateClient(handler);
|
||||
|
||||
// Act
|
||||
var ex = await Assert.ThrowsAsync<RateLimitException>(() => client.AddNzbFile(Encoding.UTF8.GetBytes("nzb body"), "test.nzb"));
|
||||
|
||||
// Assert
|
||||
Assert.Equal(TimeSpan.FromMinutes(2), ex.RetryAfter);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddTorrentMagnet_UsesPremiumizeNetTransferCreate_ReturnsTransferId()
|
||||
{
|
||||
// Arrange
|
||||
var handler = new RecordingHttpMessageHandler(_ => JsonResponse("""{"status":"success","id":"magnet-transfer-id","name":"test"}"""));
|
||||
var client = CreateClient(handler);
|
||||
|
||||
// Act
|
||||
var result = await client.AddTorrentMagnet("magnet:?xt=urn:btih:test");
|
||||
|
||||
// Assert
|
||||
Assert.Equal("magnet-transfer-id", result);
|
||||
Assert.Equal("https://www.premiumize.me/api/transfer/create?apikey=test-api-key", handler.Request!.RequestUri!.ToString());
|
||||
Assert.Equal("src=magnet%3A%3Fxt%3Durn%3Abtih%3Atest&folder_id=", handler.RequestBody);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddTorrentFile_UsesPremiumizeNetFileUpload_ReturnsTransferId()
|
||||
{
|
||||
// Arrange
|
||||
var handler = new RecordingHttpMessageHandler(_ => JsonResponse("""{"status":"success","id":"torrent-transfer-id","name":"test"}"""));
|
||||
var client = CreateClient(handler);
|
||||
|
||||
// Act
|
||||
var result = await client.AddTorrentFile(Encoding.UTF8.GetBytes("torrent body"));
|
||||
|
||||
// Assert
|
||||
Assert.Equal("torrent-transfer-id", result);
|
||||
Assert.Equal("https://www.premiumize.me/api/transfer/create?apikey=test-api-key", handler.Request!.RequestUri!.ToString());
|
||||
Assert.Contains("name=file", handler.RequestBody);
|
||||
Assert.Contains("filename=1.torrent", handler.RequestBody);
|
||||
Assert.Contains("application/x-bittorrent", handler.RequestBody);
|
||||
Assert.Contains("torrent body", handler.RequestBody);
|
||||
}
|
||||
|
||||
private PremiumizeDebridClient CreateClient(RecordingHttpMessageHandler handler)
|
||||
{
|
||||
_httpClientFactoryMock.Setup(m => m.CreateClient(It.IsAny<String>())).Returns(new HttpClient(handler));
|
||||
|
||||
return new(_loggerMock.Object, _httpClientFactoryMock.Object, _fileFilterMock.Object, _settings);
|
||||
}
|
||||
|
||||
private static HttpResponseMessage JsonResponse(String json, HttpStatusCode statusCode = HttpStatusCode.OK)
|
||||
{
|
||||
return new(statusCode)
|
||||
{
|
||||
Content = new StringContent(json, Encoding.UTF8, "application/json")
|
||||
};
|
||||
}
|
||||
|
||||
private class RecordingHttpMessageHandler(Func<HttpRequestMessage, HttpResponseMessage> handler) : HttpMessageHandler
|
||||
{
|
||||
public HttpRequestMessage? Request { get; private set; }
|
||||
public String? RequestBody { get; private set; }
|
||||
|
||||
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
|
||||
{
|
||||
Request = request;
|
||||
RequestBody = request.Content == null ? null : await request.Content.ReadAsStringAsync(cancellationToken);
|
||||
|
||||
return handler(request);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -21,7 +21,6 @@ public class TorBoxDebridClientTest
|
|||
private readonly Mock<IDownloadableFileFilter> _fileFilterMock;
|
||||
private readonly Mock<IHttpClientFactory> _httpClientFactoryMock;
|
||||
private readonly Mock<ILogger<TorBoxDebridClient>> _loggerMock;
|
||||
private readonly TestSettings _settings;
|
||||
|
||||
public TorBoxDebridClientTest()
|
||||
{
|
||||
|
|
@ -29,13 +28,12 @@ public class TorBoxDebridClientTest
|
|||
_httpClientFactoryMock = new();
|
||||
_fileFilterMock = new();
|
||||
_coordinatorMock = new();
|
||||
_settings = new();
|
||||
|
||||
var httpClient = new HttpClient();
|
||||
_httpClientFactoryMock.Setup(m => m.CreateClient(It.IsAny<String>())).Returns(httpClient);
|
||||
|
||||
_settings.Current.Provider.ApiKey = "test-api-key";
|
||||
_settings.Current.Provider.Timeout = 100;
|
||||
Settings.Get.Provider.ApiKey = "test-api-key";
|
||||
Settings.Get.Provider.Timeout = 100;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
|
|
@ -46,7 +44,6 @@ public class TorBoxDebridClientTest
|
|||
{
|
||||
new()
|
||||
{
|
||||
Id = 12345,
|
||||
Hash = "hash1",
|
||||
Name = "torrent1",
|
||||
Size = 1000,
|
||||
|
|
@ -67,7 +64,7 @@ public class TorBoxDebridClientTest
|
|||
}
|
||||
};
|
||||
|
||||
var clientMock = new Mock<TorBoxDebridClient>(_loggerMock.Object, _httpClientFactoryMock.Object, _fileFilterMock.Object, _coordinatorMock.Object, _settings);
|
||||
var clientMock = new Mock<TorBoxDebridClient>(_loggerMock.Object, _httpClientFactoryMock.Object, _fileFilterMock.Object, _coordinatorMock.Object);
|
||||
clientMock.Protected().Setup<Task<IEnumerable<TorrentInfoResult>?>>("GetCurrentTorrents").ReturnsAsync(torrents);
|
||||
clientMock.Protected().Setup<Task<IEnumerable<TorrentInfoResult>?>>("GetQueuedTorrents").ReturnsAsync(new List<TorrentInfoResult>());
|
||||
clientMock.Protected().Setup<Task<IEnumerable<UsenetInfoResult>?>>("GetCurrentUsenet").ReturnsAsync(nzbs);
|
||||
|
|
@ -79,7 +76,7 @@ public class TorBoxDebridClientTest
|
|||
// Assert
|
||||
Assert.Equal(2, result.Count);
|
||||
|
||||
var torrentResult = result.FirstOrDefault(r => r.Id == "12345");
|
||||
var torrentResult = result.FirstOrDefault(r => r.Id == "hash1");
|
||||
Assert.NotNull(torrentResult);
|
||||
Assert.Equal(DownloadType.Torrent, torrentResult.Type);
|
||||
|
||||
|
|
@ -117,7 +114,7 @@ public class TorBoxDebridClientTest
|
|||
}
|
||||
};
|
||||
|
||||
var clientMock = new Mock<TorBoxDebridClient>(_loggerMock.Object, _httpClientFactoryMock.Object, _fileFilterMock.Object, _coordinatorMock.Object, _settings);
|
||||
var clientMock = new Mock<TorBoxDebridClient>(_loggerMock.Object, _httpClientFactoryMock.Object, _fileFilterMock.Object, _coordinatorMock.Object);
|
||||
clientMock.Protected().Setup<Task<Response<List<AvailableTorrent?>>>>("GetTorrentAvailability", hash).ReturnsAsync(availability);
|
||||
|
||||
// Act
|
||||
|
|
@ -160,7 +157,7 @@ public class TorBoxDebridClientTest
|
|||
}
|
||||
};
|
||||
|
||||
var clientMock = new Mock<TorBoxDebridClient>(_loggerMock.Object, _httpClientFactoryMock.Object, _fileFilterMock.Object, _coordinatorMock.Object, _settings);
|
||||
var clientMock = new Mock<TorBoxDebridClient>(_loggerMock.Object, _httpClientFactoryMock.Object, _fileFilterMock.Object, _coordinatorMock.Object);
|
||||
clientMock.Protected().Setup<Task<Response<List<AvailableTorrent?>>>>("GetTorrentAvailability", hash).ReturnsAsync(torrentAvailability);
|
||||
clientMock.Protected().Setup<Task<Response<List<AvailableUsenet?>>>>("GetUsenetAvailability", hash).ReturnsAsync(usenetAvailability);
|
||||
|
||||
|
|
@ -189,7 +186,7 @@ public class TorBoxDebridClientTest
|
|||
Data = new()
|
||||
};
|
||||
|
||||
var clientMock = new Mock<TorBoxDebridClient>(_loggerMock.Object, _httpClientFactoryMock.Object, _fileFilterMock.Object, _coordinatorMock.Object, _settings);
|
||||
var clientMock = new Mock<TorBoxDebridClient>(_loggerMock.Object, _httpClientFactoryMock.Object, _fileFilterMock.Object, _coordinatorMock.Object);
|
||||
clientMock.Protected().Setup<Task<Response<List<AvailableTorrent?>>>>("GetTorrentAvailability", hash).ReturnsAsync(torrentAvailability);
|
||||
clientMock.Protected().Setup<Task<Response<List<AvailableUsenet?>>>>("GetUsenetAvailability", hash).ReturnsAsync(usenetAvailability);
|
||||
|
||||
|
|
@ -201,17 +198,17 @@ public class TorBoxDebridClientTest
|
|||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Delete_CallsTorrentsControlById_WhenTypeIsTorrent()
|
||||
public async Task Delete_CallsTorrentsControl_WhenTypeIsTorrent()
|
||||
{
|
||||
// Arrange
|
||||
var torrent = new Torrent
|
||||
{
|
||||
RdId = "12345",
|
||||
RdId = "torrent-id",
|
||||
Type = DownloadType.Torrent
|
||||
};
|
||||
|
||||
var torrentsApiMock = new Mock<ITorrentsApi>();
|
||||
var clientMock = new Mock<TorBoxDebridClient>(_loggerMock.Object, _httpClientFactoryMock.Object, _fileFilterMock.Object, _coordinatorMock.Object, _settings);
|
||||
var clientMock = new Mock<TorBoxDebridClient>(_loggerMock.Object, _httpClientFactoryMock.Object, _fileFilterMock.Object, _coordinatorMock.Object);
|
||||
var torBoxClientMock = new Mock<ITorBoxNetClient>();
|
||||
|
||||
torBoxClientMock.Setup(m => m.Torrents).Returns(torrentsApiMock.Object);
|
||||
|
|
@ -221,7 +218,7 @@ public class TorBoxDebridClientTest
|
|||
await clientMock.Object.Delete(torrent);
|
||||
|
||||
// Assert
|
||||
torrentsApiMock.Verify(m => m.ControlByIdAsync(12345, "delete", It.IsAny<CancellationToken>()), Times.Once);
|
||||
torrentsApiMock.Verify(m => m.ControlAsync("torrent-id", "delete", It.IsAny<CancellationToken>()), Times.Once);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
|
|
@ -235,7 +232,7 @@ public class TorBoxDebridClientTest
|
|||
};
|
||||
|
||||
var usenetApiMock = new Mock<IUsenetApi>();
|
||||
var clientMock = new Mock<TorBoxDebridClient>(_loggerMock.Object, _httpClientFactoryMock.Object, _fileFilterMock.Object, _coordinatorMock.Object, _settings);
|
||||
var clientMock = new Mock<TorBoxDebridClient>(_loggerMock.Object, _httpClientFactoryMock.Object, _fileFilterMock.Object, _coordinatorMock.Object);
|
||||
var torBoxClientMock = new Mock<ITorBoxNetClient>();
|
||||
|
||||
torBoxClientMock.Setup(m => m.Usenet).Returns(usenetApiMock.Object);
|
||||
|
|
@ -261,7 +258,7 @@ public class TorBoxDebridClientTest
|
|||
var link = "https://torbox.app/d/123/456";
|
||||
|
||||
var torrentsApiMock = new Mock<ITorrentsApi>();
|
||||
var clientMock = new Mock<TorBoxDebridClient>(_loggerMock.Object, _httpClientFactoryMock.Object, _fileFilterMock.Object, _coordinatorMock.Object, _settings);
|
||||
var clientMock = new Mock<TorBoxDebridClient>(_loggerMock.Object, _httpClientFactoryMock.Object, _fileFilterMock.Object, _coordinatorMock.Object);
|
||||
var torBoxClientMock = new Mock<ITorBoxNetClient>();
|
||||
|
||||
torBoxClientMock.Setup(m => m.Torrents).Returns(torrentsApiMock.Object);
|
||||
|
|
@ -294,7 +291,7 @@ public class TorBoxDebridClientTest
|
|||
var link = "https://torbox.app/d/123/456";
|
||||
|
||||
var usenetApiMock = new Mock<IUsenetApi>();
|
||||
var clientMock = new Mock<TorBoxDebridClient>(_loggerMock.Object, _httpClientFactoryMock.Object, _fileFilterMock.Object, _coordinatorMock.Object, _settings);
|
||||
var clientMock = new Mock<TorBoxDebridClient>(_loggerMock.Object, _httpClientFactoryMock.Object, _fileFilterMock.Object, _coordinatorMock.Object);
|
||||
var torBoxClientMock = new Mock<ITorBoxNetClient>();
|
||||
|
||||
torBoxClientMock.Setup(m => m.Usenet).Returns(usenetApiMock.Object);
|
||||
|
|
@ -326,7 +323,7 @@ public class TorBoxDebridClientTest
|
|||
var name = "test-nzb";
|
||||
var usenetApiMock = new Mock<IUsenetApi>();
|
||||
|
||||
var clientMock = new Mock<TorBoxDebridClient>(_loggerMock.Object, _httpClientFactoryMock.Object, _fileFilterMock.Object, _coordinatorMock.Object, _settings)
|
||||
var clientMock = new Mock<TorBoxDebridClient>(_loggerMock.Object, _httpClientFactoryMock.Object, _fileFilterMock.Object, _coordinatorMock.Object)
|
||||
{
|
||||
CallBase = true
|
||||
};
|
||||
|
|
@ -376,20 +373,25 @@ public class TorBoxDebridClientTest
|
|||
var torrent = new Torrent
|
||||
{
|
||||
Hash = "test-hash",
|
||||
RdId = "12345",
|
||||
RdFiles = JsonConvert.SerializeObject(files)
|
||||
};
|
||||
|
||||
var torrentsApiMock = new Mock<ITorrentsApi>();
|
||||
var clientMock = new Mock<TorBoxDebridClient>(_loggerMock.Object, _httpClientFactoryMock.Object, _fileFilterMock.Object, _coordinatorMock.Object, _settings);
|
||||
var clientMock = new Mock<TorBoxDebridClient>(_loggerMock.Object, _httpClientFactoryMock.Object, _fileFilterMock.Object, _coordinatorMock.Object);
|
||||
var torBoxClientMock = new Mock<ITorBoxNetClient>();
|
||||
|
||||
torBoxClientMock.Setup(m => m.Torrents).Returns(torrentsApiMock.Object);
|
||||
clientMock.Protected().Setup<ITorBoxNetClient>("GetClient", ItExpr.IsAny<String>()).Returns(torBoxClientMock.Object);
|
||||
|
||||
torrentsApiMock.Setup(m => m.GetHashInfoAsync("test-hash", true, It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(new TorrentInfoResult
|
||||
{
|
||||
Id = 12345
|
||||
});
|
||||
|
||||
_fileFilterMock.Setup(m => m.IsDownloadable(torrent, It.IsAny<String>(), It.IsAny<Int64>())).Returns(true);
|
||||
|
||||
_settings.Current.Provider.PreferZippedDownloads = false;
|
||||
Settings.Get.Provider.PreferZippedDownloads = false;
|
||||
|
||||
// Act
|
||||
var result = await clientMock.Object.GetDownloadInfos(torrent);
|
||||
|
|
@ -418,21 +420,26 @@ public class TorBoxDebridClientTest
|
|||
var torrent = new Torrent
|
||||
{
|
||||
Hash = "test-hash",
|
||||
RdId = "12345",
|
||||
RdName = "TestTorrent",
|
||||
RdFiles = JsonConvert.SerializeObject(files),
|
||||
DownloadClient = DownloadClient.Aria2c
|
||||
};
|
||||
|
||||
_settings.Current.Provider.PreferZippedDownloads = true;
|
||||
Settings.Get.Provider.PreferZippedDownloads = true;
|
||||
|
||||
var torrentsApiMock = new Mock<ITorrentsApi>();
|
||||
var clientMock = new Mock<TorBoxDebridClient>(_loggerMock.Object, _httpClientFactoryMock.Object, _fileFilterMock.Object, _coordinatorMock.Object, _settings);
|
||||
var clientMock = new Mock<TorBoxDebridClient>(_loggerMock.Object, _httpClientFactoryMock.Object, _fileFilterMock.Object, _coordinatorMock.Object);
|
||||
var torBoxClientMock = new Mock<ITorBoxNetClient>();
|
||||
|
||||
torBoxClientMock.Setup(m => m.Torrents).Returns(torrentsApiMock.Object);
|
||||
clientMock.Protected().Setup<ITorBoxNetClient>("GetClient", ItExpr.IsAny<String>()).Returns(torBoxClientMock.Object);
|
||||
|
||||
torrentsApiMock.Setup(m => m.GetHashInfoAsync("test-hash", true, It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(new TorrentInfoResult
|
||||
{
|
||||
Id = 12345
|
||||
});
|
||||
|
||||
_fileFilterMock.Setup(m => m.IsDownloadable(torrent, It.IsAny<String>(), It.IsAny<Int64>())).Returns(true);
|
||||
|
||||
// Act
|
||||
|
|
@ -457,7 +464,7 @@ public class TorBoxDebridClientTest
|
|||
var link = "https://torbox.app/fakedl/12345/6789";
|
||||
|
||||
var torrentsApiMock = new Mock<ITorrentsApi>();
|
||||
var clientMock = new Mock<TorBoxDebridClient>(_loggerMock.Object, _httpClientFactoryMock.Object, _fileFilterMock.Object, _coordinatorMock.Object, _settings);
|
||||
var clientMock = new Mock<TorBoxDebridClient>(_loggerMock.Object, _httpClientFactoryMock.Object, _fileFilterMock.Object, _coordinatorMock.Object);
|
||||
var torBoxClientMock = new Mock<ITorBoxNetClient>();
|
||||
|
||||
torBoxClientMock.Setup(m => m.Torrents).Returns(torrentsApiMock.Object);
|
||||
|
|
@ -489,7 +496,7 @@ public class TorBoxDebridClientTest
|
|||
var link = "https://torbox.app/fakedl/12345/zip";
|
||||
|
||||
var torrentsApiMock = new Mock<ITorrentsApi>();
|
||||
var clientMock = new Mock<TorBoxDebridClient>(_loggerMock.Object, _httpClientFactoryMock.Object, _fileFilterMock.Object, _coordinatorMock.Object, _settings);
|
||||
var clientMock = new Mock<TorBoxDebridClient>(_loggerMock.Object, _httpClientFactoryMock.Object, _fileFilterMock.Object, _coordinatorMock.Object);
|
||||
var torBoxClientMock = new Mock<ITorBoxNetClient>();
|
||||
|
||||
torBoxClientMock.Setup(m => m.Torrents).Returns(torrentsApiMock.Object);
|
||||
|
|
@ -531,13 +538,13 @@ public class TorBoxDebridClientTest
|
|||
};
|
||||
|
||||
var usenetApiMock = new Mock<IUsenetApi>();
|
||||
var clientMock = new Mock<TorBoxDebridClient>(_loggerMock.Object, _httpClientFactoryMock.Object, _fileFilterMock.Object, _coordinatorMock.Object, _settings);
|
||||
var clientMock = new Mock<TorBoxDebridClient>(_loggerMock.Object, _httpClientFactoryMock.Object, _fileFilterMock.Object, _coordinatorMock.Object);
|
||||
var torBoxClientMock = new Mock<ITorBoxNetClient>();
|
||||
|
||||
torBoxClientMock.Setup(m => m.Usenet).Returns(usenetApiMock.Object);
|
||||
clientMock.Protected().Setup<ITorBoxNetClient>("GetClient", ItExpr.IsAny<String>()).Returns(torBoxClientMock.Object);
|
||||
|
||||
usenetApiMock.Setup(m => m.GetCurrentAsync(true, 1000, It.IsAny<CancellationToken>()))
|
||||
usenetApiMock.Setup(m => m.GetCurrentAsync(true, It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(new List<UsenetInfoResult>
|
||||
{
|
||||
new()
|
||||
|
|
@ -549,7 +556,7 @@ public class TorBoxDebridClientTest
|
|||
|
||||
_fileFilterMock.Setup(m => m.IsDownloadable(torrent, It.IsAny<String>(), It.IsAny<Int64>())).Returns(true);
|
||||
|
||||
_settings.Current.Provider.PreferZippedDownloads = false;
|
||||
Settings.Get.Provider.PreferZippedDownloads = false;
|
||||
|
||||
// Act
|
||||
var result = await clientMock.Object.GetDownloadInfos(torrent);
|
||||
|
|
@ -572,7 +579,7 @@ public class TorBoxDebridClientTest
|
|||
var link = "https://torbox.app/fakedl/98765/4321";
|
||||
|
||||
var usenetApiMock = new Mock<IUsenetApi>();
|
||||
var clientMock = new Mock<TorBoxDebridClient>(_loggerMock.Object, _httpClientFactoryMock.Object, _fileFilterMock.Object, _coordinatorMock.Object, _settings);
|
||||
var clientMock = new Mock<TorBoxDebridClient>(_loggerMock.Object, _httpClientFactoryMock.Object, _fileFilterMock.Object, _coordinatorMock.Object);
|
||||
var torBoxClientMock = new Mock<ITorBoxNetClient>();
|
||||
|
||||
torBoxClientMock.Setup(m => m.Usenet).Returns(usenetApiMock.Object);
|
||||
|
|
@ -600,7 +607,7 @@ public class TorBoxDebridClientTest
|
|||
var torrentsApiMock = new Mock<ITorrentsApi>();
|
||||
var userApiMock = new Mock<IUserApi>();
|
||||
|
||||
var clientMock = new Mock<TorBoxDebridClient>(_loggerMock.Object, _httpClientFactoryMock.Object, _fileFilterMock.Object, _coordinatorMock.Object, _settings)
|
||||
var clientMock = new Mock<TorBoxDebridClient>(_loggerMock.Object, _httpClientFactoryMock.Object, _fileFilterMock.Object, _coordinatorMock.Object)
|
||||
{
|
||||
CallBase = true
|
||||
};
|
||||
|
|
@ -640,7 +647,7 @@ public class TorBoxDebridClientTest
|
|||
var torrentsApiMock = new Mock<ITorrentsApi>();
|
||||
var userApiMock = new Mock<IUserApi>();
|
||||
|
||||
var clientMock = new Mock<TorBoxDebridClient>(_loggerMock.Object, _httpClientFactoryMock.Object, _fileFilterMock.Object, _coordinatorMock.Object, _settings)
|
||||
var clientMock = new Mock<TorBoxDebridClient>(_loggerMock.Object, _httpClientFactoryMock.Object, _fileFilterMock.Object, _coordinatorMock.Object)
|
||||
{
|
||||
CallBase = true
|
||||
};
|
||||
|
|
@ -678,7 +685,7 @@ public class TorBoxDebridClientTest
|
|||
var torrentsApiMock = new Mock<ITorrentsApi>();
|
||||
var userApiMock = new Mock<IUserApi>();
|
||||
|
||||
var clientMock = new Mock<TorBoxDebridClient>(_loggerMock.Object, _httpClientFactoryMock.Object, _fileFilterMock.Object, _coordinatorMock.Object, _settings)
|
||||
var clientMock = new Mock<TorBoxDebridClient>(_loggerMock.Object, _httpClientFactoryMock.Object, _fileFilterMock.Object, _coordinatorMock.Object)
|
||||
{
|
||||
CallBase = true
|
||||
};
|
||||
|
|
@ -717,7 +724,7 @@ public class TorBoxDebridClientTest
|
|||
var torrentsApiMock = new Mock<ITorrentsApi>();
|
||||
var userApiMock = new Mock<IUserApi>();
|
||||
|
||||
var clientMock = new Mock<TorBoxDebridClient>(_loggerMock.Object, _httpClientFactoryMock.Object, _fileFilterMock.Object, _coordinatorMock.Object, _settings)
|
||||
var clientMock = new Mock<TorBoxDebridClient>(_loggerMock.Object, _httpClientFactoryMock.Object, _fileFilterMock.Object, _coordinatorMock.Object)
|
||||
{
|
||||
CallBase = true
|
||||
};
|
||||
|
|
@ -760,7 +767,7 @@ public class TorBoxDebridClientTest
|
|||
var torrentsApiMock = new Mock<ITorrentsApi>();
|
||||
var userApiMock = new Mock<IUserApi>();
|
||||
|
||||
var clientMock = new Mock<TorBoxDebridClient>(_loggerMock.Object, _httpClientFactoryMock.Object, _fileFilterMock.Object, _coordinatorMock.Object, _settings)
|
||||
var clientMock = new Mock<TorBoxDebridClient>(_loggerMock.Object, _httpClientFactoryMock.Object, _fileFilterMock.Object, _coordinatorMock.Object)
|
||||
{
|
||||
CallBase = true
|
||||
};
|
||||
|
|
@ -799,7 +806,7 @@ public class TorBoxDebridClientTest
|
|||
var nzbLink = "https://example.com/test.nzb";
|
||||
var usenetApiMock = new Mock<IUsenetApi>();
|
||||
|
||||
var clientMock = new Mock<TorBoxDebridClient>(_loggerMock.Object, _httpClientFactoryMock.Object, _fileFilterMock.Object, _coordinatorMock.Object, _settings)
|
||||
var clientMock = new Mock<TorBoxDebridClient>(_loggerMock.Object, _httpClientFactoryMock.Object, _fileFilterMock.Object, _coordinatorMock.Object)
|
||||
{
|
||||
CallBase = true
|
||||
};
|
||||
|
|
@ -830,7 +837,7 @@ public class TorBoxDebridClientTest
|
|||
var name = "test.nzb";
|
||||
var usenetApiMock = new Mock<IUsenetApi>();
|
||||
|
||||
var clientMock = new Mock<TorBoxDebridClient>(_loggerMock.Object, _httpClientFactoryMock.Object, _fileFilterMock.Object, _coordinatorMock.Object, _settings)
|
||||
var clientMock = new Mock<TorBoxDebridClient>(_loggerMock.Object, _httpClientFactoryMock.Object, _fileFilterMock.Object, _coordinatorMock.Object)
|
||||
{
|
||||
CallBase = true
|
||||
};
|
||||
|
|
@ -865,7 +872,7 @@ public class TorBoxDebridClientTest
|
|||
Filename = "test-file"
|
||||
};
|
||||
|
||||
var clientMock = new Mock<TorBoxDebridClient>(_loggerMock.Object, _httpClientFactoryMock.Object, _fileFilterMock.Object, _coordinatorMock.Object, _settings);
|
||||
var clientMock = new Mock<TorBoxDebridClient>(_loggerMock.Object, _httpClientFactoryMock.Object, _fileFilterMock.Object, _coordinatorMock.Object);
|
||||
|
||||
// Act
|
||||
var result = await clientMock.Object.UpdateData(torrent, torrentClientTorrent);
|
||||
|
|
@ -891,7 +898,7 @@ public class TorBoxDebridClientTest
|
|||
Filename = "test-torrent"
|
||||
};
|
||||
|
||||
var clientMock = new Mock<TorBoxDebridClient>(_loggerMock.Object, _httpClientFactoryMock.Object, _fileFilterMock.Object, _coordinatorMock.Object, _settings);
|
||||
var clientMock = new Mock<TorBoxDebridClient>(_loggerMock.Object, _httpClientFactoryMock.Object, _fileFilterMock.Object, _coordinatorMock.Object);
|
||||
|
||||
// Act
|
||||
await clientMock.Object.UpdateData(torrent, torrentClientTorrent);
|
||||
|
|
@ -922,7 +929,7 @@ public class TorBoxDebridClientTest
|
|||
Filename = "test-torrent"
|
||||
};
|
||||
|
||||
var clientMock = new Mock<TorBoxDebridClient>(_loggerMock.Object, _httpClientFactoryMock.Object, _fileFilterMock.Object, _coordinatorMock.Object, _settings);
|
||||
var clientMock = new Mock<TorBoxDebridClient>(_loggerMock.Object, _httpClientFactoryMock.Object, _fileFilterMock.Object, _coordinatorMock.Object);
|
||||
|
||||
// Act
|
||||
var result = await clientMock.Object.UpdateData(torrent, torrentClientTorrent);
|
||||
|
|
|
|||
|
|
@ -13,65 +13,76 @@ public class TorrentRunnerTest
|
|||
[Fact]
|
||||
public async Task Tick_ShouldNotRequeueCompletedErrorTorrent()
|
||||
{
|
||||
var testSettings = new TestSettings();
|
||||
var runnerState = new TorrentRunnerState();
|
||||
var originalApiKey = Settings.Get.Provider.ApiKey;
|
||||
var originalProvider = Settings.Get.Provider.Provider;
|
||||
var originalMaxParallelDownloads = Settings.Get.Provider.MaxParallelDownloads;
|
||||
var originalDownloadPath = Settings.Get.DownloadClient.DownloadPath;
|
||||
|
||||
testSettings.Current.Provider.ApiKey = "test-api-key";
|
||||
testSettings.Current.Provider.Provider = Provider.RealDebrid;
|
||||
testSettings.Current.Provider.MaxParallelDownloads = 1;
|
||||
testSettings.Current.DownloadClient.DownloadPath = "/downloads";
|
||||
TorrentRunner.ActiveDownloadClients.Clear();
|
||||
TorrentRunner.ActiveUnpackClients.Clear();
|
||||
|
||||
var erroredTorrent = new Torrent
|
||||
try
|
||||
{
|
||||
TorrentId = Guid.NewGuid(),
|
||||
Hash = "hash-1",
|
||||
RdName = "Torrent 1",
|
||||
FileOrMagnet = "magnet:?xt=urn:btih:hash-1",
|
||||
Type = DownloadType.Torrent,
|
||||
RdStatus = TorrentStatus.Queued,
|
||||
DeleteOnError = 10,
|
||||
Error = "Could not add to provider: Infringing file",
|
||||
Completed = DateTimeOffset.UtcNow.AddMinutes(-5),
|
||||
Downloads = new List<Download>()
|
||||
};
|
||||
Settings.Get.Provider.ApiKey = "test-api-key";
|
||||
Settings.Get.Provider.Provider = Provider.RealDebrid;
|
||||
Settings.Get.Provider.MaxParallelDownloads = 1;
|
||||
Settings.Get.DownloadClient.DownloadPath = "/downloads";
|
||||
|
||||
var torrentDataMock = new Mock<ITorrentData>(MockBehavior.Strict);
|
||||
var erroredTorrent = new Torrent
|
||||
{
|
||||
TorrentId = Guid.NewGuid(),
|
||||
Hash = "hash-1",
|
||||
RdName = "Torrent 1",
|
||||
FileOrMagnet = "magnet:?xt=urn:btih:hash-1",
|
||||
Type = DownloadType.Torrent,
|
||||
RdStatus = TorrentStatus.Queued,
|
||||
DeleteOnError = 10,
|
||||
Error = "Could not add to provider: Infringing file",
|
||||
Completed = DateTimeOffset.UtcNow.AddMinutes(-5),
|
||||
Downloads = new List<Download>()
|
||||
};
|
||||
|
||||
torrentDataMock.Setup(m => m.Get())
|
||||
.ReturnsAsync(new List<Torrent>
|
||||
{
|
||||
erroredTorrent
|
||||
});
|
||||
var torrentDataMock = new Mock<ITorrentData>(MockBehavior.Strict);
|
||||
torrentDataMock.Setup(m => m.Get()).ReturnsAsync(new List<Torrent>
|
||||
{
|
||||
erroredTorrent
|
||||
});
|
||||
|
||||
var torrents = new Torrents(Mock.Of<ILogger<Torrents>>(),
|
||||
torrentDataMock.Object,
|
||||
Mock.Of<IDownloads>(),
|
||||
null!,
|
||||
null!,
|
||||
null!,
|
||||
null!,
|
||||
null!,
|
||||
null!,
|
||||
null!,
|
||||
null!,
|
||||
testSettings,
|
||||
runnerState);
|
||||
var torrents = new Torrents(Mock.Of<ILogger<Torrents>>(),
|
||||
torrentDataMock.Object,
|
||||
Mock.Of<IDownloads>(),
|
||||
null!,
|
||||
null!,
|
||||
null!,
|
||||
null!,
|
||||
null!,
|
||||
null!,
|
||||
null!,
|
||||
null!);
|
||||
|
||||
var torrentRunner = new TorrentRunner(Mock.Of<ILogger<TorrentRunner>>(),
|
||||
torrents,
|
||||
new(null!),
|
||||
new(null!, torrents),
|
||||
Mock.Of<IHttpClientFactory>(),
|
||||
new RateLimitCoordinator(),
|
||||
testSettings,
|
||||
runnerState);
|
||||
var torrentRunner = new TorrentRunner(Mock.Of<ILogger<TorrentRunner>>(),
|
||||
torrents,
|
||||
new Downloads(null!),
|
||||
new RemoteService(null!, torrents),
|
||||
Mock.Of<IHttpClientFactory>(),
|
||||
new RateLimitCoordinator());
|
||||
|
||||
await torrentRunner.Tick();
|
||||
await torrentRunner.Tick();
|
||||
|
||||
torrentDataMock.Verify(m => m.UpdateComplete(It.IsAny<Guid>(),
|
||||
It.IsAny<String?>(),
|
||||
It.IsAny<DateTimeOffset?>(),
|
||||
It.IsAny<Boolean>()),
|
||||
Times.Never);
|
||||
torrentDataMock.Verify(m => m.UpdateComplete(It.IsAny<Guid>(),
|
||||
It.IsAny<string?>(),
|
||||
It.IsAny<DateTimeOffset?>(),
|
||||
It.IsAny<bool>()),
|
||||
Times.Never);
|
||||
}
|
||||
finally
|
||||
{
|
||||
Settings.Get.Provider.ApiKey = originalApiKey;
|
||||
Settings.Get.Provider.Provider = originalProvider;
|
||||
Settings.Get.Provider.MaxParallelDownloads = originalMaxParallelDownloads;
|
||||
Settings.Get.DownloadClient.DownloadPath = originalDownloadPath;
|
||||
TorrentRunner.ActiveDownloadClients.Clear();
|
||||
TorrentRunner.ActiveUnpackClients.Clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -96,7 +96,7 @@ public class TorrentsTest
|
|||
|
||||
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
|
||||
{
|
||||
settings.DownloadClient.DownloadPath = @"C:\Downloads";
|
||||
Settings.Get.DownloadClient.DownloadPath = settings.DownloadClient.DownloadPath = @"C:\Downloads";
|
||||
}
|
||||
|
||||
var downloadPath = Path.Combine(settings.DownloadClient.DownloadPath, category);
|
||||
|
|
@ -120,9 +120,7 @@ public class TorrentsTest
|
|||
null!,
|
||||
null!,
|
||||
null!,
|
||||
null!,
|
||||
new TestSettings(),
|
||||
new TorrentRunnerState());
|
||||
null!);
|
||||
|
||||
mocks.ProcessMock.Setup(p => p.WaitForExit(It.IsAny<Int32>())).Returns(true);
|
||||
|
||||
|
|
@ -167,9 +165,9 @@ public class TorrentsTest
|
|||
mocks.TorrentDataMock.Setup(t => t.GetById(torrent.TorrentId)).Returns(Task.FromResult<Torrent?>(torrent));
|
||||
mocks.DownloadsMock.Setup(d => d.GetForTorrent(torrent.TorrentId)).ReturnsAsync(downloads);
|
||||
|
||||
var downloadPath = Path.Combine(settings.DownloadClient.DownloadPath, torrent.Category ?? "");
|
||||
var torrentPath = Path.Combine(downloadPath, torrent.RdName ?? "");
|
||||
var filePath = Path.Combine(torrentPath, downloads[0].FileName ?? "");
|
||||
var downloadPath = $"{settings.DownloadClient.DownloadPath}/{torrent.Category}";
|
||||
var torrentPath = $"{downloadPath}/{torrent.RdName}";
|
||||
var filePath = $"{torrentPath}/{downloads[0].FileName}";
|
||||
|
||||
var fileSystemMock = new MockFileSystem(new Dictionary<String, MockFileData>
|
||||
{
|
||||
|
|
@ -188,9 +186,7 @@ public class TorrentsTest
|
|||
null!,
|
||||
null!,
|
||||
null!,
|
||||
null!,
|
||||
new TestSettings(),
|
||||
new TorrentRunnerState());
|
||||
null!);
|
||||
|
||||
//Act
|
||||
await torrents.RunTorrentComplete(torrent.TorrentId, settings);
|
||||
|
|
@ -217,9 +213,9 @@ public class TorrentsTest
|
|||
mocks.TorrentDataMock.Setup(t => t.GetById(torrent.TorrentId)).Returns(Task.FromResult<Torrent?>(torrent));
|
||||
mocks.DownloadsMock.Setup(d => d.GetForTorrent(torrent.TorrentId)).ReturnsAsync(downloads);
|
||||
|
||||
var downloadPath = Path.Combine(settings.DownloadClient.DownloadPath, torrent.Category ?? "");
|
||||
var torrentPath = Path.Combine(downloadPath, torrent.RdName ?? "");
|
||||
var filePath = Path.Combine(torrentPath, downloads[0].FileName ?? "");
|
||||
var downloadPath = $"{settings.DownloadClient.DownloadPath}/{torrent.Category}";
|
||||
var torrentPath = $"{downloadPath}/{torrent.RdName}";
|
||||
var filePath = $"{torrentPath}/{downloads[0].FileName}";
|
||||
|
||||
var fileSystemMock = new MockFileSystem(new Dictionary<String, MockFileData>
|
||||
{
|
||||
|
|
@ -238,9 +234,7 @@ public class TorrentsTest
|
|||
null!,
|
||||
null!,
|
||||
null!,
|
||||
null!,
|
||||
new TestSettings(),
|
||||
new TorrentRunnerState());
|
||||
null!);
|
||||
|
||||
mocks.ProcessMock.Setup(p => p.WaitForExit(It.IsAny<Int32>()))
|
||||
.Callback(() =>
|
||||
|
|
@ -286,9 +280,9 @@ public class TorrentsTest
|
|||
mocks.TorrentDataMock.Setup(t => t.GetById(torrent.TorrentId)).Returns(Task.FromResult<Torrent?>(torrent));
|
||||
mocks.DownloadsMock.Setup(d => d.GetForTorrent(torrent.TorrentId)).ReturnsAsync(downloads);
|
||||
|
||||
var downloadPath = Path.Combine(settings.DownloadClient.DownloadPath, torrent.Category ?? "");
|
||||
var torrentPath = Path.Combine(downloadPath, torrent.RdName ?? "");
|
||||
var filePath = Path.Combine(torrentPath, downloads[0].FileName ?? "");
|
||||
var downloadPath = $"{settings.DownloadClient.DownloadPath}/{torrent.Category}";
|
||||
var torrentPath = $"{downloadPath}/{torrent.RdName}";
|
||||
var filePath = $"{torrentPath}/{downloads[0].FileName}";
|
||||
|
||||
var fileSystemMock = new MockFileSystem(new Dictionary<String, MockFileData>
|
||||
{
|
||||
|
|
@ -307,9 +301,7 @@ public class TorrentsTest
|
|||
null!,
|
||||
null!,
|
||||
null!,
|
||||
null!,
|
||||
new TestSettings(),
|
||||
new TorrentRunnerState());
|
||||
null!);
|
||||
|
||||
mocks.ProcessMock.Setup(p => p.WaitForExit(It.IsAny<Int32>()))
|
||||
.Callback(() =>
|
||||
|
|
@ -372,9 +364,7 @@ public class TorrentsTest
|
|||
null!,
|
||||
null!,
|
||||
null!,
|
||||
null!,
|
||||
new TestSettings(),
|
||||
new TorrentRunnerState());
|
||||
null!);
|
||||
|
||||
// Act
|
||||
await torrents.AddNzbFileToDebridQueue(bytes, "filename.nzb", torrent);
|
||||
|
|
@ -422,9 +412,7 @@ public class TorrentsTest
|
|||
null!,
|
||||
null!,
|
||||
null!,
|
||||
null!,
|
||||
new TestSettings(),
|
||||
new TorrentRunnerState());
|
||||
null!);
|
||||
|
||||
// Act
|
||||
await torrents.AddNzbLinkToDebridQueue(link, torrent);
|
||||
|
|
|
|||
|
|
@ -1,59 +0,0 @@
|
|||
using RdtClient.Data.Models.Internal;
|
||||
using RdtClient.Service.Services;
|
||||
|
||||
namespace RdtClient.Service.Test;
|
||||
|
||||
internal sealed class TestSettings(DbSettings? settings = null) : ISettings
|
||||
{
|
||||
public DbSettings Current { get; } = settings ?? new();
|
||||
|
||||
public String DefaultSavePath
|
||||
{
|
||||
get
|
||||
{
|
||||
var downloadPath = Current.DownloadClient.MappedPath.TrimEnd('\\').TrimEnd('/');
|
||||
|
||||
return downloadPath + Path.DirectorySeparatorChar;
|
||||
}
|
||||
}
|
||||
|
||||
public IList<SettingProperty> GetAll()
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
public Task Update(IList<SettingProperty> settings)
|
||||
{
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public Task Update(String settingId, Object? value)
|
||||
{
|
||||
SetValue(Current, settingId.Split(':'), 0, value);
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
private static void SetValue(Object target, IReadOnlyList<String> path, Int32 index, Object? value)
|
||||
{
|
||||
var property = target.GetType().GetProperty(path[index]) ?? throw new($"Unknown setting {String.Join(":", path)}");
|
||||
|
||||
if (index < path.Count - 1)
|
||||
{
|
||||
SetValue(property.GetValue(target)!, path, index + 1, value);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (value == null)
|
||||
{
|
||||
property.SetValue(target, null);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
var propertyType = Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType;
|
||||
var convertedValue = propertyType.IsEnum ? Enum.Parse(propertyType, value.ToString()!) : Convert.ChangeType(value, propertyType);
|
||||
property.SetValue(target, convertedValue);
|
||||
}
|
||||
}
|
||||
|
|
@ -8,7 +8,7 @@ using DownloadClient = RdtClient.Data.Enums.DownloadClient;
|
|||
|
||||
namespace RdtClient.Service.BackgroundServices;
|
||||
|
||||
public class DiskSpaceMonitor(ILogger<DiskSpaceMonitor> logger, IServiceProvider serviceProvider, ISettings settings, ITorrentRunnerState runnerState) : BackgroundService
|
||||
public class DiskSpaceMonitor(ILogger<DiskSpaceMonitor> logger, IServiceProvider serviceProvider) : BackgroundService
|
||||
{
|
||||
private static DiskSpaceStatus? _lastStatus;
|
||||
private Boolean _isPausedForLowDiskSpace;
|
||||
|
|
@ -34,7 +34,7 @@ public class DiskSpaceMonitor(ILogger<DiskSpaceMonitor> logger, IServiceProvider
|
|||
{
|
||||
try
|
||||
{
|
||||
var minimumFreeSpaceGB = settings.Current.DownloadClient.MinimumFreeSpaceGB;
|
||||
var minimumFreeSpaceGB = Settings.Get.DownloadClient.MinimumFreeSpaceGB;
|
||||
|
||||
if (minimumFreeSpaceGB <= 0)
|
||||
{
|
||||
|
|
@ -43,14 +43,14 @@ public class DiskSpaceMonitor(ILogger<DiskSpaceMonitor> logger, IServiceProvider
|
|||
continue;
|
||||
}
|
||||
|
||||
var intervalMinutes = settings.Current.DownloadClient.DiskSpaceCheckIntervalMinutes;
|
||||
var intervalMinutes = Settings.Get.DownloadClient.DiskSpaceCheckIntervalMinutes;
|
||||
|
||||
if (intervalMinutes < 1)
|
||||
{
|
||||
intervalMinutes = 1;
|
||||
}
|
||||
|
||||
var downloadPath = settings.Current.DownloadClient.DownloadPath;
|
||||
var downloadPath = Settings.Get.DownloadClient.DownloadPath;
|
||||
logger.LogDebug($"Checking disk space for path: {downloadPath}");
|
||||
|
||||
if (!Directory.Exists(downloadPath))
|
||||
|
|
@ -78,7 +78,7 @@ public class DiskSpaceMonitor(ILogger<DiskSpaceMonitor> logger, IServiceProvider
|
|||
|
||||
var pausedCount = 0;
|
||||
|
||||
foreach (var download in runnerState.ActiveDownloadClients)
|
||||
foreach (var download in TorrentRunner.ActiveDownloadClients)
|
||||
{
|
||||
if (download.Value.Type == DownloadClient.Bezzad)
|
||||
{
|
||||
|
|
@ -90,7 +90,7 @@ public class DiskSpaceMonitor(ILogger<DiskSpaceMonitor> logger, IServiceProvider
|
|||
|
||||
logger.LogInformation($"Paused {pausedCount} active Bezzad downloads");
|
||||
|
||||
runnerState.IsPausedForLowDiskSpace = true;
|
||||
TorrentRunner.IsPausedForLowDiskSpace = true;
|
||||
_isPausedForLowDiskSpace = true;
|
||||
|
||||
var status = new DiskSpaceStatus
|
||||
|
|
@ -125,7 +125,7 @@ public class DiskSpaceMonitor(ILogger<DiskSpaceMonitor> logger, IServiceProvider
|
|||
|
||||
var resumedCount = 0;
|
||||
|
||||
foreach (var download in runnerState.ActiveDownloadClients)
|
||||
foreach (var download in TorrentRunner.ActiveDownloadClients)
|
||||
{
|
||||
if (download.Value.Type == DownloadClient.Bezzad)
|
||||
{
|
||||
|
|
@ -137,7 +137,7 @@ public class DiskSpaceMonitor(ILogger<DiskSpaceMonitor> logger, IServiceProvider
|
|||
|
||||
logger.LogInformation($"Resumed {resumedCount} Bezzad downloads");
|
||||
|
||||
runnerState.IsPausedForLowDiskSpace = false;
|
||||
TorrentRunner.IsPausedForLowDiskSpace = false;
|
||||
_isPausedForLowDiskSpace = false;
|
||||
|
||||
var status = new DiskSpaceStatus
|
||||
|
|
|
|||
|
|
@ -7,7 +7,7 @@ using RdtClient.Service.Services;
|
|||
|
||||
namespace RdtClient.Service.BackgroundServices;
|
||||
|
||||
public class ProviderUpdater(ILogger<ProviderUpdater> logger, IServiceProvider serviceProvider, ISettings settings) : BackgroundService
|
||||
public class ProviderUpdater(ILogger<ProviderUpdater> logger, IServiceProvider serviceProvider) : BackgroundService
|
||||
{
|
||||
private static DateTime _nextUpdate = DateTime.UtcNow;
|
||||
|
||||
|
|
@ -30,11 +30,11 @@ public class ProviderUpdater(ILogger<ProviderUpdater> logger, IServiceProvider s
|
|||
{
|
||||
var torrents = await torrentService.Get();
|
||||
|
||||
if (_nextUpdate < DateTime.UtcNow && (settings.Current.Provider.AutoImport || torrents.Any(t => t.RdStatus != TorrentStatus.Finished) || RdtHub.HasConnections))
|
||||
if (_nextUpdate < DateTime.UtcNow && (Settings.Get.Provider.AutoImport || torrents.Any(t => t.RdStatus != TorrentStatus.Finished) || RdtHub.HasConnections))
|
||||
{
|
||||
logger.LogDebug($"Updating torrent info from debrid provider");
|
||||
|
||||
var updateTime = settings.Current.Provider.CheckInterval * 3;
|
||||
var updateTime = Settings.Get.Provider.CheckInterval * 3;
|
||||
|
||||
if (updateTime < 30)
|
||||
{
|
||||
|
|
@ -43,7 +43,7 @@ public class ProviderUpdater(ILogger<ProviderUpdater> logger, IServiceProvider s
|
|||
|
||||
if (RdtHub.HasConnections)
|
||||
{
|
||||
updateTime = settings.Current.Provider.CheckInterval;
|
||||
updateTime = Settings.Get.Provider.CheckInterval;
|
||||
|
||||
if (updateTime < 5)
|
||||
{
|
||||
|
|
|
|||
|
|
@ -8,7 +8,7 @@ using LogLevel = Microsoft.Extensions.Logging.LogLevel;
|
|||
|
||||
namespace RdtClient.Service.BackgroundServices;
|
||||
|
||||
public class WatchFolderChecker(ILogger<WatchFolderChecker> logger, IServiceProvider serviceProvider, ISettings settings) : BackgroundService
|
||||
public class WatchFolderChecker(ILogger<WatchFolderChecker> logger, IServiceProvider serviceProvider) : BackgroundService
|
||||
{
|
||||
private DateTime _prevCheck = DateTime.MinValue;
|
||||
|
||||
|
|
@ -28,7 +28,7 @@ public class WatchFolderChecker(ILogger<WatchFolderChecker> logger, IServiceProv
|
|||
{
|
||||
try
|
||||
{
|
||||
var nextCheck = _prevCheck.AddSeconds(Math.Max(settings.Current.Watch.Interval, 10));
|
||||
var nextCheck = _prevCheck.AddSeconds(Math.Max(Settings.Get.Watch.Interval, 10));
|
||||
|
||||
if (DateTime.Now < nextCheck)
|
||||
{
|
||||
|
|
@ -38,25 +38,25 @@ public class WatchFolderChecker(ILogger<WatchFolderChecker> logger, IServiceProv
|
|||
|
||||
_prevCheck = DateTime.Now;
|
||||
|
||||
if (String.IsNullOrWhiteSpace(settings.Current.Watch.Path))
|
||||
if (String.IsNullOrWhiteSpace(Settings.Get.Watch.Path))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var processedStorePath = Path.Combine(settings.Current.Watch.Path, "processed");
|
||||
var errorStorePath = Path.Combine(settings.Current.Watch.Path, "error");
|
||||
var processedStorePath = Path.Combine(Settings.Get.Watch.Path, "processed");
|
||||
var errorStorePath = Path.Combine(Settings.Get.Watch.Path, "error");
|
||||
|
||||
if (!String.IsNullOrWhiteSpace(settings.Current.Watch.ProcessedPath))
|
||||
if (!String.IsNullOrWhiteSpace(Settings.Get.Watch.ProcessedPath))
|
||||
{
|
||||
processedStorePath = settings.Current.Watch.ProcessedPath;
|
||||
processedStorePath = Settings.Get.Watch.ProcessedPath;
|
||||
}
|
||||
|
||||
if (!String.IsNullOrWhiteSpace(settings.Current.Watch.ErrorPath))
|
||||
if (!String.IsNullOrWhiteSpace(Settings.Get.Watch.ErrorPath))
|
||||
{
|
||||
errorStorePath = settings.Current.Watch.ErrorPath;
|
||||
errorStorePath = Settings.Get.Watch.ErrorPath;
|
||||
}
|
||||
|
||||
var torrentFiles = Directory.GetFiles(settings.Current.Watch.Path, "*.*", SearchOption.TopDirectoryOnly);
|
||||
var torrentFiles = Directory.GetFiles(Settings.Get.Watch.Path, "*.*", SearchOption.TopDirectoryOnly);
|
||||
|
||||
foreach (var torrentFile in torrentFiles)
|
||||
{
|
||||
|
|
@ -78,22 +78,22 @@ public class WatchFolderChecker(ILogger<WatchFolderChecker> logger, IServiceProv
|
|||
|
||||
var torrent = new Torrent
|
||||
{
|
||||
DownloadClient = settings.Current.DownloadClient.Client,
|
||||
Category = settings.Current.Watch.Default.Category,
|
||||
HostDownloadAction = settings.Current.Watch.Default.HostDownloadAction,
|
||||
FinishedActionDelay = settings.Current.Watch.Default.FinishedActionDelay,
|
||||
DownloadAction = settings.Current.Watch.Default.OnlyDownloadAvailableFiles
|
||||
DownloadClient = Settings.Get.DownloadClient.Client,
|
||||
Category = Settings.Get.Watch.Default.Category,
|
||||
HostDownloadAction = Settings.Get.Watch.Default.HostDownloadAction,
|
||||
FinishedActionDelay = Settings.Get.Watch.Default.FinishedActionDelay,
|
||||
DownloadAction = Settings.Get.Watch.Default.OnlyDownloadAvailableFiles
|
||||
? TorrentDownloadAction.DownloadAvailableFiles
|
||||
: TorrentDownloadAction.DownloadAll,
|
||||
FinishedAction = settings.Current.Watch.Default.FinishedAction,
|
||||
DownloadMinSize = settings.Current.Watch.Default.MinFileSize,
|
||||
IncludeRegex = settings.Current.Watch.Default.IncludeRegex,
|
||||
ExcludeRegex = settings.Current.Watch.Default.ExcludeRegex,
|
||||
TorrentRetryAttempts = settings.Current.Watch.Default.TorrentRetryAttempts,
|
||||
DownloadRetryAttempts = settings.Current.Watch.Default.DownloadRetryAttempts,
|
||||
DeleteOnError = settings.Current.Watch.Default.DeleteOnError,
|
||||
Lifetime = settings.Current.Watch.Default.TorrentLifetime,
|
||||
Priority = settings.Current.Watch.Default.Priority > 0 ? settings.Current.Watch.Default.Priority : null
|
||||
FinishedAction = Settings.Get.Watch.Default.FinishedAction,
|
||||
DownloadMinSize = Settings.Get.Watch.Default.MinFileSize,
|
||||
IncludeRegex = Settings.Get.Watch.Default.IncludeRegex,
|
||||
ExcludeRegex = Settings.Get.Watch.Default.ExcludeRegex,
|
||||
TorrentRetryAttempts = Settings.Get.Watch.Default.TorrentRetryAttempts,
|
||||
DownloadRetryAttempts = Settings.Get.Watch.Default.DownloadRetryAttempts,
|
||||
DeleteOnError = Settings.Get.Watch.Default.DeleteOnError,
|
||||
Lifetime = Settings.Get.Watch.Default.TorrentLifetime,
|
||||
Priority = Settings.Get.Watch.Default.Priority > 0 ? Settings.Get.Watch.Default.Priority : null
|
||||
};
|
||||
|
||||
if (fileInfo.Extension == ".torrent")
|
||||
|
|
|
|||
|
|
@ -30,7 +30,6 @@ public static class DiConfig
|
|||
services.AddScoped<AllDebridDebridClient>();
|
||||
|
||||
services.AddSingleton<IRateLimitCoordinator, RateLimitCoordinator>();
|
||||
services.AddSingleton(TorrentRunner.SharedState);
|
||||
services.AddSingleton<IProcessFactory, ProcessFactory>();
|
||||
services.AddSingleton<IFileSystem, FileSystem>();
|
||||
|
||||
|
|
@ -42,8 +41,7 @@ public static class DiConfig
|
|||
services.AddScoped<Sabnzbd>();
|
||||
services.AddScoped<RemoteService>();
|
||||
services.AddScoped<RealDebridDebridClient>();
|
||||
services.AddSingleton<Settings>();
|
||||
services.AddSingleton<ISettings>(serviceProvider => serviceProvider.GetRequiredService<Settings>());
|
||||
services.AddScoped<Settings>();
|
||||
services.AddScoped<TorBoxDebridClient>();
|
||||
services.AddScoped<Torrents>();
|
||||
services.AddScoped<TorrentRunner>();
|
||||
|
|
@ -53,7 +51,7 @@ public static class DiConfig
|
|||
services.AddSingleton<ITrackerListGrabber, TrackerListGrabber>();
|
||||
services.AddSingleton<IEnricher, Enricher>();
|
||||
|
||||
services.AddScoped<IAuthorizationHandler, AuthSettingHandler>();
|
||||
services.AddSingleton<IAuthorizationHandler, AuthSettingHandler>();
|
||||
services.AddScoped<IAuthorizationHandler, SabnzbdHandler>();
|
||||
|
||||
services.AddHostedService<DiskSpaceMonitor>();
|
||||
|
|
|
|||
|
|
@ -214,18 +214,16 @@ public static class TorrentDtoMapper
|
|||
return "Finished";
|
||||
}
|
||||
|
||||
var prefix = torrent.Type == DownloadType.Nzb ? "NZB" : "Torrent";
|
||||
|
||||
return torrent.RdStatus switch
|
||||
{
|
||||
TorrentStatus.Queued => "Not Yet Added to Provider",
|
||||
TorrentStatus.Downloading when torrent.RdSeeders < 1 && torrent.Type != DownloadType.Nzb => "Torrent stalled",
|
||||
TorrentStatus.Downloading => $"{prefix} downloading ({torrent.RdProgress}% - {FileSizeHelper.FormatSize(torrent.RdSpeed)}/s)",
|
||||
TorrentStatus.Processing => $"{prefix} processing",
|
||||
TorrentStatus.WaitingForFileSelection => $"{prefix} waiting for file selection",
|
||||
TorrentStatus.Error => $"{prefix} error: {torrent.RdStatusRaw}",
|
||||
TorrentStatus.Finished => $"{prefix} finished, waiting for download links",
|
||||
TorrentStatus.Uploading => $"{prefix} uploading",
|
||||
TorrentStatus.Downloading => $"Torrent downloading ({torrent.RdProgress}% - {FileSizeHelper.FormatSize(torrent.RdSpeed)}/s)",
|
||||
TorrentStatus.Processing => "Torrent processing",
|
||||
TorrentStatus.WaitingForFileSelection => "Torrent waiting for file selection",
|
||||
TorrentStatus.Error => $"Torrent error: {torrent.RdStatusRaw}",
|
||||
TorrentStatus.Finished => "Torrent finished, waiting for download links",
|
||||
TorrentStatus.Uploading => "Torrent uploading",
|
||||
_ => "Unknown status"
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -8,7 +8,7 @@ public class AuthSettingRequirement : IAuthorizationRequirement
|
|||
{
|
||||
}
|
||||
|
||||
public class AuthSettingHandler(ISettings settings) : AuthorizationHandler<AuthSettingRequirement>
|
||||
public class AuthSettingHandler : AuthorizationHandler<AuthSettingRequirement>
|
||||
{
|
||||
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, AuthSettingRequirement requirement)
|
||||
{
|
||||
|
|
@ -17,7 +17,7 @@ public class AuthSettingHandler(ISettings settings) : AuthorizationHandler<AuthS
|
|||
context.Succeed(requirement);
|
||||
}
|
||||
|
||||
if (settings.Current.General.AuthenticationType == AuthenticationType.None)
|
||||
if (Settings.Get.General.AuthenticationType == AuthenticationType.None)
|
||||
{
|
||||
context.Succeed(requirement);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -9,7 +9,7 @@ public class SabnzbdRequirement : IAuthorizationRequirement
|
|||
{
|
||||
}
|
||||
|
||||
public class SabnzbdHandler(Authentication authentication, IHttpContextAccessor httpContextAccessor, ISettings settings) : AuthorizationHandler<SabnzbdRequirement>
|
||||
public class SabnzbdHandler(Authentication authentication, IHttpContextAccessor httpContextAccessor) : AuthorizationHandler<SabnzbdRequirement>
|
||||
{
|
||||
protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, SabnzbdRequirement requirement)
|
||||
{
|
||||
|
|
@ -22,7 +22,7 @@ public class SabnzbdHandler(Authentication authentication, IHttpContextAccessor
|
|||
return;
|
||||
}
|
||||
|
||||
if (settings.Current.General.AuthenticationType == AuthenticationType.None)
|
||||
if (Settings.Get.General.AuthenticationType == AuthenticationType.None)
|
||||
{
|
||||
context.Succeed(requirement);
|
||||
|
||||
|
|
@ -65,36 +65,6 @@ public class SabnzbdHandler(Authentication authentication, IHttpContextAccessor
|
|||
return;
|
||||
}
|
||||
|
||||
var apiKey = GetParam("apikey");
|
||||
|
||||
if (!String.IsNullOrWhiteSpace(apiKey))
|
||||
{
|
||||
var separatorIndex = apiKey.IndexOf(':');
|
||||
|
||||
if (separatorIndex <= 0 || separatorIndex == apiKey.Length - 1)
|
||||
{
|
||||
context.Fail();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
var username = apiKey[..separatorIndex];
|
||||
var password = apiKey[(separatorIndex + 1)..];
|
||||
|
||||
var loginResult = await authentication.Login(username, password);
|
||||
|
||||
if (loginResult.Succeeded)
|
||||
{
|
||||
context.Succeed(requirement);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
context.Fail();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
// Authentication required but missing credentials
|
||||
context.Fail();
|
||||
}
|
||||
|
|
|
|||
|
|
@ -12,9 +12,9 @@
|
|||
<PackageReference Include="AllDebrid.NET" Version="1.0.18" />
|
||||
<PackageReference Include="Aria2.NET" Version="1.0.6" />
|
||||
<PackageReference Include="DebridLinkFr.NET" Version="2.0.0" />
|
||||
<PackageReference Include="Downloader" Version="5.5.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.Http.Polly" Version="10.0.8" />
|
||||
<PackageReference Include="Microsoft.Extensions.Http.Resilience" Version="10.6.0" />
|
||||
<PackageReference Include="Downloader" Version="5.3.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.Http.Polly" Version="10.0.7" />
|
||||
<PackageReference Include="Microsoft.Extensions.Http.Resilience" Version="10.5.0" />
|
||||
<PackageReference Include="MonoTorrent" Version="3.0.2" />
|
||||
<PackageReference Include="Polly" Version="8.6.6" />
|
||||
<PackageReference Include="Premiumize.NET" Version="1.0.10" />
|
||||
|
|
@ -26,7 +26,7 @@
|
|||
<PackageReference Include="Synology.Api.Client" Version="[0.3.93]" />
|
||||
<PackageReference Include="TestableIO.System.IO.Abstractions" Version="22.1.1" />
|
||||
<PackageReference Include="TestableIO.System.IO.Abstractions.Wrappers" Version="22.1.1" />
|
||||
<PackageReference Include="TorBox.NET" Version="2.1.0" />
|
||||
<PackageReference Include="TorBox.NET" Version="1.6.2" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
|
|
|||
|
|
@ -17,13 +17,13 @@ public interface IAllDebridNetClientFactory
|
|||
public IAllDebridNETClient GetClient();
|
||||
}
|
||||
|
||||
public class AllDebridNetClientFactory(ILogger<AllDebridNetClientFactory> logger, IHttpClientFactory httpClientFactory, ISettings settings) : IAllDebridNetClientFactory
|
||||
public class AllDebridNetClientFactory(ILogger<AllDebridNetClientFactory> logger, IHttpClientFactory httpClientFactory) : IAllDebridNetClientFactory
|
||||
{
|
||||
public IAllDebridNETClient GetClient()
|
||||
{
|
||||
try
|
||||
{
|
||||
var apiKey = settings.Current.Provider.ApiKey;
|
||||
var apiKey = Settings.Get.Provider.ApiKey;
|
||||
|
||||
if (String.IsNullOrWhiteSpace(apiKey))
|
||||
{
|
||||
|
|
|
|||
|
|
@ -12,7 +12,7 @@ using Torrent = DebridLinkFrNET.Models.Torrent;
|
|||
|
||||
namespace RdtClient.Service.Services.DebridClients;
|
||||
|
||||
public class DebridLinkClient(ILogger<DebridLinkClient> logger, IHttpClientFactory httpClientFactory, IDownloadableFileFilter fileFilter, ISettings settings) : IDebridClient
|
||||
public class DebridLinkClient(ILogger<DebridLinkClient> logger, IHttpClientFactory httpClientFactory, IDownloadableFileFilter fileFilter) : IDebridClient
|
||||
{
|
||||
public async Task<IList<DebridClientTorrent>> GetDownloads()
|
||||
{
|
||||
|
|
@ -228,7 +228,7 @@ public class DebridLinkClient(ILogger<DebridLinkClient> logger, IHttpClientFacto
|
|||
{
|
||||
try
|
||||
{
|
||||
var apiKey = settings.Current.Provider.ApiKey;
|
||||
var apiKey = Settings.Get.Provider.ApiKey;
|
||||
|
||||
if (String.IsNullOrWhiteSpace(apiKey))
|
||||
{
|
||||
|
|
@ -236,7 +236,7 @@ public class DebridLinkClient(ILogger<DebridLinkClient> logger, IHttpClientFacto
|
|||
}
|
||||
|
||||
var httpClient = httpClientFactory.CreateClient();
|
||||
httpClient.Timeout = TimeSpan.FromSeconds(settings.Current.Provider.Timeout);
|
||||
httpClient.Timeout = TimeSpan.FromSeconds(Settings.Get.Provider.Timeout);
|
||||
|
||||
var debridLinkClient = new DebridLinkFrNETClient(apiKey, httpClient);
|
||||
|
||||
|
|
|
|||
|
|
@ -1,5 +1,4 @@
|
|||
using System.Diagnostics;
|
||||
using System.Net;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Newtonsoft.Json;
|
||||
using PremiumizeNET;
|
||||
|
|
@ -12,11 +11,8 @@ using Torrent = RdtClient.Data.Models.Data.Torrent;
|
|||
|
||||
namespace RdtClient.Service.Services.DebridClients;
|
||||
|
||||
public class PremiumizeDebridClient(ILogger<PremiumizeDebridClient> logger, IHttpClientFactory httpClientFactory, IDownloadableFileFilter fileFilter, ISettings settings)
|
||||
: IDebridClient
|
||||
public class PremiumizeDebridClient(ILogger<PremiumizeDebridClient> logger, IHttpClientFactory httpClientFactory, IDownloadableFileFilter fileFilter) : IDebridClient
|
||||
{
|
||||
private const String TransferCreateUrl = "https://www.premiumize.me/api/transfer/create";
|
||||
|
||||
public async Task<IList<DebridClientTorrent>> GetDownloads()
|
||||
{
|
||||
var results = await GetClient().Transfers.ListAsync();
|
||||
|
|
@ -37,22 +33,56 @@ public class PremiumizeDebridClient(ILogger<PremiumizeDebridClient> logger, IHtt
|
|||
|
||||
public async Task<String> AddTorrentMagnet(String magnetLink)
|
||||
{
|
||||
return await CreatePremiumizeNetTransfer(() => GetClient().Transfers.CreateAsync(magnetLink, ""), "magnet link");
|
||||
try
|
||||
{
|
||||
var result = await GetClient().Transfers.CreateAsync(magnetLink, "");
|
||||
|
||||
if (result?.Id == null)
|
||||
{
|
||||
throw new("Unable to add magnet link");
|
||||
}
|
||||
|
||||
var resultId = result.Id ?? throw new($"Invalid responseID {result.Id}");
|
||||
|
||||
return resultId;
|
||||
}
|
||||
catch (Exception ex) when (ex.Message.Contains("slow_down", StringComparison.OrdinalIgnoreCase) ||
|
||||
ex.Message.Contains("rate limit exceeded", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
throw new RateLimitException(ex.Message, TimeSpan.FromMinutes(2));
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<String> AddTorrentFile(Byte[] bytes)
|
||||
{
|
||||
return await CreatePremiumizeNetTransfer(() => GetClient().Transfers.CreateAsync(bytes, ""), "torrent file");
|
||||
try
|
||||
{
|
||||
var result = await GetClient().Transfers.CreateAsync(bytes, "");
|
||||
|
||||
if (result?.Id == null)
|
||||
{
|
||||
throw new("Unable to add torrent file");
|
||||
}
|
||||
|
||||
var resultId = result.Id ?? throw new($"Invalid responseID {result.Id}");
|
||||
|
||||
return resultId;
|
||||
}
|
||||
catch (Exception ex) when (ex.Message.Contains("slow_down", StringComparison.OrdinalIgnoreCase) ||
|
||||
ex.Message.Contains("rate limit exceeded", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
throw new RateLimitException(ex.Message, TimeSpan.FromMinutes(2));
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<String> AddNzbLink(String nzbLink)
|
||||
public Task<String> AddNzbLink(String nzbLink)
|
||||
{
|
||||
return await CreatePremiumizeNetTransfer(() => GetClient().Transfers.CreateAsync(nzbLink, ""), "NZB link");
|
||||
throw new NotSupportedException();
|
||||
}
|
||||
|
||||
public async Task<String> AddNzbFile(Byte[] bytes, String? name)
|
||||
public Task<String> AddNzbFile(Byte[] bytes, String? name)
|
||||
{
|
||||
return await CreateTransferFromNzbFile(bytes, GetNzbFileName(name));
|
||||
throw new NotSupportedException();
|
||||
}
|
||||
|
||||
public Task<IList<DebridClientAvailableFile>> GetAvailableFiles(String hash)
|
||||
|
|
@ -195,7 +225,13 @@ public class PremiumizeDebridClient(ILogger<PremiumizeDebridClient> logger, IHtt
|
|||
{
|
||||
try
|
||||
{
|
||||
var apiKey = GetApiKey();
|
||||
var apiKey = Settings.Get.Provider.ApiKey;
|
||||
|
||||
if (String.IsNullOrWhiteSpace(apiKey))
|
||||
{
|
||||
throw new("Premiumize API Key not set in the settings");
|
||||
}
|
||||
|
||||
var httpClient = httpClientFactory.CreateClient();
|
||||
httpClient.Timeout = TimeSpan.FromSeconds(10);
|
||||
|
||||
|
|
@ -217,146 +253,6 @@ public class PremiumizeDebridClient(ILogger<PremiumizeDebridClient> logger, IHtt
|
|||
}
|
||||
}
|
||||
|
||||
private String GetApiKey()
|
||||
{
|
||||
var apiKey = settings.Current.Provider.ApiKey;
|
||||
|
||||
if (String.IsNullOrWhiteSpace(apiKey))
|
||||
{
|
||||
throw new("Premiumize API Key not set in the settings");
|
||||
}
|
||||
|
||||
return apiKey;
|
||||
}
|
||||
|
||||
private async Task<String> CreatePremiumizeNetTransfer(Func<Task<TransferCreateResponse>> createTransfer, String description)
|
||||
{
|
||||
try
|
||||
{
|
||||
var result = await createTransfer();
|
||||
|
||||
if (String.IsNullOrWhiteSpace(result?.Id))
|
||||
{
|
||||
throw new($"Unable to add {description}");
|
||||
}
|
||||
|
||||
return result.Id;
|
||||
}
|
||||
catch (Exception ex) when (IsRateLimitMessage(ex.Message))
|
||||
{
|
||||
throw new RateLimitException(ex.Message, TimeSpan.FromMinutes(2));
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<String> CreateTransferFromNzbFile(Byte[] bytes, String fileName)
|
||||
{
|
||||
var content = new MultipartFormDataContent();
|
||||
var fileContent = new ByteArrayContent(bytes);
|
||||
content.Add(fileContent, "src", fileName);
|
||||
|
||||
return await CreateTransfer(content, "NZB file");
|
||||
}
|
||||
|
||||
private static String GetNzbFileName(String? name)
|
||||
{
|
||||
if (String.IsNullOrWhiteSpace(name))
|
||||
{
|
||||
return "upload.nzb";
|
||||
}
|
||||
|
||||
return name.EndsWith(".nzb", StringComparison.OrdinalIgnoreCase) ? name : $"{name}.nzb";
|
||||
}
|
||||
|
||||
private async Task<String> CreateTransfer(HttpContent content, String description)
|
||||
{
|
||||
try
|
||||
{
|
||||
using (content)
|
||||
{
|
||||
var httpClient = httpClientFactory.CreateClient();
|
||||
httpClient.Timeout = TimeSpan.FromSeconds(10);
|
||||
|
||||
using var request = new HttpRequestMessage(HttpMethod.Post, TransferCreateUrl)
|
||||
{
|
||||
Content = content
|
||||
};
|
||||
|
||||
request.Headers.Authorization = new("Bearer", GetApiKey());
|
||||
|
||||
using var response = await httpClient.SendAsync(request);
|
||||
var responseBody = await response.Content.ReadAsStringAsync();
|
||||
|
||||
if (response.StatusCode == HttpStatusCode.TooManyRequests)
|
||||
{
|
||||
var retryAfter = response.Headers.RetryAfter?.Delta ?? TimeSpan.FromMinutes(2);
|
||||
|
||||
throw new RateLimitException($"Unable to add {description}: Premiumize rate limit exceeded", retryAfter);
|
||||
}
|
||||
|
||||
if (!response.IsSuccessStatusCode)
|
||||
{
|
||||
throw new($"Unable to add {description}: Premiumize returned {(Int32)response.StatusCode} {response.ReasonPhrase}. {responseBody}");
|
||||
}
|
||||
|
||||
var result = JsonConvert.DeserializeObject<RawTransferCreateResponse>(responseBody) ?? throw new($"Unable to add {description}: invalid Premiumize response");
|
||||
|
||||
if (!String.Equals(result.Status, "success", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
var error = FormatPremiumizeError(result);
|
||||
|
||||
if (IsRateLimitMessage(error))
|
||||
{
|
||||
throw new RateLimitException(error, TimeSpan.FromMinutes(2));
|
||||
}
|
||||
|
||||
throw new($"Unable to add {description}: {error}");
|
||||
}
|
||||
|
||||
if (String.IsNullOrWhiteSpace(result.Id))
|
||||
{
|
||||
throw new($"Unable to add {description}: Premiumize did not return a transfer id");
|
||||
}
|
||||
|
||||
return result.Id;
|
||||
}
|
||||
}
|
||||
catch (RateLimitException)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
catch (Exception ex) when (IsRateLimitMessage(ex.Message))
|
||||
{
|
||||
throw new RateLimitException(ex.Message, TimeSpan.FromMinutes(2));
|
||||
}
|
||||
}
|
||||
|
||||
private static String FormatPremiumizeError(RawTransferCreateResponse result)
|
||||
{
|
||||
return String.Join(": ",
|
||||
new[]
|
||||
{
|
||||
result.Code, result.Message
|
||||
}.Where(m => !String.IsNullOrWhiteSpace(m)));
|
||||
}
|
||||
|
||||
private static Boolean IsRateLimitMessage(String message)
|
||||
{
|
||||
return message.Contains("slow_down", StringComparison.OrdinalIgnoreCase) ||
|
||||
message.Contains("rate limit exceeded", StringComparison.OrdinalIgnoreCase) ||
|
||||
message.Contains("rate_limit_reached", StringComparison.OrdinalIgnoreCase) ||
|
||||
message.Contains("account_limit_reached", StringComparison.OrdinalIgnoreCase) ||
|
||||
message.Contains("service_limit_reached", StringComparison.OrdinalIgnoreCase) ||
|
||||
message.Contains("service_down", StringComparison.OrdinalIgnoreCase) ||
|
||||
message.Contains("semi_permanent_error", StringComparison.OrdinalIgnoreCase) ||
|
||||
message.Contains("too many API requests", StringComparison.OrdinalIgnoreCase) ||
|
||||
message.Contains("fair-use points", StringComparison.OrdinalIgnoreCase) ||
|
||||
message.Contains("booster points", StringComparison.OrdinalIgnoreCase) ||
|
||||
message.Contains("active-job count", StringComparison.OrdinalIgnoreCase) ||
|
||||
message.Contains("usage limit for this service", StringComparison.OrdinalIgnoreCase) ||
|
||||
message.Contains("target service is unreachable", StringComparison.OrdinalIgnoreCase) ||
|
||||
message.Contains("retry after a delay", StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
private static DebridClientTorrent Map(Transfer transfer)
|
||||
{
|
||||
return new()
|
||||
|
|
@ -467,19 +363,4 @@ public class PremiumizeDebridClient(ILogger<PremiumizeDebridClient> logger, IHtt
|
|||
|
||||
logger.LogDebug(message);
|
||||
}
|
||||
|
||||
private class RawTransferCreateResponse
|
||||
{
|
||||
[JsonProperty("status")]
|
||||
public String? Status { get; set; }
|
||||
|
||||
[JsonProperty("id")]
|
||||
public String? Id { get; set; }
|
||||
|
||||
[JsonProperty("message")]
|
||||
public String? Message { get; set; }
|
||||
|
||||
[JsonProperty("code")]
|
||||
public String? Code { get; set; }
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -12,8 +12,7 @@ using Torrent = RDNET.Torrent;
|
|||
|
||||
namespace RdtClient.Service.Services.DebridClients;
|
||||
|
||||
public class RealDebridDebridClient(ILogger<RealDebridDebridClient> logger, IHttpClientFactory httpClientFactory, IDownloadableFileFilter fileFilter, ISettings settings)
|
||||
: IDebridClient
|
||||
public class RealDebridDebridClient(ILogger<RealDebridDebridClient> logger, IHttpClientFactory httpClientFactory, IDownloadableFileFilter fileFilter) : IDebridClient
|
||||
{
|
||||
private TimeSpan? _offset;
|
||||
|
||||
|
|
@ -54,7 +53,7 @@ public class RealDebridDebridClient(ILogger<RealDebridDebridClient> logger, IHtt
|
|||
{
|
||||
try
|
||||
{
|
||||
var timeoutCancellationToken = new CancellationTokenSource(TimeSpan.FromSeconds(settings.Current.Provider.Timeout));
|
||||
var timeoutCancellationToken = new CancellationTokenSource(TimeSpan.FromSeconds(Settings.Get.Provider.Timeout));
|
||||
|
||||
var result = await GetClient().Torrents.AddMagnetAsync(magnetLink, timeoutCancellationToken.Token);
|
||||
|
||||
|
|
@ -71,7 +70,7 @@ public class RealDebridDebridClient(ILogger<RealDebridDebridClient> logger, IHtt
|
|||
{
|
||||
try
|
||||
{
|
||||
var timeoutCancellationToken = new CancellationTokenSource(TimeSpan.FromSeconds(settings.Current.Provider.Timeout));
|
||||
var timeoutCancellationToken = new CancellationTokenSource(TimeSpan.FromSeconds(Settings.Get.Provider.Timeout));
|
||||
|
||||
var result = await GetClient().Torrents.AddFileAsync(bytes, timeoutCancellationToken.Token);
|
||||
|
||||
|
|
@ -315,7 +314,7 @@ public class RealDebridDebridClient(ILogger<RealDebridDebridClient> logger, IHtt
|
|||
{
|
||||
try
|
||||
{
|
||||
var apiKey = settings.Current.Provider.ApiKey;
|
||||
var apiKey = Settings.Get.Provider.ApiKey;
|
||||
|
||||
if (String.IsNullOrWhiteSpace(apiKey))
|
||||
{
|
||||
|
|
@ -323,9 +322,9 @@ public class RealDebridDebridClient(ILogger<RealDebridDebridClient> logger, IHtt
|
|||
}
|
||||
|
||||
var httpClient = httpClientFactory.CreateClient(DiConfig.RD_CLIENT);
|
||||
httpClient.Timeout = TimeSpan.FromSeconds(settings.Current.Provider.Timeout);
|
||||
httpClient.Timeout = TimeSpan.FromSeconds(Settings.Get.Provider.Timeout);
|
||||
|
||||
var rdtNetClient = new RdNetClient(null, httpClient, 5, settings.Current.Provider.ApiHostname);
|
||||
var rdtNetClient = new RdNetClient(null, httpClient, 5, Settings.Get.Provider.ApiHostname);
|
||||
rdtNetClient.UseApiAuthentication(apiKey);
|
||||
|
||||
// Get the server time to fix up the timezones on results
|
||||
|
|
|
|||
|
|
@ -11,12 +11,7 @@ using Torrent = RdtClient.Data.Models.Data.Torrent;
|
|||
|
||||
namespace RdtClient.Service.Services.DebridClients;
|
||||
|
||||
public class TorBoxDebridClient(
|
||||
ILogger<TorBoxDebridClient> logger,
|
||||
IHttpClientFactory httpClientFactory,
|
||||
IDownloadableFileFilter fileFilter,
|
||||
IRateLimitCoordinator coordinator,
|
||||
ISettings settings)
|
||||
public class TorBoxDebridClient(ILogger<TorBoxDebridClient> logger, IHttpClientFactory httpClientFactory, IDownloadableFileFilter fileFilter, IRateLimitCoordinator coordinator)
|
||||
: IDebridClient
|
||||
{
|
||||
private const String TorBoxApiHost = "api.torbox.app";
|
||||
|
|
@ -74,14 +69,9 @@ public class TorBoxDebridClient(
|
|||
return await HandleAddTorrentErrors(async asQueued =>
|
||||
{
|
||||
var user = await GetClient().User.GetAsync(true);
|
||||
var result = await GetClient(DiConfig.TORBOX_CLIENT_SLOW).Torrents.AddMagnetAsync(magnetLink, user.Data?.Settings?.SeedTorrents ?? 3, as_queued: asQueued);
|
||||
|
||||
var result = await GetClient(DiConfig.TORBOX_CLIENT_SLOW)
|
||||
.Torrents.AddMagnetAsync(magnetLink,
|
||||
user.Data?.Settings?.SeedTorrents ?? 3,
|
||||
allowZip: Settings.Get.Provider.PreferZippedDownloads,
|
||||
as_queued: asQueued);
|
||||
|
||||
return result.Data?.TorrentId?.ToString() ?? throw new InvalidOperationException("TorBox API did not return torrent ID.");
|
||||
return result.Data!.Hash!;
|
||||
});
|
||||
}
|
||||
|
||||
|
|
@ -90,14 +80,9 @@ public class TorBoxDebridClient(
|
|||
return await HandleAddTorrentErrors(async asQueued =>
|
||||
{
|
||||
var user = await GetClient().User.GetAsync(true);
|
||||
var result = await GetClient(DiConfig.TORBOX_CLIENT_SLOW).Torrents.AddFileAsync(bytes, user.Data?.Settings?.SeedTorrents ?? 3, as_queued: asQueued);
|
||||
|
||||
var result = await GetClient(DiConfig.TORBOX_CLIENT_SLOW)
|
||||
.Torrents.AddFileAsync(bytes,
|
||||
user.Data?.Settings?.SeedTorrents ?? 3,
|
||||
allowZip: Settings.Get.Provider.PreferZippedDownloads,
|
||||
as_queued: asQueued);
|
||||
|
||||
return result.Data?.TorrentId?.ToString() ?? throw new InvalidOperationException("TorBox API did not return torrent ID");
|
||||
return result.Data!.Hash!;
|
||||
});
|
||||
}
|
||||
|
||||
|
|
@ -171,7 +156,7 @@ public class TorBoxDebridClient(
|
|||
}
|
||||
else
|
||||
{
|
||||
await GetClient().Torrents.ControlByIdAsync(Int32.Parse(torrent.RdId), "delete");
|
||||
await GetClient().Torrents.ControlAsync(torrent.RdId, "delete");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
|
@ -331,12 +316,8 @@ public class TorBoxDebridClient(
|
|||
}
|
||||
else
|
||||
{
|
||||
if (torrent.RdId == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
id = Int32.Parse(torrent.RdId);
|
||||
var torrentId = await HandleErrors(() => GetClient().Torrents.GetHashInfoAsync(torrent.Hash, true));
|
||||
id = torrentId?.Id;
|
||||
}
|
||||
|
||||
if (id == null)
|
||||
|
|
@ -346,7 +327,7 @@ public class TorBoxDebridClient(
|
|||
|
||||
var downloadableFiles = torrent.Files.Where(file => fileFilter.IsDownloadable(torrent, file.Path, file.Bytes)).ToList();
|
||||
|
||||
if (downloadableFiles.Count == torrent.Files.Count && torrent.DownloadClient != Data.Enums.DownloadClient.Symlink && settings.Current.Provider.PreferZippedDownloads)
|
||||
if (downloadableFiles.Count == torrent.Files.Count && torrent.DownloadClient != Data.Enums.DownloadClient.Symlink && Settings.Get.Provider.PreferZippedDownloads)
|
||||
{
|
||||
logger.LogDebug("Downloading files from TorBox as a zip.");
|
||||
|
||||
|
|
@ -383,7 +364,7 @@ public class TorBoxDebridClient(
|
|||
{
|
||||
try
|
||||
{
|
||||
var apiKey = settings.Current.Provider.ApiKey;
|
||||
var apiKey = Settings.Get.Provider.ApiKey;
|
||||
|
||||
if (String.IsNullOrWhiteSpace(apiKey))
|
||||
{
|
||||
|
|
@ -391,7 +372,7 @@ public class TorBoxDebridClient(
|
|||
}
|
||||
|
||||
var httpClient = httpClientFactory.CreateClient(clientId);
|
||||
var torBoxNetClient = new TorBoxNetClient(null, httpClient, retryCount: 5);
|
||||
var torBoxNetClient = new TorBoxNetClient(null, httpClient);
|
||||
torBoxNetClient.UseApiAuthentication(apiKey);
|
||||
|
||||
// Get the server time to fix up the timezones on results
|
||||
|
|
@ -460,7 +441,7 @@ public class TorBoxDebridClient(
|
|||
{
|
||||
return new()
|
||||
{
|
||||
Id = torrent.Id.ToString(),
|
||||
Id = torrent.Hash,
|
||||
Filename = torrent.Name,
|
||||
OriginalFilename = torrent.Name,
|
||||
Hash = torrent.Hash,
|
||||
|
|
@ -532,7 +513,7 @@ public class TorBoxDebridClient(
|
|||
{
|
||||
throw rateLimitException;
|
||||
}
|
||||
catch (TorBoxException ex) when (IsRateLimit(ex))
|
||||
catch (TorBoxException ex) when ("active_limit".Equals(ex.Error, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
coordinator.UpdateCooldown(TorBoxApiHost, TimeSpan.FromMinutes(2));
|
||||
|
||||
|
|
@ -560,7 +541,7 @@ public class TorBoxDebridClient(
|
|||
{
|
||||
throw rateLimitException;
|
||||
}
|
||||
catch (TorBoxException ex) when (IsRateLimit(ex))
|
||||
catch (TorBoxException ex) when ("active_limit".Equals(ex.Error, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
coordinator.UpdateCooldown(TorBoxApiHost, TimeSpan.FromMinutes(2));
|
||||
|
||||
|
|
@ -579,12 +560,6 @@ public class TorBoxDebridClient(
|
|||
return await HandleErrors(() => action(false));
|
||||
}
|
||||
|
||||
private static Boolean IsRateLimit(TorBoxException exception)
|
||||
{
|
||||
return exception.Error.Equals("RATE_LIMIT", StringComparison.OrdinalIgnoreCase)
|
||||
|| exception.Error.Equals("ACTIVE_LIMIT", StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
private async Task<String> HandleAddUsenetErrors(Func<Boolean, Task<String>> action)
|
||||
{
|
||||
return await HandleErrors(() => action(false));
|
||||
|
|
@ -615,7 +590,7 @@ public class TorBoxDebridClient(
|
|||
}
|
||||
else
|
||||
{
|
||||
var result = await GetClient().Torrents.GetIdInfoAsync(Int32.Parse(id), true);
|
||||
var result = await GetClient().Torrents.GetHashInfoAsync(id, true);
|
||||
|
||||
if (result != null)
|
||||
{
|
||||
|
|
|
|||
|
|
@ -86,8 +86,8 @@ public class Downloads(DownloadData downloadData) : IDownloads
|
|||
await downloadData.DeleteForTorrent(torrentId);
|
||||
}
|
||||
|
||||
public async Task Reset(Guid downloadId, DateTimeOffset? downloadQueued = null)
|
||||
public async Task Reset(Guid downloadId)
|
||||
{
|
||||
await downloadData.Reset(downloadId, downloadQueued);
|
||||
await downloadData.Reset(downloadId);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -21,5 +21,5 @@ public interface IDownloads
|
|||
Task UpdateRetryCount(Guid downloadId, Int32 retryCount);
|
||||
Task UpdateRemoteId(Guid downloadId, String remoteId);
|
||||
Task DeleteForTorrent(Guid torrentId);
|
||||
Task Reset(Guid downloadId, DateTimeOffset? downloadQueued = null);
|
||||
Task Reset(Guid downloadId);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@ using RdtClient.Data.Models.QBittorrent;
|
|||
|
||||
namespace RdtClient.Service.Services;
|
||||
|
||||
public class QBittorrent(ILogger<QBittorrent> logger, ISettings settings, Authentication authentication, Torrents torrents, Downloads downloads, ITorrentRunnerState runnerState)
|
||||
public class QBittorrent(ILogger<QBittorrent> logger, Settings settings, Authentication authentication, Torrents torrents, Downloads downloads)
|
||||
{
|
||||
public async Task<Boolean> AuthLogin(String userName, String password)
|
||||
{
|
||||
|
|
@ -168,7 +168,7 @@ public class QBittorrent(ILogger<QBittorrent> logger, ISettings settings, Authen
|
|||
WebUiUsername = ""
|
||||
};
|
||||
|
||||
var savePath = settings.DefaultSavePath;
|
||||
var savePath = Settings.AppDefaultSavePath;
|
||||
|
||||
preferences.SavePath = savePath;
|
||||
preferences.TempPath = $"{savePath}temp{Path.DirectorySeparatorChar}";
|
||||
|
|
@ -185,7 +185,7 @@ public class QBittorrent(ILogger<QBittorrent> logger, ISettings settings, Authen
|
|||
|
||||
public virtual async Task<IList<TorrentInfo>> TorrentInfo()
|
||||
{
|
||||
var savePath = settings.DefaultSavePath;
|
||||
var savePath = Settings.AppDefaultSavePath;
|
||||
|
||||
var results = new List<TorrentInfo>();
|
||||
|
||||
|
|
@ -214,17 +214,7 @@ public class QBittorrent(ILogger<QBittorrent> logger, ISettings settings, Authen
|
|||
}
|
||||
else
|
||||
{
|
||||
var existingContentPath = GetExistingContentPath(downloadPath, torrent);
|
||||
|
||||
if (!String.IsNullOrWhiteSpace(existingContentPath))
|
||||
{
|
||||
torrentPath = existingContentPath;
|
||||
}
|
||||
else
|
||||
{
|
||||
var contentPathName = GetContentPathName(torrent);
|
||||
torrentPath = Path.Combine(downloadPath, contentPathName) + Path.DirectorySeparatorChar;
|
||||
}
|
||||
torrentPath = Path.Combine(downloadPath, torrent.RdName) + Path.DirectorySeparatorChar;
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -338,162 +328,6 @@ public class QBittorrent(ILogger<QBittorrent> logger, ISettings settings, Authen
|
|||
return results;
|
||||
}
|
||||
|
||||
private static String GetContentPathName(Torrent torrent)
|
||||
{
|
||||
if (String.IsNullOrWhiteSpace(torrent.RdName))
|
||||
{
|
||||
return torrent.RdName ?? String.Empty;
|
||||
}
|
||||
|
||||
var topLevelSelectedFiles = torrent.Files
|
||||
.Where(m => m.Selected && !String.IsNullOrWhiteSpace(m.Path))
|
||||
.Select(m => m.Path.Trim('/').Trim('\\'))
|
||||
.Where(m => m.IndexOfAny(['/', '\\']) < 0)
|
||||
.Select(Path.GetFileName)
|
||||
.Where(m => !String.IsNullOrWhiteSpace(m))
|
||||
.Distinct(StringComparer.OrdinalIgnoreCase)
|
||||
.ToList();
|
||||
|
||||
if (topLevelSelectedFiles.Count == 1)
|
||||
{
|
||||
var selectedFileName = topLevelSelectedFiles[0]!;
|
||||
var selectedFileBaseName = Path.GetFileNameWithoutExtension(selectedFileName);
|
||||
|
||||
if (torrent.ClientKind == Provider.TorBox)
|
||||
{
|
||||
return selectedFileBaseName;
|
||||
}
|
||||
|
||||
if (!String.IsNullOrWhiteSpace(selectedFileBaseName) &&
|
||||
selectedFileBaseName.Equals(torrent.RdName, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return selectedFileName;
|
||||
}
|
||||
}
|
||||
|
||||
return torrent.RdName;
|
||||
}
|
||||
|
||||
private static String? GetExistingContentPath(String downloadPath, Torrent torrent)
|
||||
{
|
||||
if (!torrent.Completed.HasValue || !Directory.Exists(downloadPath))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var selectedFilePaths = torrent.Files
|
||||
.Where(m => m.Selected && !String.IsNullOrWhiteSpace(m.Path))
|
||||
.Select(m => NormalizeRelativePath(m.Path!))
|
||||
.Where(m => !String.IsNullOrWhiteSpace(m))
|
||||
.Distinct(StringComparer.OrdinalIgnoreCase)
|
||||
.ToList();
|
||||
|
||||
var downloadFileNames = torrent.Downloads
|
||||
.Select(m => m.FileName)
|
||||
.Where(m => !String.IsNullOrWhiteSpace(m))
|
||||
.Select(m => Path.GetFileName(m!))
|
||||
.Where(m => !String.IsNullOrWhiteSpace(m))
|
||||
.Distinct(StringComparer.OrdinalIgnoreCase)
|
||||
.ToList();
|
||||
|
||||
if (selectedFilePaths.Count == 0 && downloadFileNames.Count == 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
foreach (var candidateRoot in GetCandidateContentRoots(downloadPath, torrent, selectedFilePaths, downloadFileNames))
|
||||
{
|
||||
if (IsMatchingContentRoot(candidateRoot, selectedFilePaths, downloadFileNames))
|
||||
{
|
||||
return candidateRoot + Path.DirectorySeparatorChar;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private static IEnumerable<String> GetCandidateContentRoots(String downloadPath,
|
||||
Torrent torrent,
|
||||
IEnumerable<String> selectedFilePaths,
|
||||
IEnumerable<String> downloadFileNames)
|
||||
{
|
||||
var yielded = new HashSet<String>(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
void AddCandidate(ICollection<String> candidates, String? name)
|
||||
{
|
||||
if (!String.IsNullOrWhiteSpace(name))
|
||||
{
|
||||
candidates.Add(Path.Combine(downloadPath, name));
|
||||
}
|
||||
}
|
||||
|
||||
var directCandidates = new List<String>();
|
||||
|
||||
AddCandidate(directCandidates, torrent.RdName);
|
||||
|
||||
foreach (var fileName in downloadFileNames)
|
||||
{
|
||||
AddCandidate(directCandidates, fileName);
|
||||
}
|
||||
|
||||
foreach (var selectedFilePath in selectedFilePaths)
|
||||
{
|
||||
AddCandidate(directCandidates, Path.GetFileName(selectedFilePath));
|
||||
AddCandidate(directCandidates, GetFirstPathComponent(selectedFilePath));
|
||||
}
|
||||
|
||||
foreach (var candidate in directCandidates)
|
||||
{
|
||||
if (Directory.Exists(candidate) && yielded.Add(candidate))
|
||||
{
|
||||
yield return candidate;
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var directory in Directory.EnumerateDirectories(downloadPath))
|
||||
{
|
||||
if (yielded.Add(directory))
|
||||
{
|
||||
yield return directory;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static Boolean IsMatchingContentRoot(String candidateRoot,
|
||||
IEnumerable<String> selectedFilePaths,
|
||||
IEnumerable<String> downloadFileNames)
|
||||
{
|
||||
foreach (var selectedFilePath in selectedFilePaths)
|
||||
{
|
||||
if (File.Exists(Path.Combine(candidateRoot, selectedFilePath)))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var fileName in downloadFileNames)
|
||||
{
|
||||
if (File.Exists(Path.Combine(candidateRoot, fileName)))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private static String NormalizeRelativePath(String path)
|
||||
{
|
||||
return path.Trim('/').Trim('\\').Replace('\\', Path.DirectorySeparatorChar);
|
||||
}
|
||||
|
||||
private static String GetFirstPathComponent(String path)
|
||||
{
|
||||
var separatorIndex = path.IndexOfAny(['/', '\\']);
|
||||
|
||||
return separatorIndex < 0 ? path : path[..separatorIndex];
|
||||
}
|
||||
|
||||
public async Task<IList<TorrentFileItem>?> TorrentFileContents(String hash)
|
||||
{
|
||||
var torrent = await torrents.GetByHash(hash);
|
||||
|
|
@ -506,21 +340,21 @@ public class QBittorrent(ILogger<QBittorrent> logger, ISettings settings, Authen
|
|||
var progress = torrent.Completed.HasValue || torrent.RdStatus == TorrentStatus.Finished ? 1f : 0f;
|
||||
|
||||
return torrent.Files
|
||||
.Select((file, index) => new TorrentFileItem
|
||||
{
|
||||
Index = index,
|
||||
Name = file.Path,
|
||||
Size = file.Bytes,
|
||||
Progress = file.Selected ? progress : 0f,
|
||||
Priority = file.Selected ? 1 : 0,
|
||||
IsSeed = false
|
||||
})
|
||||
.ToList();
|
||||
.Select((file, index) => new TorrentFileItem
|
||||
{
|
||||
Index = index,
|
||||
Name = file.Path,
|
||||
Size = file.Bytes,
|
||||
Progress = file.Selected ? progress : 0f,
|
||||
Priority = file.Selected ? 1 : 0,
|
||||
IsSeed = false
|
||||
})
|
||||
.ToList();
|
||||
}
|
||||
|
||||
public async Task<TorrentProperties?> TorrentProperties(String hash)
|
||||
{
|
||||
var savePath = settings.DefaultSavePath;
|
||||
var savePath = Settings.AppDefaultSavePath;
|
||||
|
||||
var torrent = await torrents.GetByHash(hash);
|
||||
|
||||
|
|
@ -610,7 +444,7 @@ public class QBittorrent(ILogger<QBittorrent> logger, ISettings settings, Authen
|
|||
return;
|
||||
}
|
||||
|
||||
switch (settings.Current.Integrations.Default.FinishedAction)
|
||||
switch (Settings.Get.Integrations.Default.FinishedAction)
|
||||
{
|
||||
case TorrentFinishedAction.RemoveAllTorrents:
|
||||
logger.LogDebug("Removing torrents from debrid provider and RDT-Client, no files");
|
||||
|
|
@ -638,54 +472,54 @@ public class QBittorrent(ILogger<QBittorrent> logger, ISettings settings, Authen
|
|||
}
|
||||
}
|
||||
|
||||
public async Task<Torrent> TorrentsAddMagnet(String magnetLink, String? category, Int32? priority)
|
||||
public async Task TorrentsAddMagnet(String magnetLink, String? category, Int32? priority)
|
||||
{
|
||||
logger.LogDebug($"Add magnet {category}");
|
||||
|
||||
var torrent = new Torrent
|
||||
{
|
||||
Category = category,
|
||||
DownloadClient = settings.Current.DownloadClient.Client,
|
||||
HostDownloadAction = settings.Current.Integrations.Default.HostDownloadAction,
|
||||
FinishedActionDelay = settings.Current.Integrations.Default.FinishedActionDelay,
|
||||
DownloadAction = settings.Current.Integrations.Default.OnlyDownloadAvailableFiles ? TorrentDownloadAction.DownloadAvailableFiles : TorrentDownloadAction.DownloadAll,
|
||||
DownloadClient = Settings.Get.DownloadClient.Client,
|
||||
HostDownloadAction = Settings.Get.Integrations.Default.HostDownloadAction,
|
||||
FinishedActionDelay = Settings.Get.Integrations.Default.FinishedActionDelay,
|
||||
DownloadAction = Settings.Get.Integrations.Default.OnlyDownloadAvailableFiles ? TorrentDownloadAction.DownloadAvailableFiles : TorrentDownloadAction.DownloadAll,
|
||||
FinishedAction = TorrentFinishedAction.None,
|
||||
DownloadMinSize = settings.Current.Integrations.Default.MinFileSize,
|
||||
IncludeRegex = settings.Current.Integrations.Default.IncludeRegex,
|
||||
ExcludeRegex = settings.Current.Integrations.Default.ExcludeRegex,
|
||||
TorrentRetryAttempts = settings.Current.Integrations.Default.TorrentRetryAttempts,
|
||||
DownloadRetryAttempts = settings.Current.Integrations.Default.DownloadRetryAttempts,
|
||||
DeleteOnError = settings.Current.Integrations.Default.DeleteOnError,
|
||||
Lifetime = settings.Current.Integrations.Default.TorrentLifetime,
|
||||
Priority = priority ?? (settings.Current.Integrations.Default.Priority > 0 ? settings.Current.Integrations.Default.Priority : null)
|
||||
DownloadMinSize = Settings.Get.Integrations.Default.MinFileSize,
|
||||
IncludeRegex = Settings.Get.Integrations.Default.IncludeRegex,
|
||||
ExcludeRegex = Settings.Get.Integrations.Default.ExcludeRegex,
|
||||
TorrentRetryAttempts = Settings.Get.Integrations.Default.TorrentRetryAttempts,
|
||||
DownloadRetryAttempts = Settings.Get.Integrations.Default.DownloadRetryAttempts,
|
||||
DeleteOnError = Settings.Get.Integrations.Default.DeleteOnError,
|
||||
Lifetime = Settings.Get.Integrations.Default.TorrentLifetime,
|
||||
Priority = priority ?? (Settings.Get.Integrations.Default.Priority > 0 ? Settings.Get.Integrations.Default.Priority : null)
|
||||
};
|
||||
|
||||
return await torrents.AddMagnetToDebridQueue(magnetLink, torrent);
|
||||
await torrents.AddMagnetToDebridQueue(magnetLink, torrent);
|
||||
}
|
||||
|
||||
public async Task<Torrent> TorrentsAddFile(Byte[] fileBytes, String? category, Int32? priority)
|
||||
public async Task TorrentsAddFile(Byte[] fileBytes, String? category, Int32? priority)
|
||||
{
|
||||
logger.LogDebug($"Add file {category}");
|
||||
|
||||
var torrent = new Torrent
|
||||
{
|
||||
Category = category,
|
||||
DownloadClient = settings.Current.DownloadClient.Client,
|
||||
HostDownloadAction = settings.Current.Integrations.Default.HostDownloadAction,
|
||||
FinishedActionDelay = settings.Current.Integrations.Default.FinishedActionDelay,
|
||||
DownloadAction = settings.Current.Integrations.Default.OnlyDownloadAvailableFiles ? TorrentDownloadAction.DownloadAvailableFiles : TorrentDownloadAction.DownloadAll,
|
||||
DownloadClient = Settings.Get.DownloadClient.Client,
|
||||
HostDownloadAction = Settings.Get.Integrations.Default.HostDownloadAction,
|
||||
FinishedActionDelay = Settings.Get.Integrations.Default.FinishedActionDelay,
|
||||
DownloadAction = Settings.Get.Integrations.Default.OnlyDownloadAvailableFiles ? TorrentDownloadAction.DownloadAvailableFiles : TorrentDownloadAction.DownloadAll,
|
||||
FinishedAction = TorrentFinishedAction.None,
|
||||
DownloadMinSize = settings.Current.Integrations.Default.MinFileSize,
|
||||
IncludeRegex = settings.Current.Integrations.Default.IncludeRegex,
|
||||
ExcludeRegex = settings.Current.Integrations.Default.ExcludeRegex,
|
||||
TorrentRetryAttempts = settings.Current.Integrations.Default.TorrentRetryAttempts,
|
||||
DownloadRetryAttempts = settings.Current.Integrations.Default.DownloadRetryAttempts,
|
||||
DeleteOnError = settings.Current.Integrations.Default.DeleteOnError,
|
||||
Lifetime = settings.Current.Integrations.Default.TorrentLifetime,
|
||||
Priority = priority ?? (settings.Current.Integrations.Default.Priority > 0 ? settings.Current.Integrations.Default.Priority : null)
|
||||
DownloadMinSize = Settings.Get.Integrations.Default.MinFileSize,
|
||||
IncludeRegex = Settings.Get.Integrations.Default.IncludeRegex,
|
||||
ExcludeRegex = Settings.Get.Integrations.Default.ExcludeRegex,
|
||||
TorrentRetryAttempts = Settings.Get.Integrations.Default.TorrentRetryAttempts,
|
||||
DownloadRetryAttempts = Settings.Get.Integrations.Default.DownloadRetryAttempts,
|
||||
DeleteOnError = Settings.Get.Integrations.Default.DeleteOnError,
|
||||
Lifetime = Settings.Get.Integrations.Default.TorrentLifetime,
|
||||
Priority = priority ?? (Settings.Get.Integrations.Default.Priority > 0 ? Settings.Get.Integrations.Default.Priority : null)
|
||||
};
|
||||
|
||||
return await torrents.AddFileToDebridQueue(fileBytes, torrent);
|
||||
await torrents.AddFileToDebridQueue(fileBytes, torrent);
|
||||
}
|
||||
|
||||
public async Task TorrentsSetCategory(String hash, String? category)
|
||||
|
|
@ -701,7 +535,7 @@ public class QBittorrent(ILogger<QBittorrent> logger, ISettings settings, Authen
|
|||
.Select(m => m.Category!.ToLower())
|
||||
.ToList();
|
||||
|
||||
var categoryList = (settings.Current.General.Categories ?? "")
|
||||
var categoryList = (Settings.Get.General.Categories ?? "")
|
||||
.Split(",", StringSplitOptions.RemoveEmptyEntries)
|
||||
.Distinct(StringComparer.CurrentCultureIgnoreCase)
|
||||
.Select(m => m.Trim())
|
||||
|
|
@ -718,7 +552,7 @@ public class QBittorrent(ILogger<QBittorrent> logger, ISettings settings, Authen
|
|||
m => new TorrentCategory
|
||||
{
|
||||
Name = m,
|
||||
SavePath = Path.Combine(settings.DefaultSavePath, m)
|
||||
SavePath = Path.Combine(Settings.AppDefaultSavePath, m)
|
||||
});
|
||||
}
|
||||
|
||||
|
|
@ -734,7 +568,7 @@ public class QBittorrent(ILogger<QBittorrent> logger, ISettings settings, Authen
|
|||
|
||||
category = category.Trim();
|
||||
|
||||
var categoriesSetting = settings.Current.General.Categories;
|
||||
var categoriesSetting = Settings.Get.General.Categories;
|
||||
|
||||
var categoryList = (categoriesSetting ?? "")
|
||||
.Split(",", StringSplitOptions.RemoveEmptyEntries)
|
||||
|
|
@ -761,7 +595,7 @@ public class QBittorrent(ILogger<QBittorrent> logger, ISettings settings, Authen
|
|||
|
||||
category = category.Trim();
|
||||
|
||||
var categoriesSetting = settings.Current.General.Categories;
|
||||
var categoriesSetting = Settings.Get.General.Categories;
|
||||
|
||||
var categoryList = (categoriesSetting ?? "")
|
||||
.Split(",", StringSplitOptions.RemoveEmptyEntries)
|
||||
|
|
@ -801,7 +635,7 @@ public class QBittorrent(ILogger<QBittorrent> logger, ISettings settings, Authen
|
|||
|
||||
foreach (var download in downloadsForTorrent)
|
||||
{
|
||||
if (runnerState.ActiveDownloadClients.TryGetValue(download.DownloadId, out var downloadClient))
|
||||
if (TorrentRunner.ActiveDownloadClients.TryGetValue(download.DownloadId, out var downloadClient))
|
||||
{
|
||||
await downloadClient.Pause();
|
||||
}
|
||||
|
|
@ -821,7 +655,7 @@ public class QBittorrent(ILogger<QBittorrent> logger, ISettings settings, Authen
|
|||
|
||||
foreach (var download in downloadsForTorrent)
|
||||
{
|
||||
if (runnerState.ActiveDownloadClients.TryGetValue(download.DownloadId, out var downloadClient))
|
||||
if (TorrentRunner.ActiveDownloadClients.TryGetValue(download.DownloadId, out var downloadClient))
|
||||
{
|
||||
await downloadClient.Resume();
|
||||
}
|
||||
|
|
@ -834,7 +668,7 @@ public class QBittorrent(ILogger<QBittorrent> logger, ISettings settings, Authen
|
|||
|
||||
var categories = await TorrentsCategories();
|
||||
|
||||
var activeDownloads = runnerState.ActiveDownloadClients.Sum(m => m.Value.Speed);
|
||||
var activeDownloads = TorrentRunner.ActiveDownloadClients.Sum(m => m.Value.Speed);
|
||||
|
||||
return new()
|
||||
{
|
||||
|
|
@ -852,16 +686,16 @@ public class QBittorrent(ILogger<QBittorrent> logger, ISettings settings, Authen
|
|||
};
|
||||
}
|
||||
|
||||
public virtual TransferInfo TransferInfo()
|
||||
public static TransferInfo TransferInfo()
|
||||
{
|
||||
var activeDownloads = runnerState.ActiveDownloadClients.Sum(m => m.Value.Speed);
|
||||
var activeDownloads = TorrentRunner.ActiveDownloadClients.Sum(m => m.Value.Speed);
|
||||
|
||||
return new()
|
||||
{
|
||||
ConnectionStatus = "connected",
|
||||
DlInfoData = DownloadClient.GetTotalBytesDownloadedThisSession(),
|
||||
DlInfoSpeed = activeDownloads,
|
||||
DlRateLimit = settings.Current.DownloadClient.MaxSpeed
|
||||
DlRateLimit = Settings.Get.DownloadClient.MaxSpeed
|
||||
};
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -7,7 +7,7 @@ using RdtClient.Service.Helpers;
|
|||
|
||||
namespace RdtClient.Service.Services;
|
||||
|
||||
public class Sabnzbd(ILogger<Sabnzbd> logger, Torrents torrents, AppSettings appSettings, ISettings settings)
|
||||
public class Sabnzbd(ILogger<Sabnzbd> logger, Torrents torrents, AppSettings appSettings)
|
||||
{
|
||||
public virtual async Task<SabnzbdQueue> GetQueue()
|
||||
{
|
||||
|
|
@ -87,7 +87,7 @@ public class Sabnzbd(ILogger<Sabnzbd> logger, Torrents torrents, AppSettings app
|
|||
var allTorrents = await torrents.Get();
|
||||
var completedTorrents = allTorrents.Where(t => t.Type == DownloadType.Nzb && t.Completed != null).ToList();
|
||||
|
||||
var savePath = settings.DefaultSavePath;
|
||||
var savePath = Settings.AppDefaultSavePath;
|
||||
|
||||
var history = new SabnzbdHistory
|
||||
{
|
||||
|
|
@ -130,19 +130,19 @@ public class Sabnzbd(ILogger<Sabnzbd> logger, Torrents torrents, AppSettings app
|
|||
var torrent = new Torrent
|
||||
{
|
||||
Category = category,
|
||||
DownloadClient = settings.Current.DownloadClient.Client,
|
||||
HostDownloadAction = settings.Current.Integrations.Default.HostDownloadAction,
|
||||
FinishedActionDelay = settings.Current.Integrations.Default.FinishedActionDelay,
|
||||
DownloadAction = settings.Current.Integrations.Default.OnlyDownloadAvailableFiles ? TorrentDownloadAction.DownloadAvailableFiles : TorrentDownloadAction.DownloadAll,
|
||||
DownloadClient = Settings.Get.DownloadClient.Client,
|
||||
HostDownloadAction = Settings.Get.Integrations.Default.HostDownloadAction,
|
||||
FinishedActionDelay = Settings.Get.Integrations.Default.FinishedActionDelay,
|
||||
DownloadAction = Settings.Get.Integrations.Default.OnlyDownloadAvailableFiles ? TorrentDownloadAction.DownloadAvailableFiles : TorrentDownloadAction.DownloadAll,
|
||||
FinishedAction = TorrentFinishedAction.None,
|
||||
DownloadMinSize = settings.Current.Integrations.Default.MinFileSize,
|
||||
IncludeRegex = settings.Current.Integrations.Default.IncludeRegex,
|
||||
ExcludeRegex = settings.Current.Integrations.Default.ExcludeRegex,
|
||||
TorrentRetryAttempts = settings.Current.Integrations.Default.TorrentRetryAttempts,
|
||||
DownloadRetryAttempts = settings.Current.Integrations.Default.DownloadRetryAttempts,
|
||||
DeleteOnError = settings.Current.Integrations.Default.DeleteOnError,
|
||||
Lifetime = settings.Current.Integrations.Default.TorrentLifetime,
|
||||
Priority = (priority ?? settings.Current.Integrations.Default.Priority) > 0 ? 1 : null
|
||||
DownloadMinSize = Settings.Get.Integrations.Default.MinFileSize,
|
||||
IncludeRegex = Settings.Get.Integrations.Default.IncludeRegex,
|
||||
ExcludeRegex = Settings.Get.Integrations.Default.ExcludeRegex,
|
||||
TorrentRetryAttempts = Settings.Get.Integrations.Default.TorrentRetryAttempts,
|
||||
DownloadRetryAttempts = Settings.Get.Integrations.Default.DownloadRetryAttempts,
|
||||
DeleteOnError = Settings.Get.Integrations.Default.DeleteOnError,
|
||||
Lifetime = Settings.Get.Integrations.Default.TorrentLifetime,
|
||||
Priority = (priority ?? Settings.Get.Integrations.Default.Priority) > 0 ? 1 : null
|
||||
};
|
||||
|
||||
var result = await torrents.AddNzbFileToDebridQueue(fileBytes, fileName, torrent);
|
||||
|
|
@ -157,19 +157,19 @@ public class Sabnzbd(ILogger<Sabnzbd> logger, Torrents torrents, AppSettings app
|
|||
var torrent = new Torrent
|
||||
{
|
||||
Category = category,
|
||||
DownloadClient = settings.Current.DownloadClient.Client,
|
||||
HostDownloadAction = settings.Current.Integrations.Default.HostDownloadAction,
|
||||
FinishedActionDelay = settings.Current.Integrations.Default.FinishedActionDelay,
|
||||
DownloadAction = settings.Current.Integrations.Default.OnlyDownloadAvailableFiles ? TorrentDownloadAction.DownloadAvailableFiles : TorrentDownloadAction.DownloadAll,
|
||||
DownloadClient = Settings.Get.DownloadClient.Client,
|
||||
HostDownloadAction = Settings.Get.Integrations.Default.HostDownloadAction,
|
||||
FinishedActionDelay = Settings.Get.Integrations.Default.FinishedActionDelay,
|
||||
DownloadAction = Settings.Get.Integrations.Default.OnlyDownloadAvailableFiles ? TorrentDownloadAction.DownloadAvailableFiles : TorrentDownloadAction.DownloadAll,
|
||||
FinishedAction = TorrentFinishedAction.None,
|
||||
DownloadMinSize = settings.Current.Integrations.Default.MinFileSize,
|
||||
IncludeRegex = settings.Current.Integrations.Default.IncludeRegex,
|
||||
ExcludeRegex = settings.Current.Integrations.Default.ExcludeRegex,
|
||||
TorrentRetryAttempts = settings.Current.Integrations.Default.TorrentRetryAttempts,
|
||||
DownloadRetryAttempts = settings.Current.Integrations.Default.DownloadRetryAttempts,
|
||||
DeleteOnError = settings.Current.Integrations.Default.DeleteOnError,
|
||||
Lifetime = settings.Current.Integrations.Default.TorrentLifetime,
|
||||
Priority = priority ?? (settings.Current.Integrations.Default.Priority > 0 ? settings.Current.Integrations.Default.Priority : null)
|
||||
DownloadMinSize = Settings.Get.Integrations.Default.MinFileSize,
|
||||
IncludeRegex = Settings.Get.Integrations.Default.IncludeRegex,
|
||||
ExcludeRegex = Settings.Get.Integrations.Default.ExcludeRegex,
|
||||
TorrentRetryAttempts = Settings.Get.Integrations.Default.TorrentRetryAttempts,
|
||||
DownloadRetryAttempts = Settings.Get.Integrations.Default.DownloadRetryAttempts,
|
||||
DeleteOnError = Settings.Get.Integrations.Default.DeleteOnError,
|
||||
Lifetime = Settings.Get.Integrations.Default.TorrentLifetime,
|
||||
Priority = priority ?? (Settings.Get.Integrations.Default.Priority > 0 ? Settings.Get.Integrations.Default.Priority : null)
|
||||
};
|
||||
|
||||
var result = await torrents.AddNzbLinkToDebridQueue(url, torrent);
|
||||
|
|
@ -177,7 +177,7 @@ public class Sabnzbd(ILogger<Sabnzbd> logger, Torrents torrents, AppSettings app
|
|||
return result.Hash;
|
||||
}
|
||||
|
||||
public virtual async Task Delete(String hash, Boolean deleteFiles = false)
|
||||
public virtual async Task Delete(String hash)
|
||||
{
|
||||
var torrent = await torrents.GetByHash(hash);
|
||||
|
||||
|
|
@ -186,21 +186,21 @@ public class Sabnzbd(ILogger<Sabnzbd> logger, Torrents torrents, AppSettings app
|
|||
return;
|
||||
}
|
||||
|
||||
switch (settings.Current.Integrations.Default.FinishedAction)
|
||||
switch (Settings.Get.Integrations.Default.FinishedAction)
|
||||
{
|
||||
case TorrentFinishedAction.RemoveAllTorrents:
|
||||
logger.LogDebug("Removing nzb from debrid provider and RDT-Client, {Files}", deleteFiles ? "with files" : "no files");
|
||||
await torrents.Delete(torrent.TorrentId, true, true, deleteFiles);
|
||||
logger.LogDebug("Removing nzb from debrid provider and RDT-Client, no files");
|
||||
await torrents.Delete(torrent.TorrentId, true, true, true);
|
||||
|
||||
break;
|
||||
case TorrentFinishedAction.RemoveRealDebrid:
|
||||
logger.LogDebug("Removing nzb from debrid provider, {Files}", deleteFiles ? "with files" : "no files");
|
||||
await torrents.Delete(torrent.TorrentId, false, true, deleteFiles);
|
||||
logger.LogDebug("Removing nzb from debrid provider, no files");
|
||||
await torrents.Delete(torrent.TorrentId, false, true, true);
|
||||
|
||||
break;
|
||||
case TorrentFinishedAction.RemoveClient:
|
||||
logger.LogDebug("Removing nzb from client, {Files}", deleteFiles ? "with files" : "no files");
|
||||
await torrents.Delete(torrent.TorrentId, true, false, deleteFiles);
|
||||
logger.LogDebug("Removing nzb from client, no files");
|
||||
await torrents.Delete(torrent.TorrentId, true, false, true);
|
||||
|
||||
break;
|
||||
case TorrentFinishedAction.None:
|
||||
|
|
@ -216,7 +216,7 @@ public class Sabnzbd(ILogger<Sabnzbd> logger, Torrents torrents, AppSettings app
|
|||
|
||||
public virtual List<String> GetCategories()
|
||||
{
|
||||
var categoryList = (settings.Current.General.Categories ?? "")
|
||||
var categoryList = (Settings.Get.General.Categories ?? "")
|
||||
.Split(",", StringSplitOptions.RemoveEmptyEntries)
|
||||
.Select(m => m.Trim())
|
||||
.Where(m => m != "*")
|
||||
|
|
@ -230,7 +230,7 @@ public class Sabnzbd(ILogger<Sabnzbd> logger, Torrents torrents, AppSettings app
|
|||
|
||||
public virtual SabnzbdConfig GetConfig()
|
||||
{
|
||||
var savePath = settings.DefaultSavePath;
|
||||
var savePath = Settings.AppDefaultSavePath;
|
||||
|
||||
var categoryList = GetCategories();
|
||||
|
||||
|
|
|
|||
|
|
@ -1,88 +1,49 @@
|
|||
using RdtClient.Data.Data;
|
||||
using RdtClient.Data.Enums;
|
||||
using RdtClient.Data.Models.Internal;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Serilog.Core;
|
||||
using Serilog.Events;
|
||||
|
||||
namespace RdtClient.Service.Services;
|
||||
|
||||
public interface ISettings
|
||||
{
|
||||
DbSettings Current { get; }
|
||||
|
||||
String DefaultSavePath { get; }
|
||||
|
||||
IList<SettingProperty> GetAll();
|
||||
|
||||
Task Update(IList<SettingProperty> settings);
|
||||
|
||||
Task Update(String settingId, Object? value);
|
||||
}
|
||||
|
||||
public class Settings(IServiceScopeFactory serviceScopeFactory) : ISettings
|
||||
public class Settings(SettingData settingData)
|
||||
{
|
||||
public static readonly LoggingLevelSwitch LoggingLevelSwitch = new(LogEventLevel.Debug);
|
||||
|
||||
public static DbSettings Get => SettingData.Get;
|
||||
|
||||
public DbSettings Current => Get;
|
||||
|
||||
public static String AppDefaultSavePath => GetDefaultSavePath(Get);
|
||||
|
||||
public String DefaultSavePath => GetDefaultSavePath(Current);
|
||||
|
||||
public IList<SettingProperty> GetAll()
|
||||
public static String AppDefaultSavePath
|
||||
{
|
||||
return SettingData.GetAll();
|
||||
}
|
||||
|
||||
private static String GetDefaultSavePath(DbSettings settings)
|
||||
{
|
||||
var downloadPath = settings.DownloadClient.MappedPath;
|
||||
|
||||
if (String.IsNullOrWhiteSpace(downloadPath))
|
||||
get
|
||||
{
|
||||
downloadPath = settings.DownloadClient.DownloadPath;
|
||||
var downloadPath = Get.DownloadClient.MappedPath;
|
||||
|
||||
downloadPath = downloadPath.TrimEnd('\\')
|
||||
.TrimEnd('/');
|
||||
|
||||
downloadPath += Path.DirectorySeparatorChar;
|
||||
|
||||
return downloadPath;
|
||||
}
|
||||
|
||||
downloadPath = downloadPath.TrimEnd('\\')
|
||||
.TrimEnd('/');
|
||||
|
||||
downloadPath += Path.DirectorySeparatorChar;
|
||||
|
||||
return downloadPath;
|
||||
}
|
||||
|
||||
public async Task Update(IList<SettingProperty> settings)
|
||||
{
|
||||
using var scope = serviceScopeFactory.CreateScope();
|
||||
var settingData = scope.ServiceProvider.GetRequiredService<SettingData>();
|
||||
|
||||
await settingData.Update(settings);
|
||||
}
|
||||
|
||||
public async Task Update(String settingId, Object? value)
|
||||
{
|
||||
using var scope = serviceScopeFactory.CreateScope();
|
||||
var settingData = scope.ServiceProvider.GetRequiredService<SettingData>();
|
||||
|
||||
await settingData.Update(settingId, value);
|
||||
}
|
||||
|
||||
public async Task Seed()
|
||||
{
|
||||
using var scope = serviceScopeFactory.CreateScope();
|
||||
var settingData = scope.ServiceProvider.GetRequiredService<SettingData>();
|
||||
|
||||
await settingData.Seed();
|
||||
}
|
||||
|
||||
public async Task ResetCache()
|
||||
{
|
||||
using var scope = serviceScopeFactory.CreateScope();
|
||||
var settingData = scope.ServiceProvider.GetRequiredService<SettingData>();
|
||||
|
||||
await settingData.ResetCache();
|
||||
|
||||
LoggingLevelSwitch.MinimumLevel = Get.General.LogLevel switch
|
||||
|
|
|
|||
|
|
@ -17,34 +17,34 @@ public class TorrentRunner(
|
|||
Downloads downloads,
|
||||
RemoteService remoteService,
|
||||
IHttpClientFactory httpClientFactory,
|
||||
IRateLimitCoordinator coordinator,
|
||||
ISettings settings,
|
||||
ITorrentRunnerState runnerState)
|
||||
IRateLimitCoordinator coordinator)
|
||||
{
|
||||
public static readonly ITorrentRunnerState SharedState = new TorrentRunnerState();
|
||||
|
||||
public static ConcurrentDictionary<Guid, DownloadClient> ActiveDownloadClients => SharedState.ActiveDownloadClients;
|
||||
|
||||
public static ConcurrentDictionary<Guid, UnpackClient> ActiveUnpackClients => SharedState.ActiveUnpackClients;
|
||||
|
||||
public static readonly ConcurrentDictionary<Guid, DownloadClient> ActiveDownloadClients = new();
|
||||
public static readonly ConcurrentDictionary<Guid, UnpackClient> ActiveUnpackClients = new();
|
||||
private DateTimeOffset? _lastNextAllowedAt;
|
||||
|
||||
public static Boolean IsPausedForLowDiskSpace
|
||||
{
|
||||
get => SharedState.IsPausedForLowDiskSpace;
|
||||
set => SharedState.IsPausedForLowDiskSpace = value;
|
||||
}
|
||||
public static Boolean IsPausedForLowDiskSpace { get; set; }
|
||||
|
||||
public static (Int64 Speed, Int64 BytesTotal, Int64 BytesDone) GetStats(Guid downloadId)
|
||||
{
|
||||
return SharedState.GetStats(downloadId);
|
||||
if (ActiveDownloadClients.TryGetValue(downloadId, out var downloadClient))
|
||||
{
|
||||
return (downloadClient.Speed, downloadClient.BytesTotal, downloadClient.BytesDone);
|
||||
}
|
||||
|
||||
if (ActiveUnpackClients.TryGetValue(downloadId, out var unpackClient))
|
||||
{
|
||||
return (0, 100, unpackClient.Progess);
|
||||
}
|
||||
|
||||
return (0, 0, 0);
|
||||
}
|
||||
|
||||
public async Task Initialize()
|
||||
{
|
||||
Log("Initializing TorrentRunner");
|
||||
|
||||
var settingsCopy = JsonSerializer.Deserialize<DbSettings>(JsonSerializer.Serialize(settings.Current));
|
||||
var settingsCopy = JsonSerializer.Deserialize<DbSettings>(JsonSerializer.Serialize(Settings.Get));
|
||||
|
||||
if (settingsCopy != null)
|
||||
{
|
||||
|
|
@ -87,28 +87,28 @@ public class TorrentRunner(
|
|||
|
||||
public async Task Tick()
|
||||
{
|
||||
if (String.IsNullOrWhiteSpace(settings.Current.Provider.ApiKey))
|
||||
if (String.IsNullOrWhiteSpace(Settings.Get.Provider.ApiKey))
|
||||
{
|
||||
Log($"No RealDebridApiKey set in settings");
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
var settingDownloadLimit = settings.Current.General.DownloadLimit;
|
||||
var settingDownloadLimit = Settings.Get.General.DownloadLimit;
|
||||
|
||||
if (settingDownloadLimit < 1)
|
||||
{
|
||||
settingDownloadLimit = 1;
|
||||
}
|
||||
|
||||
var settingUnpackLimit = settings.Current.General.UnpackLimit;
|
||||
var settingUnpackLimit = Settings.Get.General.UnpackLimit;
|
||||
|
||||
if (settingUnpackLimit < 0)
|
||||
{
|
||||
settingUnpackLimit = 0;
|
||||
}
|
||||
|
||||
var settingDownloadPath = settings.Current.DownloadClient.DownloadPath;
|
||||
var settingDownloadPath = Settings.Get.DownloadClient.DownloadPath;
|
||||
|
||||
if (String.IsNullOrWhiteSpace(settingDownloadPath))
|
||||
{
|
||||
|
|
@ -141,25 +141,25 @@ public class TorrentRunner(
|
|||
_lastNextAllowedAt = currentNextAllowedAt;
|
||||
}
|
||||
|
||||
if (!runnerState.ActiveDownloadClients.IsEmpty || !runnerState.ActiveUnpackClients.IsEmpty)
|
||||
if (!ActiveDownloadClients.IsEmpty || !ActiveUnpackClients.IsEmpty)
|
||||
{
|
||||
Log($"TorrentRunner Tick Start, {runnerState.ActiveDownloadClients.Count} active downloads, {runnerState.ActiveUnpackClients.Count} active unpacks");
|
||||
Log($"TorrentRunner Tick Start, {ActiveDownloadClients.Count} active downloads, {ActiveUnpackClients.Count} active unpacks");
|
||||
}
|
||||
|
||||
if (runnerState.ActiveDownloadClients.Any(m => m.Value.Type == Data.Enums.DownloadClient.Aria2c))
|
||||
if (ActiveDownloadClients.Any(m => m.Value.Type == Data.Enums.DownloadClient.Aria2c))
|
||||
{
|
||||
Log("Updating Aria2 status");
|
||||
|
||||
var httpClient = httpClientFactory.CreateClient();
|
||||
httpClient.Timeout = TimeSpan.FromSeconds(10);
|
||||
|
||||
var aria2NetClient = new Aria2NetClient(settings.Current.DownloadClient.Aria2cUrl, settings.Current.DownloadClient.Aria2cSecret, httpClient, 1);
|
||||
var aria2NetClient = new Aria2NetClient(Settings.Get.DownloadClient.Aria2cUrl, Settings.Get.DownloadClient.Aria2cSecret, httpClient, 1);
|
||||
|
||||
var allDownloads = await aria2NetClient.TellAllAsync();
|
||||
|
||||
Log($"Found {allDownloads.Count} Aria2 downloads");
|
||||
|
||||
foreach (var activeDownload in runnerState.ActiveDownloadClients)
|
||||
foreach (var activeDownload in ActiveDownloadClients)
|
||||
{
|
||||
if (activeDownload.Value.Downloader is Aria2cDownloader aria2Downloader)
|
||||
{
|
||||
|
|
@ -170,11 +170,11 @@ public class TorrentRunner(
|
|||
Log("Finished updating Aria2 status");
|
||||
}
|
||||
|
||||
if (runnerState.ActiveDownloadClients.Any(m => m.Value.Type == Data.Enums.DownloadClient.DownloadStation))
|
||||
if (ActiveDownloadClients.Any(m => m.Value.Type == Data.Enums.DownloadClient.DownloadStation))
|
||||
{
|
||||
Log("Updating DownloadStation status");
|
||||
|
||||
foreach (var activeDownload in runnerState.ActiveDownloadClients)
|
||||
foreach (var activeDownload in ActiveDownloadClients)
|
||||
{
|
||||
if (activeDownload.Value.Downloader is DownloadStationDownloader downloadStationDownloader)
|
||||
{
|
||||
|
|
@ -184,7 +184,7 @@ public class TorrentRunner(
|
|||
}
|
||||
|
||||
// Check if any torrents are finished downloading to the host, remove them from the active download list.
|
||||
var completedActiveDownloads = runnerState.ActiveDownloadClients.Where(m => m.Value.Finished).ToList();
|
||||
var completedActiveDownloads = ActiveDownloadClients.Where(m => m.Value.Finished).ToList();
|
||||
|
||||
if (completedActiveDownloads.Count > 0)
|
||||
{
|
||||
|
|
@ -196,7 +196,7 @@ public class TorrentRunner(
|
|||
|
||||
if (download == null)
|
||||
{
|
||||
runnerState.ActiveDownloadClients.TryRemove(downloadId, out _);
|
||||
ActiveDownloadClients.TryRemove(downloadId, out _);
|
||||
|
||||
Log($"Download with ID {downloadId} not found! Removed from download queue");
|
||||
|
||||
|
|
@ -237,14 +237,14 @@ public class TorrentRunner(
|
|||
await downloads.UpdateUnpackingQueued(downloadId, DateTimeOffset.UtcNow);
|
||||
}
|
||||
|
||||
runnerState.ActiveDownloadClients.TryRemove(downloadId, out _);
|
||||
ActiveDownloadClients.TryRemove(downloadId, out _);
|
||||
|
||||
Log($"Removed from ActiveDownloadClients", download, download.Torrent);
|
||||
}
|
||||
}
|
||||
|
||||
// Check if any torrents are finished unpacking, remove them from the active unpack list.
|
||||
var completedUnpacks = runnerState.ActiveUnpackClients.Where(m => m.Value.Finished).ToList();
|
||||
var completedUnpacks = ActiveUnpackClients.Where(m => m.Value.Finished).ToList();
|
||||
|
||||
if (completedUnpacks.Count > 0)
|
||||
{
|
||||
|
|
@ -256,7 +256,7 @@ public class TorrentRunner(
|
|||
|
||||
if (download == null)
|
||||
{
|
||||
runnerState.ActiveUnpackClients.TryRemove(downloadId, out _);
|
||||
ActiveUnpackClients.TryRemove(downloadId, out _);
|
||||
|
||||
Log($"Download with ID {downloadId} not found! Removed from unpack queue");
|
||||
|
||||
|
|
@ -278,7 +278,7 @@ public class TorrentRunner(
|
|||
|
||||
await downloads.UpdateCompleted(downloadId, DateTimeOffset.UtcNow);
|
||||
|
||||
runnerState.ActiveUnpackClients.TryRemove(downloadId, out _);
|
||||
ActiveUnpackClients.TryRemove(downloadId, out _);
|
||||
|
||||
Log($"Removed from ActiveUnpackClients", download, download.Torrent);
|
||||
}
|
||||
|
|
@ -288,23 +288,23 @@ public class TorrentRunner(
|
|||
var downloadsById = allTorrents.SelectMany(m => m.Downloads).ToDictionary(m => m.DownloadId, m => m);
|
||||
|
||||
// Check for deleted torrents that are stuck in the ActiveDownloads or ActiveUnpacks
|
||||
foreach (var activeDownload in runnerState.ActiveDownloadClients)
|
||||
foreach (var activeDownload in ActiveDownloadClients)
|
||||
{
|
||||
if (!downloadsById.ContainsKey(activeDownload.Key))
|
||||
{
|
||||
await activeDownload.Value.Cancel();
|
||||
runnerState.ActiveDownloadClients.TryRemove(activeDownload.Key, out _);
|
||||
ActiveDownloadClients.TryRemove(activeDownload.Key, out _);
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var activeUnpacks in runnerState.ActiveUnpackClients)
|
||||
foreach (var activeUnpacks in ActiveUnpackClients)
|
||||
{
|
||||
if (!downloadsById.ContainsKey(activeUnpacks.Key))
|
||||
{
|
||||
activeUnpacks.Value.Cancel();
|
||||
runnerState.ActiveUnpackClients.TryRemove(activeUnpacks.Key, out _);
|
||||
ActiveUnpackClients.TryRemove(activeUnpacks.Key, out _);
|
||||
|
||||
break;
|
||||
}
|
||||
|
|
@ -367,10 +367,8 @@ public class TorrentRunner(
|
|||
}
|
||||
|
||||
// Process torrents in DebridQueue
|
||||
var torrentsToAddToProvider = allTorrents
|
||||
.Where(m => m.Completed == null && m.Error == null && m.RdId == null && m.RdAdded == null && m.FileOrMagnet != null &&
|
||||
m.RdStatus == TorrentStatus.Queued)
|
||||
.ToList();
|
||||
var torrentsToAddToProvider = allTorrents.Where(m => m.Completed == null && m.Error == null && m.RdId == null && m.RdAdded == null && m.FileOrMagnet != null && m.RdStatus == TorrentStatus.Queued)
|
||||
.ToList();
|
||||
|
||||
if (torrentsToAddToProvider.Count != 0)
|
||||
{
|
||||
|
|
@ -384,7 +382,7 @@ public class TorrentRunner(
|
|||
{
|
||||
var downloadingTorrentsCount = allTorrents.Count(m => m.RdStatus is not (TorrentStatus.Queued or TorrentStatus.Finished or TorrentStatus.Error));
|
||||
|
||||
var maxParallelDownloads = settings.Current.Provider.MaxParallelDownloads;
|
||||
var maxParallelDownloads = Settings.Get.Provider.MaxParallelDownloads;
|
||||
|
||||
logger.LogDebug("Currently downloading {downloadingTorrentCount}/{maxParallelDownloads} torrents, {queuedCount} queued.",
|
||||
downloadingTorrentsCount,
|
||||
|
|
@ -479,35 +477,31 @@ public class TorrentRunner(
|
|||
{
|
||||
// Check if there are any downloads that are queued and can be started.
|
||||
var queuedDownloads = torrent.Downloads
|
||||
.Where(m => m.Completed == null
|
||||
&& m.DownloadQueued != null
|
||||
&& m.DownloadQueued <= DateTimeOffset.UtcNow
|
||||
&& m.DownloadStarted == null
|
||||
&& m.Error == null)
|
||||
.Where(m => m.Completed == null && m.DownloadQueued != null && m.DownloadStarted == null && m.Error == null)
|
||||
.OrderBy(m => m.DownloadQueued)
|
||||
.ToList();
|
||||
|
||||
Log($"Currently {queuedDownloads.Count} queued downloads and {runnerState.ActiveDownloadClients.Count} total active downloads", torrent);
|
||||
Log($"Currently {queuedDownloads.Count} queued downloads and {ActiveDownloadClients.Count} total active downloads", torrent);
|
||||
|
||||
foreach (var download in queuedDownloads)
|
||||
{
|
||||
Log($"Processing to download", download, torrent);
|
||||
|
||||
if (runnerState.ActiveDownloadClients.Count >= settingDownloadLimit && torrent.DownloadClient != Data.Enums.DownloadClient.Symlink)
|
||||
if (ActiveDownloadClients.Count >= settingDownloadLimit && torrent.DownloadClient != Data.Enums.DownloadClient.Symlink)
|
||||
{
|
||||
Log($"Not starting download because there are already the max number of downloads active", download, torrent);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (runnerState.IsPausedForLowDiskSpace && torrent.DownloadClient == Data.Enums.DownloadClient.Bezzad)
|
||||
if (IsPausedForLowDiskSpace && torrent.DownloadClient == Data.Enums.DownloadClient.Bezzad)
|
||||
{
|
||||
logger.LogInformation($"Not starting Bezzad download because of low disk space {download.ToLog()} {torrent.ToLog()}");
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (runnerState.ActiveDownloadClients.ContainsKey(download.DownloadId))
|
||||
if (ActiveDownloadClients.ContainsKey(download.DownloadId))
|
||||
{
|
||||
Log($"Not starting download because this download is already active", download, torrent);
|
||||
|
||||
|
|
@ -534,24 +528,10 @@ public class TorrentRunner(
|
|||
{
|
||||
logger.LogError(ex, "Cannot unrestrict link: {ex.Message}", ex.Message);
|
||||
|
||||
if (download.RetryCount < torrent.DownloadRetryAttempts)
|
||||
{
|
||||
var retryCount = download.RetryCount + 1;
|
||||
var retryDelay = GetDownloadLinkRetryDelay(retryCount);
|
||||
var retryAt = DateTimeOffset.UtcNow.Add(retryDelay);
|
||||
|
||||
Log($"Retrying download link generation {retryCount}/{torrent.DownloadRetryAttempts} at {retryAt:u}", download, torrent);
|
||||
|
||||
await downloads.Reset(download.DownloadId, retryAt);
|
||||
await downloads.UpdateRetryCount(download.DownloadId, retryCount);
|
||||
}
|
||||
else
|
||||
{
|
||||
await downloads.UpdateError(download.DownloadId, ex.Message);
|
||||
await downloads.UpdateCompleted(download.DownloadId, DateTimeOffset.UtcNow);
|
||||
download.Error = ex.Message;
|
||||
download.Completed = DateTimeOffset.UtcNow;
|
||||
}
|
||||
await downloads.UpdateError(download.DownloadId, ex.Message);
|
||||
await downloads.UpdateCompleted(download.DownloadId, DateTimeOffset.UtcNow);
|
||||
download.Error = ex.Message;
|
||||
download.Completed = DateTimeOffset.UtcNow;
|
||||
|
||||
return;
|
||||
}
|
||||
|
|
@ -573,7 +553,7 @@ public class TorrentRunner(
|
|||
// Start the download process
|
||||
var downloadClient = new DownloadClient(download, torrent, downloadPath, torrent.Category);
|
||||
|
||||
if (runnerState.ActiveDownloadClients.TryAdd(download.DownloadId, downloadClient))
|
||||
if (ActiveDownloadClients.TryAdd(download.DownloadId, downloadClient))
|
||||
{
|
||||
Log($"Starting download", download, torrent);
|
||||
|
||||
|
|
@ -593,7 +573,7 @@ public class TorrentRunner(
|
|||
await downloads.UpdateRemoteId(download.DownloadId, remoteId);
|
||||
}
|
||||
|
||||
if (runnerState.IsPausedForLowDiskSpace && downloadClient.Type == Data.Enums.DownloadClient.Bezzad)
|
||||
if (IsPausedForLowDiskSpace && downloadClient.Type == Data.Enums.DownloadClient.Bezzad)
|
||||
{
|
||||
logger.LogInformation($"Pausing new Bezzad download due to low disk space {download.ToLog()} {torrent.ToLog()}");
|
||||
await downloadClient.Pause();
|
||||
|
|
@ -653,14 +633,14 @@ public class TorrentRunner(
|
|||
}
|
||||
|
||||
// Check if we have reached the download limit, if so queue the download, but don't start it.
|
||||
if (runnerState.ActiveUnpackClients.Count >= settingUnpackLimit)
|
||||
if (ActiveUnpackClients.Count >= settingUnpackLimit)
|
||||
{
|
||||
Log($"Not starting unpack because there are already the max number of unpacks active", download, torrent);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (runnerState.ActiveUnpackClients.ContainsKey(download.DownloadId))
|
||||
if (ActiveUnpackClients.ContainsKey(download.DownloadId))
|
||||
{
|
||||
Log($"Not starting unpack because this download is already active", download, torrent);
|
||||
|
||||
|
|
@ -682,7 +662,7 @@ public class TorrentRunner(
|
|||
// Start the unpacking process
|
||||
var unpackClient = new UnpackClient(download, downloadPath);
|
||||
|
||||
if (runnerState.ActiveUnpackClients.TryAdd(download.DownloadId, unpackClient))
|
||||
if (ActiveUnpackClients.TryAdd(download.DownloadId, unpackClient))
|
||||
{
|
||||
Log($"Starting unpack", download, torrent);
|
||||
|
||||
|
|
@ -740,8 +720,8 @@ public class TorrentRunner(
|
|||
|
||||
var completePerc = 0;
|
||||
|
||||
var totalDownloadBytes = torrent.Downloads.Sum(m => runnerState.GetStats(m.DownloadId).BytesTotal);
|
||||
var totalDoneBytes = torrent.Downloads.Sum(m => runnerState.GetStats(m.DownloadId).BytesDone);
|
||||
var totalDownloadBytes = torrent.Downloads.Sum(m => GetStats(m.DownloadId).BytesTotal);
|
||||
var totalDoneBytes = torrent.Downloads.Sum(m => GetStats(m.DownloadId).BytesDone);
|
||||
|
||||
if (totalDownloadBytes > 0)
|
||||
{
|
||||
|
|
@ -802,19 +782,6 @@ public class TorrentRunner(
|
|||
});
|
||||
}
|
||||
|
||||
private static TimeSpan GetDownloadLinkRetryDelay(Int32 retryCount)
|
||||
{
|
||||
var seconds = retryCount switch
|
||||
{
|
||||
<= 1 => 15,
|
||||
2 => 30,
|
||||
3 => 60,
|
||||
_ => 120
|
||||
};
|
||||
|
||||
return TimeSpan.FromSeconds(seconds);
|
||||
}
|
||||
|
||||
private void Log(String message, Download? download, Torrent? torrent)
|
||||
{
|
||||
if (download != null)
|
||||
|
|
|
|||
|
|
@ -1,47 +0,0 @@
|
|||
using System.Collections.Concurrent;
|
||||
|
||||
namespace RdtClient.Service.Services;
|
||||
|
||||
public interface ITorrentRunnerState
|
||||
{
|
||||
ConcurrentDictionary<Guid, DownloadClient> ActiveDownloadClients { get; }
|
||||
|
||||
ConcurrentDictionary<Guid, UnpackClient> ActiveUnpackClients { get; }
|
||||
|
||||
Boolean IsPausedForLowDiskSpace { get; set; }
|
||||
|
||||
(Int64 Speed, Int64 BytesTotal, Int64 BytesDone) GetStats(Guid downloadId);
|
||||
|
||||
void Clear();
|
||||
}
|
||||
|
||||
public class TorrentRunnerState : ITorrentRunnerState
|
||||
{
|
||||
public ConcurrentDictionary<Guid, DownloadClient> ActiveDownloadClients { get; } = new();
|
||||
|
||||
public ConcurrentDictionary<Guid, UnpackClient> ActiveUnpackClients { get; } = new();
|
||||
|
||||
public Boolean IsPausedForLowDiskSpace { get; set; }
|
||||
|
||||
public (Int64 Speed, Int64 BytesTotal, Int64 BytesDone) GetStats(Guid downloadId)
|
||||
{
|
||||
if (ActiveDownloadClients.TryGetValue(downloadId, out var downloadClient))
|
||||
{
|
||||
return (downloadClient.Speed, downloadClient.BytesTotal, downloadClient.BytesDone);
|
||||
}
|
||||
|
||||
if (ActiveUnpackClients.TryGetValue(downloadId, out var unpackClient))
|
||||
{
|
||||
return (0, 100, unpackClient.Progess);
|
||||
}
|
||||
|
||||
return (0, 0, 0);
|
||||
}
|
||||
|
||||
public void Clear()
|
||||
{
|
||||
ActiveDownloadClients.Clear();
|
||||
ActiveUnpackClients.Clear();
|
||||
IsPausedForLowDiskSpace = false;
|
||||
}
|
||||
}
|
||||
|
|
@ -32,9 +32,7 @@ public class Torrents(
|
|||
PremiumizeDebridClient premiumizeDebridClient,
|
||||
RealDebridDebridClient realDebridDebridClient,
|
||||
DebridLinkClient debridLinkClient,
|
||||
TorBoxDebridClient torBoxDebridClient,
|
||||
ISettings settings,
|
||||
ITorrentRunnerState runnerState)
|
||||
TorBoxDebridClient torBoxDebridClient)
|
||||
{
|
||||
private static readonly SemaphoreSlim RealDebridUpdateLock = new(1, 1);
|
||||
|
||||
|
|
@ -49,7 +47,7 @@ public class Torrents(
|
|||
{
|
||||
get
|
||||
{
|
||||
return settings.Current.Provider.Provider switch
|
||||
return Settings.Get.Provider.Provider switch
|
||||
{
|
||||
Provider.Premiumize => premiumizeDebridClient,
|
||||
Provider.RealDebrid => realDebridDebridClient,
|
||||
|
|
@ -63,7 +61,7 @@ public class Torrents(
|
|||
|
||||
public virtual (Int64 Speed, Int64 BytesTotal, Int64 BytesDone) GetDownloadStats(Guid downloadId)
|
||||
{
|
||||
return runnerState.GetStats(downloadId);
|
||||
return TorrentRunner.GetStats(downloadId);
|
||||
}
|
||||
|
||||
public virtual async Task<IList<Torrent>> Get()
|
||||
|
|
@ -199,9 +197,9 @@ public class Torrents(
|
|||
throw new($"{ex.Message}, trying to parse {magnetLink}");
|
||||
}
|
||||
|
||||
if (!String.IsNullOrWhiteSpace(settings.Current.General.BannedTrackers))
|
||||
if (!String.IsNullOrWhiteSpace(Settings.Get.General.BannedTrackers))
|
||||
{
|
||||
var bannedTrackers = settings.Current.General.BannedTrackers.Split(',');
|
||||
var bannedTrackers = Settings.Get.General.BannedTrackers.Split(',');
|
||||
|
||||
foreach (var bannedTracker in bannedTrackers)
|
||||
{
|
||||
|
|
@ -266,9 +264,9 @@ public class Torrents(
|
|||
throw new($"{ex.Message}, trying to parse {fileAsBase64}");
|
||||
}
|
||||
|
||||
if (!String.IsNullOrWhiteSpace(settings.Current.General.BannedTrackers))
|
||||
if (!String.IsNullOrWhiteSpace(Settings.Get.General.BannedTrackers))
|
||||
{
|
||||
var bannedTrackers = settings.Current.General.BannedTrackers.Split(',');
|
||||
var bannedTrackers = Settings.Get.General.BannedTrackers.Split(',');
|
||||
|
||||
foreach (var bannedTracker in bannedTrackers)
|
||||
{
|
||||
|
|
@ -314,16 +312,16 @@ public class Torrents(
|
|||
|
||||
private async Task CopyAddedTorrent(Torrent torrent)
|
||||
{
|
||||
if (String.IsNullOrWhiteSpace(settings.Current.General.CopyAddedTorrents) || String.IsNullOrWhiteSpace(torrent.FileOrMagnet) || String.IsNullOrWhiteSpace(torrent.RdName))
|
||||
if (String.IsNullOrWhiteSpace(Settings.Get.General.CopyAddedTorrents) || String.IsNullOrWhiteSpace(torrent.FileOrMagnet) || String.IsNullOrWhiteSpace(torrent.RdName))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
if (!fileSystem.Directory.Exists(settings.Current.General.CopyAddedTorrents))
|
||||
if (!fileSystem.Directory.Exists(Settings.Get.General.CopyAddedTorrents))
|
||||
{
|
||||
fileSystem.Directory.CreateDirectory(settings.Current.General.CopyAddedTorrents);
|
||||
fileSystem.Directory.CreateDirectory(Settings.Get.General.CopyAddedTorrents);
|
||||
}
|
||||
|
||||
var extension = torrent.Type switch
|
||||
|
|
@ -333,7 +331,7 @@ public class Torrents(
|
|||
_ => throw new ArgumentException("Unexpected DownloadType")
|
||||
};
|
||||
|
||||
var copyFileName = Path.Combine(settings.Current.General.CopyAddedTorrents, FileHelper.RemoveInvalidFileNameChars(torrent.RdName));
|
||||
var copyFileName = Path.Combine(Settings.Get.General.CopyAddedTorrents, FileHelper.RemoveInvalidFileNameChars(torrent.RdName));
|
||||
|
||||
if (!copyFileName.EndsWith(extension, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
|
|
@ -357,7 +355,7 @@ public class Torrents(
|
|||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, $"Unable to create torrent blackhole directory: {settings.Current.General.CopyAddedTorrents}: {ex.Message}");
|
||||
logger.LogError(ex, $"Unable to create torrent blackhole directory: {Settings.Get.General.CopyAddedTorrents}: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -513,7 +511,7 @@ public class Torrents(
|
|||
{
|
||||
var retry = 10;
|
||||
|
||||
while (runnerState.ActiveDownloadClients.TryGetValue(download.DownloadId, out var downloadClient))
|
||||
while (TorrentRunner.ActiveDownloadClients.TryGetValue(download.DownloadId, out var downloadClient))
|
||||
{
|
||||
Log($"Cancelling download", download, torrent);
|
||||
|
||||
|
|
@ -531,7 +529,7 @@ public class Torrents(
|
|||
|
||||
retry = 10;
|
||||
|
||||
while (runnerState.ActiveUnpackClients.TryGetValue(download.DownloadId, out var unpackClient))
|
||||
while (TorrentRunner.ActiveUnpackClients.TryGetValue(download.DownloadId, out var unpackClient))
|
||||
{
|
||||
Log($"Cancelling unpack", download, torrent);
|
||||
|
||||
|
|
@ -571,7 +569,7 @@ public class Torrents(
|
|||
|
||||
if (deleteLocalFiles && !String.IsNullOrWhiteSpace(torrent.RdName))
|
||||
{
|
||||
var downloadPath = DownloadPath(torrent, settings.Current);
|
||||
var downloadPath = DownloadPath(torrent);
|
||||
downloadPath = Path.Combine(downloadPath, torrent.RdName);
|
||||
|
||||
Log($"Deleting local files in {downloadPath}", torrent);
|
||||
|
|
@ -636,13 +634,13 @@ public class Torrents(
|
|||
|
||||
var profile = new Profile
|
||||
{
|
||||
Provider = Enum.GetName(settings.Current.Provider.Provider),
|
||||
Provider = Enum.GetName(Settings.Get.Provider.Provider),
|
||||
UserName = user.Username,
|
||||
Expiration = user.Expiration,
|
||||
CurrentVersion = UpdateChecker.CurrentVersion,
|
||||
LatestVersion = UpdateChecker.LatestVersion,
|
||||
IsInsecure = UpdateChecker.IsInsecure,
|
||||
DisableUpdateNotification = settings.Current.General.DisableUpdateNotifications
|
||||
DisableUpdateNotification = Settings.Get.General.DisableUpdateNotifications
|
||||
};
|
||||
|
||||
return profile;
|
||||
|
|
@ -664,58 +662,26 @@ public class Torrents(
|
|||
{
|
||||
torrentsByRdId.TryGetValue(rdTorrent.Id, out var torrent);
|
||||
|
||||
// TorBox migration from storing torrent hash in RdId to torrent ids.
|
||||
if (torrent == null
|
||||
&& Settings.Get.Provider.Provider == Provider.TorBox
|
||||
&& rdTorrent.Type == DownloadType.Torrent
|
||||
&& !String.IsNullOrWhiteSpace(rdTorrent.Hash)
|
||||
&& !String.IsNullOrWhiteSpace(rdTorrent.Id))
|
||||
{
|
||||
torrent = torrents.FirstOrDefault(localTorrent => localTorrent is { Type: DownloadType.Torrent, ClientKind: null or Provider.TorBox }
|
||||
&& !String.IsNullOrWhiteSpace(localTorrent.Hash)
|
||||
&& !String.IsNullOrWhiteSpace(localTorrent.RdId)
|
||||
&& localTorrent.RdId.Equals(localTorrent.Hash, StringComparison.OrdinalIgnoreCase)
|
||||
&& localTorrent.Hash.Equals(rdTorrent.Hash, StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
if (torrent != null)
|
||||
{
|
||||
if (!String.IsNullOrWhiteSpace(torrent.RdId))
|
||||
{
|
||||
torrentsByRdId.Remove(torrent.RdId);
|
||||
}
|
||||
|
||||
await torrentData.UpdateRdId(torrent, rdTorrent.Id);
|
||||
torrent.RdId = rdTorrent.Id;
|
||||
torrent.ClientKind = Provider.TorBox;
|
||||
torrentsByRdId[rdTorrent.Id] = torrent;
|
||||
|
||||
logger.LogInformation("Migrated TorBox torrent RdId from hash to torrent id for {TorrentName} ({Hash}) -> {RdId}",
|
||||
torrent.RdName ?? rdTorrent.Filename,
|
||||
rdTorrent.Hash,
|
||||
rdTorrent.Id);
|
||||
}
|
||||
}
|
||||
|
||||
// Auto import torrents only torrents that have their files selected
|
||||
if (torrent == null && settings.Current.Provider.AutoImport)
|
||||
if (torrent == null && Settings.Get.Provider.AutoImport)
|
||||
{
|
||||
var newTorrent = new Torrent
|
||||
{
|
||||
Category = settings.Current.Provider.Default.Category,
|
||||
DownloadClient = settings.Current.DownloadClient.Client,
|
||||
Category = Settings.Get.Provider.Default.Category,
|
||||
DownloadClient = Settings.Get.DownloadClient.Client,
|
||||
DownloadAction =
|
||||
settings.Current.Provider.Default.OnlyDownloadAvailableFiles ? TorrentDownloadAction.DownloadAvailableFiles : TorrentDownloadAction.DownloadAll,
|
||||
HostDownloadAction = settings.Current.Provider.Default.HostDownloadAction,
|
||||
FinishedActionDelay = settings.Current.Provider.Default.FinishedActionDelay,
|
||||
FinishedAction = settings.Current.Provider.Default.FinishedAction,
|
||||
DownloadMinSize = settings.Current.Provider.Default.MinFileSize,
|
||||
IncludeRegex = settings.Current.Provider.Default.IncludeRegex,
|
||||
ExcludeRegex = settings.Current.Provider.Default.ExcludeRegex,
|
||||
TorrentRetryAttempts = settings.Current.Provider.Default.TorrentRetryAttempts,
|
||||
DownloadRetryAttempts = settings.Current.Provider.Default.DownloadRetryAttempts,
|
||||
DeleteOnError = settings.Current.Provider.Default.DeleteOnError,
|
||||
Lifetime = settings.Current.Provider.Default.TorrentLifetime,
|
||||
Priority = settings.Current.Provider.Default.Priority > 0 ? settings.Current.Provider.Default.Priority : null,
|
||||
Settings.Get.Provider.Default.OnlyDownloadAvailableFiles ? TorrentDownloadAction.DownloadAvailableFiles : TorrentDownloadAction.DownloadAll,
|
||||
HostDownloadAction = Settings.Get.Provider.Default.HostDownloadAction,
|
||||
FinishedActionDelay = Settings.Get.Provider.Default.FinishedActionDelay,
|
||||
FinishedAction = Settings.Get.Provider.Default.FinishedAction,
|
||||
DownloadMinSize = Settings.Get.Provider.Default.MinFileSize,
|
||||
IncludeRegex = Settings.Get.Provider.Default.IncludeRegex,
|
||||
ExcludeRegex = Settings.Get.Provider.Default.ExcludeRegex,
|
||||
TorrentRetryAttempts = Settings.Get.Provider.Default.TorrentRetryAttempts,
|
||||
DownloadRetryAttempts = Settings.Get.Provider.Default.DownloadRetryAttempts,
|
||||
DeleteOnError = Settings.Get.Provider.Default.DeleteOnError,
|
||||
Lifetime = Settings.Get.Provider.Default.TorrentLifetime,
|
||||
Priority = Settings.Get.Provider.Default.Priority > 0 ? Settings.Get.Provider.Default.Priority : null,
|
||||
RdId = rdTorrent.Id
|
||||
};
|
||||
|
||||
|
|
@ -724,7 +690,7 @@ public class Torrents(
|
|||
continue;
|
||||
}
|
||||
|
||||
torrent = await torrentData.Add(rdTorrent.Id, rdTorrent.Hash, null, false, DownloadType.Torrent, settings.Current.DownloadClient.Client, newTorrent);
|
||||
torrent = await torrentData.Add(rdTorrent.Id, rdTorrent.Hash, null, false, DownloadType.Torrent, Settings.Get.DownloadClient.Client, newTorrent);
|
||||
torrentsByRdId[rdTorrent.Id] = torrent;
|
||||
torrents.Add(torrent);
|
||||
|
||||
|
|
@ -740,7 +706,7 @@ public class Torrents(
|
|||
{
|
||||
var rdTorrent = torrent.RdId != null && providerTorrentsById.TryGetValue(torrent.RdId, out var providerTorrent) ? providerTorrent : null;
|
||||
|
||||
if (rdTorrent == null && settings.Current.Provider.AutoDelete && torrent.RdStatus != TorrentStatus.Queued)
|
||||
if (rdTorrent == null && Settings.Get.Provider.AutoDelete && torrent.RdStatus != TorrentStatus.Queued)
|
||||
{
|
||||
await Delete(torrent.TorrentId, true, false, true);
|
||||
}
|
||||
|
|
@ -778,14 +744,14 @@ public class Torrents(
|
|||
|
||||
foreach (var download in torrent.Downloads)
|
||||
{
|
||||
while (runnerState.ActiveDownloadClients.TryRemove(download.DownloadId, out var downloadClient))
|
||||
while (TorrentRunner.ActiveDownloadClients.TryRemove(download.DownloadId, out var downloadClient))
|
||||
{
|
||||
await downloadClient.Cancel();
|
||||
|
||||
await Task.Delay(100);
|
||||
}
|
||||
|
||||
while (runnerState.ActiveUnpackClients.TryRemove(download.DownloadId, out var unpackClient))
|
||||
while (TorrentRunner.ActiveUnpackClients.TryRemove(download.DownloadId, out var unpackClient))
|
||||
{
|
||||
unpackClient.Cancel();
|
||||
|
||||
|
|
@ -848,21 +814,21 @@ public class Torrents(
|
|||
|
||||
Log($"Retrying Download", download, download.Torrent);
|
||||
|
||||
while (runnerState.ActiveDownloadClients.TryRemove(download.DownloadId, out var downloadClient))
|
||||
while (TorrentRunner.ActiveDownloadClients.TryRemove(download.DownloadId, out var downloadClient))
|
||||
{
|
||||
await downloadClient.Cancel();
|
||||
|
||||
await Task.Delay(100);
|
||||
}
|
||||
|
||||
while (runnerState.ActiveUnpackClients.TryRemove(download.DownloadId, out var unpackClient))
|
||||
while (TorrentRunner.ActiveUnpackClients.TryRemove(download.DownloadId, out var unpackClient))
|
||||
{
|
||||
unpackClient.Cancel();
|
||||
|
||||
await Task.Delay(100);
|
||||
}
|
||||
|
||||
var downloadPath = DownloadPath(download.Torrent!, settings.Current);
|
||||
var downloadPath = DownloadPath(download.Torrent!);
|
||||
|
||||
var filePath = DownloadHelper.GetDownloadPath(downloadPath, download.Torrent!, download);
|
||||
|
||||
|
|
@ -963,9 +929,9 @@ public class Torrents(
|
|||
return torrent;
|
||||
}
|
||||
|
||||
private static String DownloadPath(Torrent torrent, DbSettings settings)
|
||||
private static String DownloadPath(Torrent torrent)
|
||||
{
|
||||
var settingDownloadPath = settings.DownloadClient.DownloadPath;
|
||||
var settingDownloadPath = Settings.Get.DownloadClient.DownloadPath;
|
||||
|
||||
if (!String.IsNullOrWhiteSpace(torrent.Category))
|
||||
{
|
||||
|
|
@ -1004,11 +970,11 @@ public class Torrents(
|
|||
await torrentData.Update(torrent);
|
||||
}
|
||||
|
||||
public async Task RunTorrentComplete(Guid torrentId, DbSettings? runSettings = null)
|
||||
public async Task RunTorrentComplete(Guid torrentId, DbSettings? settings = null)
|
||||
{
|
||||
runSettings ??= settings.Current;
|
||||
settings ??= Settings.Get;
|
||||
|
||||
if (String.IsNullOrWhiteSpace(runSettings.General.RunOnTorrentCompleteFileName))
|
||||
if (String.IsNullOrWhiteSpace(settings.General.RunOnTorrentCompleteFileName))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
|
@ -1017,12 +983,12 @@ public class Torrents(
|
|||
|
||||
var downloadsForTorrent = await downloads.GetForTorrent(torrentId);
|
||||
|
||||
var fileName = runSettings.General.RunOnTorrentCompleteFileName;
|
||||
var arguments = runSettings.General.RunOnTorrentCompleteArguments ?? "";
|
||||
var fileName = settings.General.RunOnTorrentCompleteFileName;
|
||||
var arguments = settings.General.RunOnTorrentCompleteArguments ?? "";
|
||||
|
||||
Log($"Parsing external program {fileName} with arguments {arguments}", torrent);
|
||||
|
||||
var downloadPath = DownloadPath(torrent, runSettings);
|
||||
var downloadPath = DownloadPath(torrent);
|
||||
var torrentPath = Path.Combine(downloadPath, torrent.RdName ?? "Unknown");
|
||||
|
||||
var filePath = torrentPath;
|
||||
|
|
@ -1117,7 +1083,7 @@ public class Torrents(
|
|||
await torrentData.UpdateRdData(torrent);
|
||||
}
|
||||
}
|
||||
catch (Exception)
|
||||
catch (Exception ex)
|
||||
{
|
||||
// ignored
|
||||
}
|
||||
|
|
@ -1169,19 +1135,18 @@ public class Torrents(
|
|||
torrent.RdFiles);
|
||||
}
|
||||
|
||||
private readonly record struct TorrentRdState(
|
||||
String? RdName,
|
||||
Int64? RdSize,
|
||||
String? RdHost,
|
||||
Int64? RdSplit,
|
||||
Int64? RdProgress,
|
||||
TorrentStatus? RdStatus,
|
||||
String? RdStatusRaw,
|
||||
DateTimeOffset? RdAdded,
|
||||
DateTimeOffset? RdEnded,
|
||||
Int64? RdSpeed,
|
||||
Int64? RdSeeders,
|
||||
String? RdFiles);
|
||||
private readonly record struct TorrentRdState(String? RdName,
|
||||
Int64? RdSize,
|
||||
String? RdHost,
|
||||
Int64? RdSplit,
|
||||
Int64? RdProgress,
|
||||
TorrentStatus? RdStatus,
|
||||
String? RdStatusRaw,
|
||||
DateTimeOffset? RdAdded,
|
||||
DateTimeOffset? RdEnded,
|
||||
Int64? RdSpeed,
|
||||
Int64? RdSeeders,
|
||||
String? RdFiles);
|
||||
|
||||
private void Log(String message, Download? download, Torrent? torrent)
|
||||
{
|
||||
|
|
|
|||
|
|
@ -12,20 +12,15 @@ public class QBittorrentControllerTest
|
|||
{
|
||||
private readonly QBittorrentController _controller;
|
||||
private readonly Mock<QBittorrent> _qBittorrentMock;
|
||||
private readonly Mock<Torrents> _torrentsMock;
|
||||
private readonly TestSettings _settings;
|
||||
|
||||
public QBittorrentControllerTest()
|
||||
{
|
||||
_settings = new();
|
||||
_qBittorrentMock = new(new Mock<ILogger<QBittorrent>>().Object, _settings, null!, null!, null!, new TorrentRunnerState());
|
||||
_torrentsMock = new(null!, null!, null!, null!, null!, null!, null!, null!, null!, null!, null!, _settings, new TorrentRunnerState());
|
||||
_qBittorrentMock = new(new Mock<ILogger<QBittorrent>>().Object, null!, null!, null!, null!);
|
||||
|
||||
_controller = new(new Mock<ILogger<QBittorrentController>>().Object,
|
||||
_qBittorrentMock.Object,
|
||||
new Mock<IHttpClientFactory>().Object,
|
||||
_settings,
|
||||
_torrentsMock.Object);
|
||||
_controller = new(
|
||||
new Mock<ILogger<QBittorrentController>>().Object,
|
||||
_qBittorrentMock.Object,
|
||||
new Mock<IHttpClientFactory>().Object);
|
||||
|
||||
_controller.ControllerContext = new()
|
||||
{
|
||||
|
|
@ -37,16 +32,15 @@ public class QBittorrentControllerTest
|
|||
public async Task TorrentsInfo_FilterAll_DoesNotFilterOutResults()
|
||||
{
|
||||
// Arrange
|
||||
_qBittorrentMock.Setup(q => q.TorrentInfo())
|
||||
.ReturnsAsync(new List<TorrentInfo>
|
||||
{
|
||||
new()
|
||||
{
|
||||
Hash = "hash1",
|
||||
State = "pausedUP",
|
||||
Progress = 1f
|
||||
}
|
||||
});
|
||||
_qBittorrentMock.Setup(q => q.TorrentInfo()).ReturnsAsync(new List<TorrentInfo>
|
||||
{
|
||||
new()
|
||||
{
|
||||
Hash = "hash1",
|
||||
State = "pausedUP",
|
||||
Progress = 1f
|
||||
}
|
||||
});
|
||||
|
||||
// Act
|
||||
var result = await _controller.TorrentsInfo(new()
|
||||
|
|
@ -66,22 +60,21 @@ public class QBittorrentControllerTest
|
|||
public async Task TorrentsInfo_FilterCompleted_MatchesPausedUploadTorrents()
|
||||
{
|
||||
// Arrange
|
||||
_qBittorrentMock.Setup(q => q.TorrentInfo())
|
||||
.ReturnsAsync(new List<TorrentInfo>
|
||||
{
|
||||
new()
|
||||
{
|
||||
Hash = "hash1",
|
||||
State = "pausedUP",
|
||||
Progress = 1f
|
||||
},
|
||||
new()
|
||||
{
|
||||
Hash = "hash2",
|
||||
State = "downloading",
|
||||
Progress = 0.4f
|
||||
}
|
||||
});
|
||||
_qBittorrentMock.Setup(q => q.TorrentInfo()).ReturnsAsync(new List<TorrentInfo>
|
||||
{
|
||||
new()
|
||||
{
|
||||
Hash = "hash1",
|
||||
State = "pausedUP",
|
||||
Progress = 1f
|
||||
},
|
||||
new()
|
||||
{
|
||||
Hash = "hash2",
|
||||
State = "downloading",
|
||||
Progress = 0.4f
|
||||
}
|
||||
});
|
||||
|
||||
// Act
|
||||
var result = await _controller.TorrentsInfo(new()
|
||||
|
|
@ -95,4 +88,4 @@ public class QBittorrentControllerTest
|
|||
Assert.Single(payload);
|
||||
Assert.Equal("hash1", payload[0].Hash);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -3,6 +3,7 @@ using Microsoft.AspNetCore.Http;
|
|||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Moq;
|
||||
using RdtClient.Data.Data;
|
||||
using RdtClient.Data.Enums;
|
||||
using RdtClient.Data.Models.Sabnzbd;
|
||||
using RdtClient.Service.Services;
|
||||
|
|
@ -16,17 +17,15 @@ public class SabnzbdControllerTest
|
|||
private readonly Mock<Authentication> _authenticationMock;
|
||||
private readonly SabnzbdController _controller;
|
||||
private readonly Mock<Sabnzbd> _sabnzbdMock;
|
||||
private readonly TestSettings _settings;
|
||||
|
||||
public SabnzbdControllerTest()
|
||||
{
|
||||
_settings = new();
|
||||
_settings.Current.General.AuthenticationType = AuthenticationType.None;
|
||||
_settings.Current.Provider.ApiKey = "test-api-key";
|
||||
SettingData.Get.General.AuthenticationType = AuthenticationType.None;
|
||||
SettingData.Get.Provider.ApiKey = "test-api-key";
|
||||
|
||||
var torrentsMock = new Mock<Torrents>(null!, null!, null!, null!, null!, null!, null!, null!, null!, null!, null!, _settings, new TorrentRunnerState());
|
||||
var torrentsMock = new Mock<Torrents>(null!, null!, null!, null!, null!, null!, null!, null!, null!, null!, null!);
|
||||
var sabnzbdLoggerMock = new Mock<ILogger<Sabnzbd>>();
|
||||
_sabnzbdMock = new(sabnzbdLoggerMock.Object, torrentsMock.Object, null!, _settings);
|
||||
_sabnzbdMock = new(sabnzbdLoggerMock.Object, torrentsMock.Object, null!);
|
||||
var loggerMock = new Mock<ILogger<SabnzbdController>>();
|
||||
_authenticationMock = new(null!, null!, null!);
|
||||
|
||||
|
|
@ -65,7 +64,7 @@ public class SabnzbdControllerTest
|
|||
public async Task GetQueue_Unauthorized_ReturnsOk_BecauseFilterIsSkippedInUnitTests()
|
||||
{
|
||||
// Arrange
|
||||
_settings.Current.General.AuthenticationType = AuthenticationType.UserNamePassword;
|
||||
SettingData.Get.General.AuthenticationType = AuthenticationType.UserNamePassword;
|
||||
|
||||
var queue = new SabnzbdQueue
|
||||
{
|
||||
|
|
@ -87,7 +86,7 @@ public class SabnzbdControllerTest
|
|||
public async Task GetQueue_WithMaAuth_ReturnsOk()
|
||||
{
|
||||
// Arrange
|
||||
_settings.Current.General.AuthenticationType = AuthenticationType.UserNamePassword;
|
||||
SettingData.Get.General.AuthenticationType = AuthenticationType.UserNamePassword;
|
||||
var httpContext = new DefaultHttpContext();
|
||||
httpContext.Request.QueryString = new("?ma_username=user&ma_password=pass");
|
||||
_controller.ControllerContext.HttpContext = httpContext;
|
||||
|
|
@ -108,30 +107,6 @@ public class SabnzbdControllerTest
|
|||
Assert.IsType<OkObjectResult>(result);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("?name=delete&value=hash1&del_files=1", true)]
|
||||
[InlineData("?name=delete&value=hash1&del_files=true", true)]
|
||||
[InlineData("?name=delete&value=hash1&del_files=0", false)]
|
||||
[InlineData("?name=delete&value=hash1", false)]
|
||||
public async Task Queue_Delete_PassesDeleteFilesFlag(String queryString, Boolean expectedDeleteFiles)
|
||||
{
|
||||
// Arrange
|
||||
var httpContext = new DefaultHttpContext();
|
||||
httpContext.Request.QueryString = new(queryString);
|
||||
_controller.ControllerContext.HttpContext = httpContext;
|
||||
|
||||
_sabnzbdMock.Setup(s => s.Delete("hash1", expectedDeleteFiles)).Returns(Task.CompletedTask);
|
||||
|
||||
// Act
|
||||
var result = await _controller.Queue();
|
||||
|
||||
// Assert
|
||||
var okResult = Assert.IsType<OkObjectResult>(result);
|
||||
var response = Assert.IsType<SabnzbdResponse>(okResult.Value);
|
||||
Assert.True(response.Status);
|
||||
_sabnzbdMock.Verify(s => s.Delete("hash1", expectedDeleteFiles), Times.Once);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetHistory_ReturnsOk()
|
||||
{
|
||||
|
|
@ -153,26 +128,6 @@ public class SabnzbdControllerTest
|
|||
Assert.Equal(1, response.History.NoOfSlots);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task History_Delete_PassesDeleteFilesFlag()
|
||||
{
|
||||
// Arrange
|
||||
var httpContext = new DefaultHttpContext();
|
||||
httpContext.Request.QueryString = new("?name=delete&value=hash1&del_files=1");
|
||||
_controller.ControllerContext.HttpContext = httpContext;
|
||||
|
||||
_sabnzbdMock.Setup(s => s.Delete("hash1", true)).Returns(Task.CompletedTask);
|
||||
|
||||
// Act
|
||||
var result = await _controller.History();
|
||||
|
||||
// Assert
|
||||
var okResult = Assert.IsType<OkObjectResult>(result);
|
||||
var response = Assert.IsType<SabnzbdResponse>(okResult.Value);
|
||||
Assert.True(response.Status);
|
||||
_sabnzbdMock.Verify(s => s.Delete("hash1", true), Times.Once);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetVersion_HasAllowAnonymousAttribute()
|
||||
{
|
||||
|
|
@ -191,7 +146,7 @@ public class SabnzbdControllerTest
|
|||
public void GetVersion_ReturnsOk()
|
||||
{
|
||||
// Arrange
|
||||
_settings.Current.General.AuthenticationType = AuthenticationType.UserNamePassword;
|
||||
SettingData.Get.General.AuthenticationType = AuthenticationType.UserNamePassword;
|
||||
|
||||
// Act
|
||||
var result = _controller.Version();
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ using Microsoft.AspNetCore.Authorization;
|
|||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using Moq;
|
||||
using RdtClient.Data.Data;
|
||||
using RdtClient.Data.Enums;
|
||||
using RdtClient.Service.Middleware;
|
||||
using RdtClient.Service.Services;
|
||||
|
|
@ -14,22 +15,20 @@ public class SabnzbdHandlerTest
|
|||
private readonly Mock<Authentication> _authenticationMock;
|
||||
private readonly SabnzbdHandler _handler;
|
||||
private readonly Mock<IHttpContextAccessor> _httpContextAccessorMock;
|
||||
private readonly TestSettings _settings;
|
||||
|
||||
public SabnzbdHandlerTest()
|
||||
{
|
||||
_authenticationMock = new(null!, null!, null!);
|
||||
_httpContextAccessorMock = new();
|
||||
_settings = new();
|
||||
_handler = new(_authenticationMock.Object, _httpContextAccessorMock.Object, _settings);
|
||||
_settings.Current.General.AuthenticationType = AuthenticationType.UserNamePassword;
|
||||
_handler = new(_authenticationMock.Object, _httpContextAccessorMock.Object);
|
||||
SettingData.Get.General.AuthenticationType = AuthenticationType.UserNamePassword;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_AuthNone_Succeeds()
|
||||
{
|
||||
// Arrange
|
||||
_settings.Current.General.AuthenticationType = AuthenticationType.None;
|
||||
SettingData.Get.General.AuthenticationType = AuthenticationType.None;
|
||||
var context = CreateContext();
|
||||
|
||||
// Act
|
||||
|
|
@ -43,8 +42,7 @@ public class SabnzbdHandlerTest
|
|||
public async Task HandleAsync_ValidCredentials_Succeeds()
|
||||
{
|
||||
// Arrange
|
||||
_settings.Current.General.AuthenticationType = AuthenticationType.UserNamePassword;
|
||||
|
||||
Settings.Get.General.AuthenticationType = AuthenticationType.UserNamePassword;
|
||||
var httpContext = new DefaultHttpContext
|
||||
{
|
||||
Request =
|
||||
|
|
@ -65,119 +63,11 @@ public class SabnzbdHandlerTest
|
|||
Assert.True(context.HasSucceeded, "HasSucceeded should be true for valid credentials");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_ValidApiKeyCredentials_Succeeds()
|
||||
{
|
||||
// Arrange
|
||||
_settings.Current.General.AuthenticationType = AuthenticationType.UserNamePassword;
|
||||
|
||||
var httpContext = new DefaultHttpContext
|
||||
{
|
||||
Request =
|
||||
{
|
||||
QueryString = new("?apikey=user:pass")
|
||||
}
|
||||
};
|
||||
|
||||
_httpContextAccessorMock.Setup(a => a.HttpContext).Returns(httpContext);
|
||||
|
||||
var context = CreateContext(httpContext);
|
||||
_authenticationMock.Setup(a => a.Login("user", "pass")).ReturnsAsync(SignInResult.Success);
|
||||
|
||||
// Act
|
||||
await _handler.HandleAsync(context);
|
||||
|
||||
// Assert
|
||||
Assert.True(context.HasSucceeded, "HasSucceeded should be true for valid api key credentials");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_ValidApiKeyCredentialsFromForm_Succeeds()
|
||||
{
|
||||
// Arrange
|
||||
_settings.Current.General.AuthenticationType = AuthenticationType.UserNamePassword;
|
||||
var httpContext = new DefaultHttpContext();
|
||||
httpContext.Request.ContentType = "application/x-www-form-urlencoded";
|
||||
|
||||
httpContext.Request.Form = new FormCollection(new()
|
||||
{
|
||||
{
|
||||
"apikey", "user:pass"
|
||||
}
|
||||
});
|
||||
|
||||
_httpContextAccessorMock.Setup(a => a.HttpContext).Returns(httpContext);
|
||||
|
||||
var context = CreateContext(httpContext);
|
||||
_authenticationMock.Setup(a => a.Login("user", "pass")).ReturnsAsync(SignInResult.Success);
|
||||
|
||||
// Act
|
||||
await _handler.HandleAsync(context);
|
||||
|
||||
// Assert
|
||||
Assert.True(context.HasSucceeded, "HasSucceeded should be true for valid form api key credentials");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_ApiKeyPasswordContainingColon_Succeeds()
|
||||
{
|
||||
// Arrange
|
||||
_settings.Current.General.AuthenticationType = AuthenticationType.UserNamePassword;
|
||||
|
||||
var httpContext = new DefaultHttpContext
|
||||
{
|
||||
Request =
|
||||
{
|
||||
QueryString = new("?apikey=user:pass:with:colons")
|
||||
}
|
||||
};
|
||||
|
||||
_httpContextAccessorMock.Setup(a => a.HttpContext).Returns(httpContext);
|
||||
|
||||
var context = CreateContext(httpContext);
|
||||
_authenticationMock.Setup(a => a.Login("user", "pass:with:colons")).ReturnsAsync(SignInResult.Success);
|
||||
|
||||
// Act
|
||||
await _handler.HandleAsync(context);
|
||||
|
||||
// Assert
|
||||
Assert.True(context.HasSucceeded, "HasSucceeded should be true when the password contains colons");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_MaCredentialsTakePrecedenceOverApiKey()
|
||||
{
|
||||
// Arrange
|
||||
_settings.Current.General.AuthenticationType = AuthenticationType.UserNamePassword;
|
||||
|
||||
var httpContext = new DefaultHttpContext
|
||||
{
|
||||
Request =
|
||||
{
|
||||
QueryString = new("?ma_username=user&ma_password=wrong&apikey=user:pass")
|
||||
}
|
||||
};
|
||||
|
||||
_httpContextAccessorMock.Setup(a => a.HttpContext).Returns(httpContext);
|
||||
|
||||
var context = CreateContext(httpContext);
|
||||
_authenticationMock.Setup(a => a.Login("user", "wrong")).ReturnsAsync(SignInResult.Failed);
|
||||
_authenticationMock.Setup(a => a.Login("user", "pass")).ReturnsAsync(SignInResult.Success);
|
||||
|
||||
// Act
|
||||
await _handler.HandleAsync(context);
|
||||
|
||||
// Assert
|
||||
Assert.False(context.HasSucceeded, "HasSucceeded should be false because ma_username/ma_password take precedence");
|
||||
_authenticationMock.Verify(a => a.Login("user", "wrong"), Times.Once);
|
||||
_authenticationMock.Verify(a => a.Login("user", "pass"), Times.Never);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_AlreadyAuthenticated_Succeeds()
|
||||
{
|
||||
// Arrange
|
||||
_settings.Current.General.AuthenticationType = AuthenticationType.UserNamePassword;
|
||||
Settings.Get.General.AuthenticationType = AuthenticationType.UserNamePassword;
|
||||
var httpContext = new DefaultHttpContext();
|
||||
var claimsPrincipal = new ClaimsPrincipal(new ClaimsIdentity("TestAuth"));
|
||||
httpContext.User = claimsPrincipal;
|
||||
|
|
@ -196,8 +86,7 @@ public class SabnzbdHandlerTest
|
|||
public async Task HandleAsync_InvalidCredentials_DoesNotSucceed()
|
||||
{
|
||||
// Arrange
|
||||
_settings.Current.General.AuthenticationType = AuthenticationType.UserNamePassword;
|
||||
|
||||
Settings.Get.General.AuthenticationType = AuthenticationType.UserNamePassword;
|
||||
var httpContext = new DefaultHttpContext
|
||||
{
|
||||
Request =
|
||||
|
|
@ -218,66 +107,11 @@ public class SabnzbdHandlerTest
|
|||
Assert.False(context.HasSucceeded, "HasSucceeded should be false for invalid credentials");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_InvalidApiKeyCredentials_DoesNotSucceed()
|
||||
{
|
||||
// Arrange
|
||||
_settings.Current.General.AuthenticationType = AuthenticationType.UserNamePassword;
|
||||
|
||||
var httpContext = new DefaultHttpContext
|
||||
{
|
||||
Request =
|
||||
{
|
||||
QueryString = new("?apikey=user:wrong")
|
||||
}
|
||||
};
|
||||
|
||||
_httpContextAccessorMock.Setup(a => a.HttpContext).Returns(httpContext);
|
||||
|
||||
var context = CreateContext(httpContext);
|
||||
_authenticationMock.Setup(a => a.Login("user", "wrong")).ReturnsAsync(SignInResult.Failed);
|
||||
|
||||
// Act
|
||||
await _handler.HandleAsync(context);
|
||||
|
||||
// Assert
|
||||
Assert.False(context.HasSucceeded, "HasSucceeded should be false for invalid api key credentials");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("missingdelimiter")]
|
||||
[InlineData(":pass")]
|
||||
[InlineData("user:")]
|
||||
public async Task HandleAsync_MalformedApiKey_DoesNotSucceed(String apiKey)
|
||||
{
|
||||
// Arrange
|
||||
_settings.Current.General.AuthenticationType = AuthenticationType.UserNamePassword;
|
||||
|
||||
var httpContext = new DefaultHttpContext
|
||||
{
|
||||
Request =
|
||||
{
|
||||
QueryString = new($"?apikey={apiKey}")
|
||||
}
|
||||
};
|
||||
|
||||
_httpContextAccessorMock.Setup(a => a.HttpContext).Returns(httpContext);
|
||||
|
||||
var context = CreateContext(httpContext);
|
||||
|
||||
// Act
|
||||
await _handler.HandleAsync(context);
|
||||
|
||||
// Assert
|
||||
Assert.False(context.HasSucceeded, "HasSucceeded should be false for malformed api keys");
|
||||
_authenticationMock.Verify(a => a.Login(It.IsAny<String>(), It.IsAny<String>()), Times.Never);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_MissingCredentials_DoesNotSucceed()
|
||||
{
|
||||
// Arrange
|
||||
_settings.Current.General.AuthenticationType = AuthenticationType.UserNamePassword;
|
||||
Settings.Get.General.AuthenticationType = AuthenticationType.UserNamePassword;
|
||||
var httpContext = new DefaultHttpContext();
|
||||
_httpContextAccessorMock.Setup(a => a.HttpContext).Returns(httpContext);
|
||||
|
||||
|
|
|
|||
|
|
@ -17,7 +17,7 @@ public class TorrentsControllerNzbTest
|
|||
|
||||
public TorrentsControllerNzbTest()
|
||||
{
|
||||
_torrentsMock = new(null!, null!, null!, null!, null!, null!, null!, null!, null!, null!, null!, new TestSettings(), new TorrentRunnerState());
|
||||
_torrentsMock = new(null!, null!, null!, null!, null!, null!, null!, null!, null!, null!, null!);
|
||||
_loggerMock = new();
|
||||
_coordinatorMock = new();
|
||||
_controller = new(_loggerMock.Object, _torrentsMock.Object, null!, _coordinatorMock.Object);
|
||||
|
|
|
|||
|
|
@ -1 +0,0 @@
|
|||
[assembly: CollectionBehavior(DisableTestParallelization = true)]
|
||||
|
|
@ -5,13 +5,12 @@
|
|||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<IsPackable>false</IsPackable>
|
||||
<IsTestProject>true</IsTestProject>
|
||||
<AssemblyName>RdtClient.Web.Test</AssemblyName>
|
||||
<RootNamespace>RdtClient.Web.Test</RootNamespace>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.6.0" />
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.4.0" />
|
||||
<PackageReference Include="Moq" Version="4.20.72" />
|
||||
<PackageReference Include="SharpCompress" Version="[0.42.1]" />
|
||||
<PackageReference Include="xunit" Version="2.9.3" />
|
||||
|
|
|
|||
|
|
@ -1,59 +0,0 @@
|
|||
using RdtClient.Data.Models.Internal;
|
||||
using RdtClient.Service.Services;
|
||||
|
||||
namespace RdtClient.Web.Test;
|
||||
|
||||
internal sealed class TestSettings(DbSettings? settings = null) : ISettings
|
||||
{
|
||||
public DbSettings Current { get; } = settings ?? new();
|
||||
|
||||
public String DefaultSavePath
|
||||
{
|
||||
get
|
||||
{
|
||||
var downloadPath = Current.DownloadClient.MappedPath.TrimEnd('\\').TrimEnd('/');
|
||||
|
||||
return downloadPath + Path.DirectorySeparatorChar;
|
||||
}
|
||||
}
|
||||
|
||||
public IList<SettingProperty> GetAll()
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
public Task Update(IList<SettingProperty> settings)
|
||||
{
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public Task Update(String settingId, Object? value)
|
||||
{
|
||||
SetValue(Current, settingId.Split(':'), 0, value);
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
private static void SetValue(Object target, IReadOnlyList<String> path, Int32 index, Object? value)
|
||||
{
|
||||
var property = target.GetType().GetProperty(path[index]) ?? throw new($"Unknown setting {String.Join(":", path)}");
|
||||
|
||||
if (index < path.Count - 1)
|
||||
{
|
||||
SetValue(property.GetValue(target)!, path, index + 1, value);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (value == null)
|
||||
{
|
||||
property.SetValue(target, null);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
var propertyType = Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType;
|
||||
var convertedValue = propertyType.IsEnum ? Enum.Parse(propertyType, value.ToString()!) : Convert.ChangeType(value, propertyType);
|
||||
property.SetValue(target, convertedValue);
|
||||
}
|
||||
}
|
||||
|
|
@ -6,14 +6,14 @@ using RdtClient.Service.Services;
|
|||
namespace RdtClient.Web.Controllers;
|
||||
|
||||
[Route("Api/Authentication")]
|
||||
public class AuthController(Authentication authentication, ISettings settings) : Controller
|
||||
public class AuthController(Authentication authentication, Settings settings) : Controller
|
||||
{
|
||||
[AllowAnonymous]
|
||||
[Route("IsLoggedIn")]
|
||||
[HttpGet]
|
||||
public async Task<ActionResult> IsLoggedIn()
|
||||
{
|
||||
if (settings.Current.General.AuthenticationType == AuthenticationType.None)
|
||||
if (Settings.Get.General.AuthenticationType == AuthenticationType.None)
|
||||
{
|
||||
return Ok();
|
||||
}
|
||||
|
|
@ -77,7 +77,7 @@ public class AuthController(Authentication authentication, ISettings settings) :
|
|||
return BadRequest();
|
||||
}
|
||||
|
||||
if (!String.IsNullOrEmpty(settings.Current.Provider.ApiKey))
|
||||
if (!String.IsNullOrEmpty(Settings.Get.Provider.ApiKey))
|
||||
{
|
||||
return StatusCode(401);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@ using Microsoft.AspNetCore.Mvc;
|
|||
using RdtClient.Data.Enums;
|
||||
using RdtClient.Data.Models.QBittorrent;
|
||||
using RdtClient.Service.Services;
|
||||
using Torrent = RdtClient.Data.Models.Data.Torrent;
|
||||
using RealDebridException = RDNET.RealDebridException;
|
||||
|
||||
namespace RdtClient.Web.Controllers;
|
||||
|
||||
|
|
@ -14,8 +14,7 @@ namespace RdtClient.Web.Controllers;
|
|||
[ApiController]
|
||||
[Route("api/v2")]
|
||||
[Route("qbittorrent/api/v2")]
|
||||
public class QBittorrentController(ILogger<QBittorrentController> logger, QBittorrent qBittorrent, IHttpClientFactory httpClientFactory, ISettings settings, Torrents torrents)
|
||||
: Controller
|
||||
public class QBittorrentController(ILogger<QBittorrentController> logger, QBittorrent qBittorrent, IHttpClientFactory httpClientFactory) : Controller
|
||||
{
|
||||
[AllowAnonymous]
|
||||
[Route("/version/api")]
|
||||
|
|
@ -34,7 +33,7 @@ public class QBittorrentController(ILogger<QBittorrentController> logger, QBitto
|
|||
{
|
||||
logger.LogDebug($"Auth login");
|
||||
|
||||
if (settings.Current.General.AuthenticationType == AuthenticationType.None)
|
||||
if (Settings.Get.General.AuthenticationType == AuthenticationType.None)
|
||||
{
|
||||
return Content("Ok.", "text/plain");
|
||||
}
|
||||
|
|
@ -147,7 +146,7 @@ public class QBittorrentController(ILogger<QBittorrentController> logger, QBitto
|
|||
[HttpPost]
|
||||
public ActionResult<AppPreferences> AppDefaultSavePath()
|
||||
{
|
||||
var result = settings.DefaultSavePath;
|
||||
var result = Settings.AppDefaultSavePath;
|
||||
|
||||
return Ok(result);
|
||||
}
|
||||
|
|
@ -369,28 +368,30 @@ public class QBittorrentController(ILogger<QBittorrentController> logger, QBitto
|
|||
|
||||
foreach (var url in urls)
|
||||
{
|
||||
Torrent? torrent;
|
||||
|
||||
if (url.StartsWith("magnet"))
|
||||
try
|
||||
{
|
||||
torrent = await qBittorrent.TorrentsAddMagnet(url.Trim(), request.Category, null);
|
||||
if (url.StartsWith("magnet"))
|
||||
{
|
||||
await qBittorrent.TorrentsAddMagnet(url.Trim(), request.Category, null);
|
||||
}
|
||||
else if (url.StartsWith("http"))
|
||||
{
|
||||
var httpClient = httpClientFactory.CreateClient();
|
||||
var result = await httpClient.GetByteArrayAsync(url);
|
||||
await qBittorrent.TorrentsAddFile(result, request.Category, null);
|
||||
}
|
||||
else
|
||||
{
|
||||
return BadRequest($"Invalid torrent link format {url}");
|
||||
}
|
||||
}
|
||||
else if (url.StartsWith("http"))
|
||||
catch (RealDebridException ex)
|
||||
{
|
||||
var httpClient = httpClientFactory.CreateClient();
|
||||
var result = await httpClient.GetByteArrayAsync(url);
|
||||
torrent = await qBittorrent.TorrentsAddFile(result, request.Category, null);
|
||||
}
|
||||
else
|
||||
{
|
||||
return BadRequest($"Invalid torrent link format {url}");
|
||||
}
|
||||
|
||||
var addResult = await WaitForTorrent(torrent.TorrentId);
|
||||
|
||||
if (!addResult)
|
||||
{
|
||||
return Ok("Fails.");
|
||||
// Infringing file.
|
||||
if (ex.ErrorCode == 35)
|
||||
{
|
||||
return Ok("Fails.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -411,14 +412,7 @@ public class QBittorrentController(ILogger<QBittorrentController> logger, QBitto
|
|||
await file.CopyToAsync(target);
|
||||
var fileBytes = target.ToArray();
|
||||
|
||||
var torrent = await qBittorrent.TorrentsAddFile(fileBytes, request.Category, request.Priority);
|
||||
|
||||
var addResult = await WaitForTorrent(torrent.TorrentId);
|
||||
|
||||
if (!addResult)
|
||||
{
|
||||
return Ok("Fails.");
|
||||
}
|
||||
await qBittorrent.TorrentsAddFile(fileBytes, request.Category, request.Priority);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -441,11 +435,11 @@ public class QBittorrentController(ILogger<QBittorrentController> logger, QBitto
|
|||
}
|
||||
|
||||
var fileIds = request.Id
|
||||
.Split('|', StringSplitOptions.RemoveEmptyEntries)
|
||||
.Select(value => Int32.TryParse(value, out var parsedValue) ? parsedValue : (Int32?)null)
|
||||
.Where(value => value.HasValue)
|
||||
.Select(value => value!.Value)
|
||||
.ToList();
|
||||
.Split('|', StringSplitOptions.RemoveEmptyEntries)
|
||||
.Select(value => Int32.TryParse(value, out var parsedValue) ? parsedValue : (Int32?)null)
|
||||
.Where(value => value.HasValue)
|
||||
.Select(value => value!.Value)
|
||||
.ToList();
|
||||
|
||||
if (fileIds.Count == 0)
|
||||
{
|
||||
|
|
@ -619,7 +613,7 @@ public class QBittorrentController(ILogger<QBittorrentController> logger, QBitto
|
|||
[HttpGet]
|
||||
public ActionResult TransferInfo()
|
||||
{
|
||||
return Ok(qBittorrent.TransferInfo());
|
||||
return Ok(QBittorrent.TransferInfo());
|
||||
}
|
||||
|
||||
[Authorize(Policy = "AuthSetting")]
|
||||
|
|
@ -677,31 +671,6 @@ public class QBittorrentController(ILogger<QBittorrentController> logger, QBitto
|
|||
_ => String.Equals(torrent.State, filter, StringComparison.OrdinalIgnoreCase)
|
||||
};
|
||||
}
|
||||
|
||||
private async Task<Boolean> WaitForTorrent(Guid torrentId)
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
var torrent = await torrents.GetById(torrentId);
|
||||
|
||||
if (torrent == null)
|
||||
{
|
||||
throw new($"Failed to add torrent: Not Found");
|
||||
}
|
||||
|
||||
if (torrent.RdStatus == TorrentStatus.Error || torrent.Error != null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (torrent.RdStatus != TorrentStatus.Queued)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
await Task.Delay(1000);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public class QBAuthLoginRequest
|
||||
|
|
@ -717,6 +686,7 @@ public class QBTorrentsInfoRequest
|
|||
public String? Hashes { get; set; }
|
||||
}
|
||||
|
||||
|
||||
public class QBTorrentsCountRequest
|
||||
{
|
||||
public String? Filter { get; set; }
|
||||
|
|
|
|||
|
|
@ -56,7 +56,22 @@ public class SabnzbdController(ILogger<SabnzbdController> logger, Sabnzbd sabnzb
|
|||
|
||||
if (name == "delete")
|
||||
{
|
||||
return await DeleteDownloads();
|
||||
var value = GetParam("value");
|
||||
|
||||
if (String.IsNullOrWhiteSpace(value))
|
||||
{
|
||||
return BadRequest(new SabnzbdResponse
|
||||
{
|
||||
Error = "No value specified for delete operation"
|
||||
});
|
||||
}
|
||||
|
||||
await sabnzbd.Delete(value ?? "");
|
||||
|
||||
return Ok(new SabnzbdResponse
|
||||
{
|
||||
Status = true
|
||||
});
|
||||
}
|
||||
|
||||
return Ok(new SabnzbdResponse
|
||||
|
|
@ -70,12 +85,6 @@ public class SabnzbdController(ILogger<SabnzbdController> logger, Sabnzbd sabnzb
|
|||
public async Task<ActionResult> History()
|
||||
{
|
||||
logger.LogDebug("Sabnzbd mode: history");
|
||||
var name = GetParam("name");
|
||||
|
||||
if (name == "delete")
|
||||
{
|
||||
return await DeleteDownloads();
|
||||
}
|
||||
|
||||
return Ok(new SabnzbdResponse
|
||||
{
|
||||
|
|
@ -174,31 +183,6 @@ public class SabnzbdController(ILogger<SabnzbdController> logger, Sabnzbd sabnzb
|
|||
});
|
||||
}
|
||||
|
||||
private async Task<ActionResult> DeleteDownloads()
|
||||
{
|
||||
var value = GetParam("value");
|
||||
|
||||
if (String.IsNullOrWhiteSpace(value))
|
||||
{
|
||||
return BadRequest(new SabnzbdResponse
|
||||
{
|
||||
Error = "No value specified for delete operation"
|
||||
});
|
||||
}
|
||||
|
||||
var deleteFiles = IsTrue(GetParam("del_files"));
|
||||
|
||||
foreach (var hash in value.Split(",", StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
|
||||
{
|
||||
await sabnzbd.Delete(hash, deleteFiles);
|
||||
}
|
||||
|
||||
return Ok(new SabnzbdResponse
|
||||
{
|
||||
Status = true
|
||||
});
|
||||
}
|
||||
|
||||
private String? GetParam(String name)
|
||||
{
|
||||
var value = Request.Query[name].ToString();
|
||||
|
|
@ -210,9 +194,4 @@ public class SabnzbdController(ILogger<SabnzbdController> logger, Sabnzbd sabnzb
|
|||
|
||||
return value;
|
||||
}
|
||||
|
||||
private static Boolean IsTrue(String? value)
|
||||
{
|
||||
return value is "1" || Boolean.TryParse(value, out var result) && result;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ using System.Reflection;
|
|||
using Aria2NET;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using RdtClient.Data.Data;
|
||||
using RdtClient.Data.Models.Data;
|
||||
using RdtClient.Data.Models.Internal;
|
||||
using RdtClient.Service.Helpers;
|
||||
|
|
@ -14,13 +15,13 @@ namespace RdtClient.Web.Controllers;
|
|||
|
||||
[Authorize(Policy = "AuthSetting")]
|
||||
[Route("Api/Settings")]
|
||||
public class SettingsController(ISettings settings, Torrents torrents) : Controller
|
||||
public class SettingsController(Settings settings, Torrents torrents) : Controller
|
||||
{
|
||||
[HttpGet]
|
||||
[Route("")]
|
||||
public ActionResult Get()
|
||||
{
|
||||
var result = settings.GetAll();
|
||||
var result = SettingData.GetAll();
|
||||
|
||||
return Ok(result);
|
||||
}
|
||||
|
|
@ -94,7 +95,7 @@ public class SettingsController(ISettings settings, Torrents torrents) : Control
|
|||
[Route("TestDownloadSpeed")]
|
||||
public async Task<ActionResult> TestDownloadSpeed(CancellationToken cancellationToken)
|
||||
{
|
||||
var downloadPath = settings.Current.DownloadClient.DownloadPath;
|
||||
var downloadPath = Settings.Get.DownloadClient.DownloadPath;
|
||||
|
||||
var testFilePath = Path.Combine(downloadPath, "testDefault.rar");
|
||||
|
||||
|
|
@ -105,7 +106,7 @@ public class SettingsController(ISettings settings, Torrents torrents) : Control
|
|||
Link = "https://34.download.real-debrid.com/speedtest/testDefault.rar",
|
||||
Torrent = new()
|
||||
{
|
||||
DownloadClient = settings.Current.DownloadClient.Client == DownloadClient.Symlink ? DownloadClient.Bezzad : settings.Current.DownloadClient.Client,
|
||||
DownloadClient = Settings.Get.DownloadClient.Client == DownloadClient.Symlink ? DownloadClient.Bezzad : Settings.Get.DownloadClient.Client,
|
||||
RdName = "testDefault.rar"
|
||||
}
|
||||
};
|
||||
|
|
@ -130,7 +131,7 @@ public class SettingsController(ISettings settings, Torrents torrents) : Control
|
|||
|
||||
if (downloadClient.Downloader is Aria2cDownloader aria2Downloader)
|
||||
{
|
||||
var aria2NetClient = new Aria2NetClient(settings.Current.DownloadClient.Aria2cUrl, settings.Current.DownloadClient.Aria2cSecret, httpClient, 1);
|
||||
var aria2NetClient = new Aria2NetClient(Settings.Get.DownloadClient.Aria2cUrl, Settings.Get.DownloadClient.Aria2cSecret, httpClient, 1);
|
||||
|
||||
var allDownloads = await aria2NetClient.TellAllAsync(cancellationToken);
|
||||
|
||||
|
|
@ -154,7 +155,7 @@ public class SettingsController(ISettings settings, Torrents torrents) : Control
|
|||
[Route("TestWriteSpeed")]
|
||||
public async Task<ActionResult> TestWriteSpeed()
|
||||
{
|
||||
var downloadPath = settings.Current.DownloadClient.DownloadPath;
|
||||
var downloadPath = Settings.Get.DownloadClient.DownloadPath;
|
||||
|
||||
var testFilePath = Path.Combine(downloadPath, "test.tmp");
|
||||
|
||||
|
|
|
|||
|
|
@ -30,14 +30,14 @@
|
|||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.AspNetCore.SpaServices.Extensions" Version="10.0.8" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="10.0.8" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite.Core" Version="10.0.8" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="10.0.8">
|
||||
<PackageReference Include="Microsoft.AspNetCore.SpaServices.Extensions" Version="10.0.7" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="10.0.7" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite.Core" Version="10.0.7" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="10.0.7">
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="Microsoft.Extensions.Hosting.WindowsServices" Version="10.0.8" />
|
||||
<PackageReference Include="Microsoft.Extensions.Hosting.WindowsServices" Version="10.0.7" />
|
||||
<PackageReference Include="Serilog" Version="4.3.1" />
|
||||
<PackageReference Include="Serilog.AspNetCore" Version="10.0.0" />
|
||||
<PackageReference Include="Serilog.Sinks.File" Version="7.0.0" />
|
||||
|
|
|
|||
Loading…
Reference in a new issue