1
0
mirror of https://github.com/Radarr/Radarr.git synced 2024-11-04 10:02:40 +01:00

NzbGet now uses RestSharp

This commit is contained in:
Mark McDowall 2013-12-01 01:44:33 -08:00
parent 39bb2ce80a
commit 53cebdee17
8 changed files with 174 additions and 104 deletions

View File

@ -22,14 +22,6 @@ public class DownloadNzbFixture : CoreTest
[SetUp] [SetUp]
public void Setup() public void Setup()
{ {
var fakeConfig = Mocker.GetMock<IConfigService>();
fakeConfig.SetupGet(c => c.NzbgetHost).Returns("192.168.5.55");
fakeConfig.SetupGet(c => c.NzbgetPort).Returns(6789);
fakeConfig.SetupGet(c => c.NzbgetUsername).Returns("nzbget");
fakeConfig.SetupGet(c => c.NzbgetPassword).Returns("pass");
fakeConfig.SetupGet(c => c.NzbgetTvCategory).Returns("TV");
fakeConfig.SetupGet(c => c.NzbgetRecentTvPriority).Returns(PriorityType.High);
_remoteEpisode = new RemoteEpisode(); _remoteEpisode = new RemoteEpisode();
_remoteEpisode.Release = new ReleaseInfo(); _remoteEpisode.Release = new ReleaseInfo();
_remoteEpisode.Release.Title = _title; _remoteEpisode.Release.Title = _title;
@ -42,37 +34,19 @@ public void Setup()
.ToList(); .ToList();
} }
private void WithFailResponse()
{
Mocker.GetMock<IHttpProvider>()
.Setup(s => s.PostCommand("192.168.5.55:6789", "nzbget", "pass", It.IsAny<String>()))
.Returns(ReadAllText("Files", "Nzbget", "JsonError.txt"));
}
[Test] [Test]
public void should_add_item_to_queue() public void should_add_item_to_queue()
{ {
var p = new object[] {"30.Rock.S01E01.Pilot.720p.hdtv.nzb", "TV", 50, false, "http://www.nzbdrone.com"};
var command = new JsonRequest Mocker.GetMock<INzbGetCommunicationProxy>()
{ .Setup(s => s.AddNzb(p))
Method = "appendurl", .Returns(true);
Params = new object[] { "30.Rock.S01E01.Pilot.720p.hdtv.nzb", "TV", 50, false, "http://www.nzbdrone.com" }
};
Mocker.GetMock<IHttpProvider>()
.Setup(s => s.PostCommand("192.168.5.55:6789", "nzbget", "pass",
It.Is<String>(c => c.Equals(command.ToJson()))))
.Returns("{\"version\": \"1.1\",\"result\": true}");
Mocker.Resolve<NzbgetClient>().DownloadNzb(_remoteEpisode); Mocker.Resolve<NzbgetClient>().DownloadNzb(_remoteEpisode);
}
[Test] Mocker.GetMock<INzbGetCommunicationProxy>()
public void should_throw_when_error_is_returned() .Verify(v => v.AddNzb(It.IsAny<object []>()), Times.Once());
{
WithFailResponse();
Assert.Throws<ApplicationException>(() => Mocker.Resolve<NzbgetClient>().DownloadNzb(_remoteEpisode));
} }
} }
} }

View File

@ -1,9 +1,10 @@
using System; using System;
using System.Collections.Generic;
using System.Linq;
using FizzWare.NBuilder;
using FluentAssertions; using FluentAssertions;
using Moq; using Moq;
using NUnit.Framework; using NUnit.Framework;
using NzbDrone.Common;
using NzbDrone.Core.Configuration;
using NzbDrone.Core.Download.Clients.Nzbget; using NzbDrone.Core.Download.Clients.Nzbget;
using NzbDrone.Core.Parser; using NzbDrone.Core.Parser;
using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Parser.Model;
@ -14,37 +15,30 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.NzbgetProviderTests
{ {
public class QueueFixture : CoreTest<NzbgetClient> public class QueueFixture : CoreTest<NzbgetClient>
{ {
private List<NzbGetQueueItem> _queue;
[SetUp] [SetUp]
public void Setup() public void Setup()
{ {
var fakeConfig = Mocker.GetMock<IConfigService>(); _queue = Builder<NzbGetQueueItem>.CreateListOfSize(5)
fakeConfig.SetupGet(c => c.NzbgetHost).Returns("192.168.5.55"); .All()
fakeConfig.SetupGet(c => c.NzbgetPort).Returns(6789); .With(q => q.NzbName = "30.Rock.S01E01.Pilot.720p.hdtv.nzb")
fakeConfig.SetupGet(c => c.NzbgetUsername).Returns("nzbget"); .Build()
fakeConfig.SetupGet(c => c.NzbgetPassword).Returns("pass"); .ToList();
fakeConfig.SetupGet(c => c.NzbgetTvCategory).Returns("TV");
fakeConfig.SetupGet(c => c.NzbgetRecentTvPriority).Returns(PriorityType.High);
} }
private void WithFullQueue() private void WithFullQueue()
{ {
Mocker.GetMock<IHttpProvider>() Mocker.GetMock<INzbGetCommunicationProxy>()
.Setup(s => s.PostCommand("192.168.5.55:6789", "nzbget", "pass", It.IsAny<String>())) .Setup(s => s.GetQueue())
.Returns(ReadAllText("Files", "Nzbget", "Queue.txt")); .Returns(_queue);
} }
private void WithEmptyQueue() private void WithEmptyQueue()
{ {
Mocker.GetMock<IHttpProvider>() Mocker.GetMock<INzbGetCommunicationProxy>()
.Setup(s => s.PostCommand("192.168.5.55:6789", "nzbget", "pass", It.IsAny<String>())) .Setup(s => s.GetQueue())
.Returns(ReadAllText("Files", "Nzbget", "Queue_empty.txt")); .Returns(new List<NzbGetQueueItem>());
}
private void WithFailResponse()
{
Mocker.GetMock<IHttpProvider>()
.Setup(s => s.PostCommand("192.168.5.55:6789", "nzbget", "pass", It.IsAny<String>()))
.Returns(ReadAllText("Files", "Nzbget", "JsonError.txt"));
} }
[Test] [Test]
@ -68,7 +62,7 @@ public void should_return_item_when_queue_has_item()
Subject.GetQueue() Subject.GetQueue()
.Should() .Should()
.HaveCount(1); .HaveCount(_queue.Count);
} }
} }
} }

View File

@ -6,5 +6,16 @@ public class JsonRequest
{ {
public String Method { get; set; } public String Method { get; set; }
public object[] Params { get; set; } public object[] Params { get; set; }
public JsonRequest(string method)
{
Method = method;
}
public JsonRequest(string method, object[] @params)
{
Method = method;
Params = @params;
}
} }
} }

View File

@ -0,0 +1,99 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NLog;
using NzbDrone.Common.Serializer;
using NzbDrone.Core.Configuration;
using NzbDrone.Core.Rest;
using RestSharp;
namespace NzbDrone.Core.Download.Clients.Nzbget
{
public interface INzbGetCommunicationProxy
{
bool AddNzb(params object[] parameters);
List<NzbGetQueueItem> GetQueue();
string GetVersion();
}
public class NzbGetCommunicationProxy : INzbGetCommunicationProxy
{
private readonly IConfigService _configService;
private readonly Logger _logger;
public NzbGetCommunicationProxy(IConfigService configService, Logger logger)
{
_configService = configService;
_logger = logger;
}
public bool AddNzb(params object[] parameters)
{
var request = BuildRequest(new JsonRequest("appendurl", parameters));
return Json.Deserialize<EnqueueResponse>(ProcessRequest(request)).Result;
}
public List<NzbGetQueueItem> GetQueue()
{
var request = BuildRequest(new JsonRequest("listgroups"));
return Json.Deserialize<NzbGetQueue>(ProcessRequest(request)).QueueItems;
}
public string GetVersion()
{
var request = BuildRequest(new JsonRequest("version"));
return ProcessRequest(request);
}
private string ProcessRequest(IRestRequest restRequest)
{
var client = BuildClient();
var response = client.Execute(restRequest);
_logger.Trace("Response: {0}", response.Content);
CheckForError(response);
return response.Content;
}
private IRestClient BuildClient()
{
var url = String.Format("http://{0}:{1}/jsonrpc",
_configService.NzbgetHost,
_configService.NzbgetPort);
var client = new RestClient(url);
client.Authenticator = new HttpBasicAuthenticator(_configService.NzbgetUsername, _configService.NzbgetPassword);
return client;
}
private IRestRequest BuildRequest(JsonRequest jsonRequest)
{
var request = new RestRequest(Method.POST);
request.JsonSerializer = new JsonNetSerializer();
request.RequestFormat = DataFormat.Json;
request.AddBody(jsonRequest);
return request;
}
private void CheckForError(IRestResponse response)
{
if (response.ResponseStatus != ResponseStatus.Completed)
{
throw new ApplicationException("Unable to connect to NzbGet, please check your settings");
}
var result = Json.Deserialize<JsonError>(response.Content);
if (result.Error != null)
throw new ApplicationException(result.Error.ToString());
}
}
}

View File

@ -13,5 +13,6 @@ public class NzbGetQueueItem
public String Category { get; set; } public String Category { get; set; }
public Int32 FileSizeMb { get; set; } public Int32 FileSizeMb { get; set; }
public Int32 RemainingSizeMb { get; set; } public Int32 RemainingSizeMb { get; set; }
public Int32 PausedSizeMb { get; set; }
} }
} }

View File

@ -13,13 +13,19 @@ public class NzbgetClient : IDownloadClient
{ {
private readonly IConfigService _configService; private readonly IConfigService _configService;
private readonly IHttpProvider _httpProvider; private readonly IHttpProvider _httpProvider;
private readonly INzbGetCommunicationProxy _proxy;
private readonly IParsingService _parsingService; private readonly IParsingService _parsingService;
private readonly Logger _logger; private readonly Logger _logger;
public NzbgetClient(IConfigService configService, IHttpProvider httpProvider, IParsingService parsingService, Logger logger) public NzbgetClient(IConfigService configService,
IHttpProvider httpProvider,
INzbGetCommunicationProxy proxy,
IParsingService parsingService,
Logger logger)
{ {
_configService = configService; _configService = configService;
_httpProvider = httpProvider; _httpProvider = httpProvider;
_proxy = proxy;
_parsingService = parsingService; _parsingService = parsingService;
_logger = logger; _logger = logger;
} }
@ -32,18 +38,10 @@ public string DownloadNzb(RemoteEpisode remoteEpisode)
string cat = _configService.NzbgetTvCategory; string cat = _configService.NzbgetTvCategory;
int priority = remoteEpisode.IsRecentEpisode() ? (int)_configService.NzbgetRecentTvPriority : (int)_configService.NzbgetOlderTvPriority; int priority = remoteEpisode.IsRecentEpisode() ? (int)_configService.NzbgetRecentTvPriority : (int)_configService.NzbgetOlderTvPriority;
var command = new JsonRequest
{
Method = "appendurl",
Params = new object[] { title, cat, priority, false, url }
};
_logger.Info("Adding report [{0}] to the queue.", title); _logger.Info("Adding report [{0}] to the queue.", title);
var response = PostCommand(command.ToJson());
CheckForError(response); var success = _proxy.AddNzb(title, cat, priority, false, url);
var success = Json.Deserialize<EnqueueResponse>(response).Result;
_logger.Debug("Queue Response: [{0}]", success); _logger.Debug("Queue Response: [{0}]", success);
return null; return null;
@ -59,25 +57,16 @@ public bool IsConfigured
public virtual IEnumerable<QueueItem> GetQueue() public virtual IEnumerable<QueueItem> GetQueue()
{ {
var command = new JsonRequest var items = _proxy.GetQueue();
{
Method = "listgroups",
Params = null
};
var response = PostCommand(command.ToJson()); foreach (var nzbGetQueueItem in items)
CheckForError(response);
var itmes = Json.Deserialize<NzbGetQueue>(response).QueueItems;
foreach (var nzbGetQueueItem in itmes)
{ {
var queueItem = new QueueItem(); var queueItem = new QueueItem();
queueItem.Id = nzbGetQueueItem.NzbId.ToString(); queueItem.Id = nzbGetQueueItem.NzbId.ToString();
queueItem.Title = nzbGetQueueItem.NzbName; queueItem.Title = nzbGetQueueItem.NzbName;
queueItem.Size = nzbGetQueueItem.FileSizeMb; queueItem.Size = nzbGetQueueItem.FileSizeMb;
queueItem.Sizeleft = nzbGetQueueItem.RemainingSizeMb; queueItem.Sizeleft = nzbGetQueueItem.RemainingSizeMb;
queueItem.Status = nzbGetQueueItem.FileSizeMb == nzbGetQueueItem.PausedSizeMb ? "paused" : "queued";
var parsedEpisodeInfo = Parser.Parser.ParseTitle(queueItem.Title); var parsedEpisodeInfo = Parser.Parser.ParseTitle(queueItem.Title);
if (parsedEpisodeInfo == null) continue; if (parsedEpisodeInfo == null) continue;
@ -108,6 +97,8 @@ public void RemoveFromHistory(string id)
public virtual VersionModel GetVersion(string host = null, int port = 0, string username = null, string password = null) public virtual VersionModel GetVersion(string host = null, int port = 0, string username = null, string password = null)
{ {
throw new NotImplementedException();
//Get saved values if any of these are defaults //Get saved values if any of these are defaults
if (host == null) if (host == null)
host = _configService.NzbgetHost; host = _configService.NzbgetHost;
@ -121,16 +112,8 @@ public virtual VersionModel GetVersion(string host = null, int port = 0, string
if (password == null) if (password == null)
password = _configService.NzbgetPassword; password = _configService.NzbgetPassword;
var command = new JsonRequest
{
Method = "version",
Params = null
};
var address = String.Format(@"{0}:{1}", host, port); var response = _proxy.GetVersion();
var response = _httpProvider.PostCommand(address, username, password, command.ToJson());
CheckForError(response);
return Json.Deserialize<VersionModel>(response); return Json.Deserialize<VersionModel>(response);
} }
@ -149,22 +132,5 @@ public virtual string Test(string host, int port, string username, string passwo
return String.Empty; return String.Empty;
} }
private string PostCommand(string command)
{
var url = String.Format(@"{0}:{1}",
_configService.NzbgetHost,
_configService.NzbgetPort);
return _httpProvider.PostCommand(url, _configService.NzbgetUsername, _configService.NzbgetPassword, command);
}
private void CheckForError(string response)
{
var result = Json.Deserialize<JsonError>(response);
if (result.Error != null)
throw new ApplicationException(result.Error.ToString());
}
} }
} }

View File

@ -228,6 +228,8 @@
<Compile Include="DecisionEngine\Specifications\RssSync\HistorySpecification.cs" /> <Compile Include="DecisionEngine\Specifications\RssSync\HistorySpecification.cs" />
<Compile Include="DiskSpace\DiskSpace.cs" /> <Compile Include="DiskSpace\DiskSpace.cs" />
<Compile Include="DiskSpace\DiskSpaceService.cs" /> <Compile Include="DiskSpace\DiskSpaceService.cs" />
<Compile Include="Download\Clients\Nzbget\JsonRequest.cs" />
<Compile Include="Download\Clients\Nzbget\NzbGetCommunicationProxy.cs" />
<Compile Include="Download\Clients\Sabnzbd\ConnectionInfoModel.cs" /> <Compile Include="Download\Clients\Sabnzbd\ConnectionInfoModel.cs" />
<Compile Include="Download\Clients\Sabnzbd\JsonConverters\SabnzbdPriorityTypeConverter.cs" /> <Compile Include="Download\Clients\Sabnzbd\JsonConverters\SabnzbdPriorityTypeConverter.cs" />
<Compile Include="Download\Clients\Sabnzbd\JsonConverters\SabnzbdQueueTimeConverter.cs" /> <Compile Include="Download\Clients\Sabnzbd\JsonConverters\SabnzbdQueueTimeConverter.cs" />
@ -435,7 +437,6 @@
<Compile Include="Download\Clients\Nzbget\EnqueueResponse.cs" /> <Compile Include="Download\Clients\Nzbget\EnqueueResponse.cs" />
<Compile Include="Download\Clients\Nzbget\ErrorModel.cs" /> <Compile Include="Download\Clients\Nzbget\ErrorModel.cs" />
<Compile Include="Download\Clients\Nzbget\JsonError.cs" /> <Compile Include="Download\Clients\Nzbget\JsonError.cs" />
<Compile Include="Download\Clients\Nzbget\JsonRequest.cs" />
<Compile Include="Download\Clients\Nzbget\NzbGetQueue.cs" /> <Compile Include="Download\Clients\Nzbget\NzbGetQueue.cs" />
<Compile Include="Download\Clients\Nzbget\NzbGetQueueItem.cs" /> <Compile Include="Download\Clients\Nzbget\NzbGetQueueItem.cs" />
<Compile Include="Download\Clients\Nzbget\PriorityType.cs" /> <Compile Include="Download\Clients\Nzbget\PriorityType.cs" />
@ -450,6 +451,7 @@
<Compile Include="Parser\Parser.cs" /> <Compile Include="Parser\Parser.cs" />
<Compile Include="Parser\ParsingService.cs" /> <Compile Include="Parser\ParsingService.cs" />
<Compile Include="Parser\QualityParser.cs" /> <Compile Include="Parser\QualityParser.cs" />
<Compile Include="Rest\JsonNetSerializer.cs" />
<Compile Include="RootFolders\RootFolderRepository.cs" /> <Compile Include="RootFolders\RootFolderRepository.cs" />
<Compile Include="ThingiProvider\ConfigContractNotFoundException.cs" /> <Compile Include="ThingiProvider\ConfigContractNotFoundException.cs" />
<Compile Include="ThingiProvider\IProvider.cs" /> <Compile Include="ThingiProvider\IProvider.cs" />

View File

@ -0,0 +1,23 @@
using NzbDrone.Common.Serializer;
using RestSharp.Serializers;
namespace NzbDrone.Core.Rest
{
public class JsonNetSerializer : ISerializer
{
public JsonNetSerializer()
{
ContentType = "application/json";
}
public string Serialize(object obj)
{
return obj.ToJson();
}
public string RootElement { get; set; }
public string Namespace { get; set; }
public string DateFormat { get; set; }
public string ContentType { get; set; }
}
}