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 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.NzbgetProviderTests
[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.Release = new ReleaseInfo();
_remoteEpisode.Release.Title = _title;
@ -42,37 +34,19 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.NzbgetProviderTests
.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]
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
{
Method = "appendurl",
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.GetMock<INzbGetCommunicationProxy>()
.Setup(s => s.AddNzb(p))
.Returns(true);
Mocker.Resolve<NzbgetClient>().DownloadNzb(_remoteEpisode);
}
[Test]
public void should_throw_when_error_is_returned()
{
WithFailResponse();
Assert.Throws<ApplicationException>(() => Mocker.Resolve<NzbgetClient>().DownloadNzb(_remoteEpisode));
Mocker.GetMock<INzbGetCommunicationProxy>()
.Verify(v => v.AddNzb(It.IsAny<object []>()), Times.Once());
}
}
}

View File

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

View File

@ -6,5 +6,16 @@ namespace NzbDrone.Core.Download.Clients.Nzbget
{
public String Method { 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 @@ namespace NzbDrone.Core.Download.Clients.Nzbget
public String Category { get; set; }
public Int32 FileSizeMb { get; set; }
public Int32 RemainingSizeMb { get; set; }
public Int32 PausedSizeMb { get; set; }
}
}

View File

@ -13,13 +13,19 @@ namespace NzbDrone.Core.Download.Clients.Nzbget
{
private readonly IConfigService _configService;
private readonly IHttpProvider _httpProvider;
private readonly INzbGetCommunicationProxy _proxy;
private readonly IParsingService _parsingService;
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;
_httpProvider = httpProvider;
_proxy = proxy;
_parsingService = parsingService;
_logger = logger;
}
@ -32,18 +38,10 @@ namespace NzbDrone.Core.Download.Clients.Nzbget
string cat = _configService.NzbgetTvCategory;
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);
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);
return null;
@ -59,25 +57,16 @@ namespace NzbDrone.Core.Download.Clients.Nzbget
public virtual IEnumerable<QueueItem> GetQueue()
{
var command = new JsonRequest
{
Method = "listgroups",
Params = null
};
var items = _proxy.GetQueue();
var response = PostCommand(command.ToJson());
CheckForError(response);
var itmes = Json.Deserialize<NzbGetQueue>(response).QueueItems;
foreach (var nzbGetQueueItem in itmes)
foreach (var nzbGetQueueItem in items)
{
var queueItem = new QueueItem();
queueItem.Id = nzbGetQueueItem.NzbId.ToString();
queueItem.Title = nzbGetQueueItem.NzbName;
queueItem.Size = nzbGetQueueItem.FileSizeMb;
queueItem.Sizeleft = nzbGetQueueItem.RemainingSizeMb;
queueItem.Status = nzbGetQueueItem.FileSizeMb == nzbGetQueueItem.PausedSizeMb ? "paused" : "queued";
var parsedEpisodeInfo = Parser.Parser.ParseTitle(queueItem.Title);
if (parsedEpisodeInfo == null) continue;
@ -108,6 +97,8 @@ namespace NzbDrone.Core.Download.Clients.Nzbget
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
if (host == null)
host = _configService.NzbgetHost;
@ -121,16 +112,8 @@ namespace NzbDrone.Core.Download.Clients.Nzbget
if (password == null)
password = _configService.NzbgetPassword;
var command = new JsonRequest
{
Method = "version",
Params = null
};
var address = String.Format(@"{0}:{1}", host, port);
var response = _httpProvider.PostCommand(address, username, password, command.ToJson());
CheckForError(response);
var response = _proxy.GetVersion();
return Json.Deserialize<VersionModel>(response);
}
@ -149,22 +132,5 @@ namespace NzbDrone.Core.Download.Clients.Nzbget
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="DiskSpace\DiskSpace.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\JsonConverters\SabnzbdPriorityTypeConverter.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\ErrorModel.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\NzbGetQueueItem.cs" />
<Compile Include="Download\Clients\Nzbget\PriorityType.cs" />
@ -450,6 +451,7 @@
<Compile Include="Parser\Parser.cs" />
<Compile Include="Parser\ParsingService.cs" />
<Compile Include="Parser\QualityParser.cs" />
<Compile Include="Rest\JsonNetSerializer.cs" />
<Compile Include="RootFolders\RootFolderRepository.cs" />
<Compile Include="ThingiProvider\ConfigContractNotFoundException.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; }
}
}