Skip to content

Commit

Permalink
增加对Transmission的支持
Browse files Browse the repository at this point in the history
  • Loading branch information
kaedei committed Jun 24, 2020
1 parent 25e6417 commit 352fc78
Show file tree
Hide file tree
Showing 9 changed files with 154 additions and 14 deletions.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using ResourceMonitor.Services.Implementation;

namespace ResourceMonitor.Test
{
[TestClass]
public class TransmissionDownloaderTests
{
IConfigurationRoot configuration = new ConfigurationBuilder()
.AddInMemoryCollection(new Dictionary<string, string>
{
{"Transmission:Url", "http://localhost:9091/transmission/rpc"},
{"Transmission:Login", "admin"},
{"Transmission:Password", "admin"}
})
.Build();

[TestMethod]
public async Task TryConnect()
{
var downloader = new TransmissionDownloader(configuration, new NullLogger<TransmissionDownloader>());
Assert.IsTrue(await downloader.TryConnect());
}

[TestMethod]
public async Task GetAllTasks()
{
var downloader = new TransmissionDownloader(configuration, new NullLogger<TransmissionDownloader>());
var tasks = await downloader.GetAllTasks();
foreach (var task in tasks)
{
Debug.WriteLine(task.ToString());
}
}

[TestMethod]
public async Task AddNewTorrentTask()
{
var downloader = new TransmissionDownloader(configuration, new NullLogger<TransmissionDownloader>());
var torrentBytes = File.ReadAllBytes("valid.torrent");
await downloader.AddNewTorrentTask(torrentBytes);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,10 @@ public class DownloaderTask
public string Id { get; set; }
public string Magnet { get; set; }
public string Name { get; set; }

public override string ToString()
{
return $"{nameof(Id)}: {Id}, {nameof(Magnet)}: {Magnet}, {nameof(Name)}: {Name}";
}
}
}
2 changes: 1 addition & 1 deletion ResourceMonitor/ResourceMonitor/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ public class Program
public static int Main(string[] args)
{
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Information()
.MinimumLevel.Debug()
.MinimumLevel.Override("Microsoft", LogEventLevel.Information)
.MinimumLevel.Override("Microsoft.AspNetCore", LogEventLevel.Warning)
.Enrich.FromLogContext()
Expand Down
1 change: 1 addition & 0 deletions ResourceMonitor/ResourceMonitor/ResourceMonitor.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
<PackageReference Include="Refit.HttpClientFactory" Version="5.1.67" />
<PackageReference Include="Serilog.AspNetCore" Version="3.2.0" />
<PackageReference Include="Serilog.Sinks.RollingFile" Version="3.3.0" />
<PackageReference Include="Transmission.API.RPC" Version="2.1.2" />
</ItemGroup>


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,8 @@ private async Task DownloadRule(AutoDownloadRule rule)
.ToArray();

//进一步根据条件过滤
filtered = FilterResources(filtered, rule.chooseNewerIfDuplicate, rule.limitFileSize, true);
filtered = FilterResources(filtered, rule.chooseNewerIfDuplicate, rule.limitFileSize,
_configuration["LogDetails"] == "true");
//获取前 n 个结果
filtered = filtered.Take(rule.maxCount).ToArray();

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using ResourceMonitor.Models.Downloader;
using ResourceMonitor.Services.Declaration;
using Transmission.API.RPC;
using Transmission.API.RPC.Entity;

namespace ResourceMonitor.Services.Implementation
{
public class TransmissionDownloader : IDownloader
{
private readonly ILogger<TransmissionDownloader> _logger;
private readonly Client _client;


public TransmissionDownloader(IConfiguration configuration, ILogger<TransmissionDownloader> logger)
{
_logger = logger;
_client = new Client(
configuration["Transmission:Url"],
Guid.NewGuid().ToString("N"),
configuration["Transmission:Login"],
configuration["Transmission:Password"]);
}

public async Task<bool> TryConnect()
{
_logger.LogInformation("尝试连接到 Transmission");
try
{
var info = await _client.GetSessionInformationAsync();
_logger.LogInformation($"连接到 Transmission 成功。版本 {info.Version}。RPC版本 {info.RpcVersion}");
return true;
}
catch (Exception ex)
{
_logger.LogWarning(ex, "连接到 Transmission 失败");
return false;
}
}

public async Task<List<DownloaderTask>> GetAllTasks()
{
_logger.LogDebug("获取 Transmission 所有任务的状态");
var tasks = await _client.TorrentGetAsync(TorrentFields.ALL_FIELDS);
return tasks?.Torrents?.Select(t => new DownloaderTask
{
Id = t.HashString,
Magnet = t.MagnetLink,
Name = t.Name
}).ToList() ?? new List<DownloaderTask>(0);
}

public async Task<bool> IfTaskExists(string id, string url)
{
var allTasks = await GetAllTasks();
return allTasks.Any(t => t.Id.Equals(id, StringComparison.InvariantCultureIgnoreCase));
}

public async Task AddNewTorrentTask(byte[] torrentBytes)
{
var newTorrentInfo = await _client.TorrentAddAsync(new NewTorrent
{
Metainfo = Convert.ToBase64String(torrentBytes),
Paused = false
});
if (newTorrentInfo == null || newTorrentInfo.ID == 0)
{
throw new Exception("在 Transmission 上建立任务失败");
}

_logger.LogInformation($"在 Transmission 上建立任务成功。ID={newTorrentInfo.ID}");
}
}
}
12 changes: 7 additions & 5 deletions ResourceMonitor/ResourceMonitor/Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,12 +32,14 @@ public Startup(IConfiguration configuration)
public void ConfigureServices(IServiceCollection services)
{
services.AddHttpClient();
if (Configuration["Downloader"] == "aria2")
{
services.AddSingleton<IDownloader, Aria2Downloader>();
}
else if (Configuration["Downloader"] == "transmission")
switch (Configuration["Downloader"]?.ToLowerInvariant())
{
case "aria2":
services.AddSingleton<IDownloader, Aria2Downloader>();
break;
case "transmission":
services.AddSingleton<IDownloader, TransmissionDownloader>();
break;
}

services.AddHostedService<SyncRulesBackgroundService>();
Expand Down
13 changes: 6 additions & 7 deletions ResourceMonitor/ResourceMonitor/appsettings.json
Original file line number Diff line number Diff line change
@@ -1,11 +1,5 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"LogDetails": false,
"AllowedHosts": "*",
"Api": {
"ApiBaseUrl": "https://api.acplay.net",
Expand All @@ -21,5 +15,10 @@
"Aria2": {
"Url": "http://localhost:6800/jsonrpc",
"Token": "token"
},
"Transmission": {
"Url": "http://localhost:9091/transmission/rpc",
"Login": "admin",
"Password": "admin"
}
}

0 comments on commit 352fc78

Please sign in to comment.