Updated restmodule, moved series, root folder to the new restmodule.

pull/6/head
kay.one 11 years ago committed by Keivan Beigi
parent 4878556e14
commit a2e84a8f83

@ -2,7 +2,9 @@
using NUnit.Framework;
using NzbDrone.Api.Episodes;
using NzbDrone.Api.Mapping;
using NzbDrone.Api.RootFolders;
using NzbDrone.Api.Series;
using NzbDrone.Core.RootFolders;
using NzbDrone.Test.Common;
namespace NzbDrone.Api.Test.MappingTests
@ -12,6 +14,7 @@ namespace NzbDrone.Api.Test.MappingTests
{
[TestCase(typeof(Core.Tv.Series), typeof(SeriesResource))]
[TestCase(typeof(Core.Tv.Episode), typeof(EpisodeResource))]
[TestCase(typeof(RootFolder), typeof(RootFolderResource))]
public void matching_fields(Type modelType, Type resourceType)
{
MappingValidation.ValidateMapping(modelType, resourceType);

@ -1,7 +1,5 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using AutoMapper;
using Nancy;
using NzbDrone.Api.Extensions;

@ -101,6 +101,7 @@
<Compile Include="REST\RestModule.cs" />
<Compile Include="REST\RestResource.cs" />
<Compile Include="RootFolders\RootFolderModule.cs" />
<Compile Include="RootFolders\RootFolderResource.cs" />
<Compile Include="Seasons\SeasonModule.cs" />
<Compile Include="Series\SeriesResource.cs" />
<Compile Include="Series\SeriesModule.cs" />

@ -1,10 +1,20 @@
using NzbDrone.Api.REST;
using System;
using System.Collections.Generic;
using NzbDrone.Api.REST;
using NzbDrone.Api.Validation;
using NzbDrone.Core.Datastore;
using NzbDrone.Api.Mapping;
namespace NzbDrone.Api
{
public abstract class NzbDroneRestModule<TResource> : RestModule<TResource> where TResource : RestResource, new()
{
protected NzbDroneRestModule()
: this(new TResource().ResourceName)
{
}
protected NzbDroneRestModule(string resource)
: base("/api/" + resource.Trim('/'))
{
@ -12,5 +22,25 @@ namespace NzbDrone.Api
PutValidator.RuleFor(r => r.Id).ValidId();
}
protected TResource Apply<TModel>(Func<TModel, TModel> function, TResource resource) where TModel : ModelBase, new()
{
var model = resource.InjectTo<TModel>();
function(model);
return model.InjectTo<TResource>();
}
protected List<TResource> Apply<TModel>(Func<IEnumerable<TModel>> function) where TModel : ModelBase, new()
{
var modelList = function();
return modelList.InjectTo<List<TResource>>();
}
protected TResource Apply<TModel>(Func<int, TModel> action, int id) where TModel : ModelBase, new()
{
var model = action(id);
return model.InjectTo<TResource>();
}
}
}

@ -10,17 +10,19 @@ namespace NzbDrone.Api.REST
public abstract class RestModule<TResource> : NancyModule
where TResource : RestResource, new()
{
protected ResourceValidator<TResource> PostValidator { get; private set; }
protected ResourceValidator<TResource> PutValidator { get; private set; }
protected ResourceValidator<TResource> SharedValidator { get; private set; }
private const string ROOT_ROUTE = "/";
private const string ID_ROUTE = "/{id}";
protected RestModule()
: this(new TResource().ResourceName)
{
private Action<int> _deleteResource;
private Func<int, TResource> _getResourceById;
private Func<List<TResource>> _getResourceAll;
private Func<TResource, TResource> _createResource;
private Func<TResource, TResource> _updateResource;
protected ResourceValidator<TResource> PostValidator { get; private set; }
protected ResourceValidator<TResource> PutValidator { get; private set; }
protected ResourceValidator<TResource> SharedValidator { get; private set; }
}
protected RestModule(string modulePath)
: base(modulePath)
@ -29,61 +31,81 @@ namespace NzbDrone.Api.REST
PostValidator = new ResourceValidator<TResource>();
PutValidator = new ResourceValidator<TResource>();
SharedValidator = new ResourceValidator<TResource>();
}
Get[ROOT_ROUTE] = options =>
protected Action<int> DeleteResource
{
private get { return _deleteResource; }
set
{
EnsureImplementation(GetResourceAll);
var resource = GetResourceAll();
return resource.AsResponse();
};
_deleteResource = value;
Delete[ID_ROUTE] = options =>
{
DeleteResource((int)options.Id);
return new Response { StatusCode = HttpStatusCode.OK };
};
}
}
Get[ID_ROUTE] = options =>
protected Func<int, TResource> GetResourceById
{
private get { return _getResourceById; }
set
{
EnsureImplementation(GetResourceById);
var resource = GetResourceById((int)options.Id);
return resource.AsResponse();
};
_getResourceById = value;
Get[ID_ROUTE] = options =>
{
var resource = GetResourceById((int)options.Id);
return resource.AsResponse();
};
}
}
Post[ROOT_ROUTE] = options =>
protected Func<List<TResource>> GetResourceAll
{
private get { return _getResourceAll; }
set
{
EnsureImplementation(CreateResource);
var resource = CreateResource(ReadFromRequest());
return resource.AsResponse(HttpStatusCode.Created);
};
_getResourceAll = value;
Put[ROOT_ROUTE] = options =>
{
EnsureImplementation(UpdateResource);
var resource = UpdateResource(ReadFromRequest());
return resource.AsResponse(HttpStatusCode.Accepted);
};
Get[ROOT_ROUTE] = options =>
{
var resource = GetResourceAll();
return resource.AsResponse();
};
}
}
Delete[ID_ROUTE] = options =>
protected Func<TResource, TResource> CreateResource
{
private get { return _createResource; }
set
{
EnsureImplementation(DeleteResource);
DeleteResource((int)options.Id);
return new Response { StatusCode = HttpStatusCode.OK };
};
_createResource = value;
Post[ROOT_ROUTE] = options =>
{
var resource = CreateResource(ReadFromRequest());
return resource.AsResponse(HttpStatusCode.Created);
};
}
}
protected Action<int> DeleteResource { get; set; }
protected Func<int, TResource> GetResourceById { get; set; }
protected Func<List<TResource>> GetResourceAll { get; set; }
protected Func<TResource, TResource> CreateResource { get; set; }
protected Func<TResource, TResource> UpdateResource { get; set; }
private void EnsureImplementation(Delegate implementation)
protected Func<TResource, TResource> UpdateResource
{
if (implementation == null)
private get { return _updateResource; }
set
{
throw new NotImplementedException();
_updateResource = value;
Put[ROOT_ROUTE] = options =>
{
var resource = UpdateResource(ReadFromRequest());
return resource.AsResponse(HttpStatusCode.Accepted);
};
}
}
private TResource ReadFromRequest()
{
var resource = Request.Body.FromJson<TResource>();

@ -10,7 +10,7 @@ namespace NzbDrone.Api.REST
{
get
{
return GetType().Name.ToLower();
return GetType().Name.ToLower().Replace("resource", "");
}
}
}

@ -1,41 +1,34 @@
using System.Linq;
using Nancy;
using NzbDrone.Api.Extensions;
using NzbDrone.Core.Providers;
using System.Collections.Generic;
using NzbDrone.Core.RootFolders;
namespace NzbDrone.Api.RootFolders
{
public class RootFolderModule : NzbDroneApiModule
public class RootFolderModule : NzbDroneRestModule<RootFolderResource>
{
private readonly RootFolderService _rootFolderService;
public RootFolderModule(RootFolderService rootFolderService)
: base("/rootfolder")
{
_rootFolderService = rootFolderService;
Get["/"] = x => GetRootFolders();
Post["/"] = x => AddRootFolder();
Delete["/{id}"] = x => DeleteRootFolder((int)x.id);
GetResourceAll = GetRootFolders;
CreateResource = CreateRootFolder;
DeleteResource = DeleteFolder;
}
private Response AddRootFolder()
private RootFolderResource CreateRootFolder(RootFolderResource rootFolderResource)
{
var dir = _rootFolderService.Add(Request.Body.FromJson<RootFolder>());
return dir.AsResponse(HttpStatusCode.Created);
return Apply<RootFolder>(_rootFolderService.Add, rootFolderResource);
}
private Response GetRootFolders()
private List<RootFolderResource> GetRootFolders()
{
return _rootFolderService.All().AsResponse();
return Apply(_rootFolderService.All);
}
private Response DeleteRootFolder(int folderId)
private void DeleteFolder(int id)
{
_rootFolderService.Remove(folderId);
return new Response { StatusCode = HttpStatusCode.OK };
_rootFolderService.Remove(id);
}
}
}

@ -0,0 +1,11 @@
using System;
using NzbDrone.Api.REST;
namespace NzbDrone.Api.RootFolders
{
public class RootFolderResource : RestResource
{
public String Path { get; set; }
public UInt64 FreeSpace { get; set; }
}
}

@ -2,11 +2,7 @@
using System.Collections.Generic;
using System.Linq;
using FluentValidation;
using NzbDrone.Api.Extensions;
using NzbDrone.Common;
using NzbDrone.Common;
using NzbDrone.Core.SeriesStats;
using NzbDrone.Api.Mapping;
using NzbDrone.Core.Tv;
using NzbDrone.Api.Validation;
@ -40,10 +36,8 @@ namespace NzbDrone.Api.Series
private List<SeriesResource> AllSeries()
{
var series = _seriesService.GetAllSeries().ToList();
var seriesStats = _seriesStatisticsService.SeriesStatistics();
var seriesModels = series.InjectTo<List<SeriesResource>>();
var seriesModels = Apply(_seriesService.GetAllSeries);
foreach (var s in seriesModels)
{
@ -61,40 +55,22 @@ namespace NzbDrone.Api.Series
private SeriesResource GetSeries(int id)
{
var series = _seriesService.GetSeries(id);
return series.InjectTo<SeriesResource>();
return Apply(_seriesService.GetSeries, id);
}
private SeriesResource AddSeries(SeriesResource seriesResource)
{
var newSeries = Request.Body.FromJson<Core.Tv.Series>();
//Todo: Alert the user if this series already exists
//Todo: We need to create the folder if the user is adding a new series
//(we can just create the folder and it won't blow up if it already exists)
//We also need to remove any special characters from the filename before attempting to create it
var series = seriesResource.InjectTo<Core.Tv.Series>();
_seriesService.AddSeries(series);
return series.InjectTo<SeriesResource>();
return Apply<Core.Tv.Series>(_seriesService.AddSeries, seriesResource);
}
private SeriesResource UpdateSeries(SeriesResource seriesResource)
{
var series = _seriesService.GetSeries(seriesResource.Id);
series.Monitored = seriesResource.Monitored;
series.SeasonFolder = seriesResource.SeasonFolder;
series.QualityProfileId = seriesResource.QualityProfileId;
//Todo: Do we want to force a scan when this path changes? Can we use events instead?
series.RootFolderId = seriesResource.RootFolderId;
series.FolderName = seriesResource.FolderName;
series.BacklogSetting = seriesResource.BacklogSetting;
_seriesService.UpdateSeries(series);
return series.InjectTo<SeriesResource>();
return Apply<Core.Tv.Series>(_seriesService.UpdateSeries, seriesResource);
}
private void DeleteSeries(int id)

@ -24,14 +24,14 @@ namespace NzbDrone.Core.Tv
bool IsMonitored(int id);
Series UpdateSeriesInfo(int seriesId);
Series GetSeries(int seriesId);
void AddSeries(Series newSeries);
Series AddSeries(Series newSeries);
void UpdateFromSeriesEditor(IList<Series> editedSeries);
Series FindByTvdbId(int tvdbId);
Series FindByTitle(string title);
void SetSeriesType(int seriesId, SeriesTypes seriesTypes);
void DeleteSeries(int seriesId, bool deleteFiles);
List<Series> GetAllSeries();
void UpdateSeries(Series series);
Series UpdateSeries(Series series);
bool SeriesPathExists(string folder);
List<Series> GetSeriesInList(IEnumerable<int> seriesIds);
}
@ -93,7 +93,7 @@ namespace NzbDrone.Core.Tv
return _seriesRepository.Get(seriesId);
}
public void AddSeries(Series newSeries)
public Series AddSeries(Series newSeries)
{
Ensure.That(() => newSeries).IsNotNull();
@ -115,6 +115,8 @@ namespace NzbDrone.Core.Tv
_seriesRepository.Insert(newSeries);
_eventAggregator.Publish(new SeriesAddedEvent(newSeries));
return newSeries;
}
public void UpdateFromSeriesEditor(IList<Series> editedSeries)
@ -164,9 +166,9 @@ namespace NzbDrone.Core.Tv
return _seriesRepository.All().ToList();
}
public void UpdateSeries(Series series)
public Series UpdateSeries(Series series)
{
_seriesRepository.Update(series);
return _seriesRepository.Update(series);
}
public bool SeriesPathExists(string folder)

@ -1,29 +1,32 @@
using System.Collections.Generic;
using System.Net;
using FluentAssertions;
using FluentValidation;
using FluentValidation.Results;
using NLog;
using Newtonsoft.Json;
using NzbDrone.Api.REST;
using RestSharp;
namespace NzbDrone.Integration.Test.Client
{
public abstract class ClientBase<TResource> where TResource : new()
public class ClientBase<TResource> where TResource : RestResource, new()
{
private readonly IRestClient _restClient;
private readonly string _resource;
private readonly Logger _logger;
protected ClientBase(IRestClient restClient, string resource)
public ClientBase(IRestClient restClient, string resource = null)
{
if (resource == null)
{
resource = new TResource().ResourceName;
}
_restClient = restClient;
_resource = resource;
_logger = LogManager.GetLogger("REST");
}
public List<TResource> GetAll()
public List<TResource> All()
{
var request = BuildRequest();
return Get<List<TResource>>(request);
@ -36,6 +39,12 @@ namespace NzbDrone.Integration.Test.Client
return Post<TResource>(request);
}
public void Delete(int id)
{
var request = BuildRequest(id.ToString());
Delete(request);
}
public List<string> InvalidPost(TResource body)
{
var request = BuildRequest();
@ -63,6 +72,12 @@ namespace NzbDrone.Integration.Test.Client
return Execute<T>(request, statusCode);
}
public void Delete(IRestRequest request, HttpStatusCode statusCode = HttpStatusCode.OK)
{
request.Method = Method.DELETE;
Execute<object>(request, statusCode);
}
private T Execute<T>(IRestRequest request, HttpStatusCode statusCode) where T : new()
{
_logger.Info("{0}: {1}", request.Method, _restClient.BuildUri(request));

@ -7,7 +7,7 @@ namespace NzbDrone.Integration.Test.Client
public class SeriesClient : ClientBase<SeriesResource>
{
public SeriesClient(IRestClient restClient)
: base(restClient, "series")
: base(restClient)
{
}
@ -19,4 +19,4 @@ namespace NzbDrone.Integration.Test.Client
}
}
}
}

@ -1,96 +1,99 @@
using System;
using System.IO;
using NLog;
using NLog.Config;
using NLog.Targets;
using NUnit.Framework;
using Nancy.Hosting.Self;
using NzbDrone.Api;
using NzbDrone.Common;
using NzbDrone.Core.Datastore;
using NzbDrone.Integration.Test.Client;
using RestSharp;
using TinyIoC;
namespace NzbDrone.Integration.Test
{
[TestFixture]
public abstract class SmokeTestBase
{
private NancyBootstrapper _bootstrapper;
private NancyHost _host;
protected RestClient RestClient { get; private set; }
private static readonly Logger Logger = LogManager.GetLogger("TEST");
protected TinyIoCContainer Container { get; private set; }
protected SeriesClient Series;
static SmokeTestBase()
{
if (LogManager.Configuration == null || LogManager.Configuration is XmlLoggingConfiguration)
{
LogManager.Configuration = new LoggingConfiguration();
var consoleTarget = new ConsoleTarget { Layout = "${logger} - ${message} ${exception}" };
LogManager.Configuration.AddTarget(consoleTarget.GetType().Name, consoleTarget);
LogManager.Configuration.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, consoleTarget));
}
LogManager.ReconfigExistingLoggers();
}
private void InitDatabase()
{
Logger.Info("Registering Database...");
//TODO: move this to factory
var environmentProvider = new EnvironmentProvider();
var appDataPath = environmentProvider.GetAppDataPath();
if (!Directory.Exists(appDataPath))
{
Directory.CreateDirectory(appDataPath);
}
var dbPath = Path.Combine(environmentProvider.WorkingDirectory, DateTime.Now.Ticks + ".db");
Logger.Info("Working Folder: {0}", environmentProvider.WorkingDirectory);
Logger.Info("Data Folder: {0}", environmentProvider.GetAppDataPath());
Logger.Info("DB Na: {0}", dbPath);
Container.Register((c, p) => c.Resolve<IDbFactory>().Create(dbPath));
}
[SetUp]
public void SmokeTestSetup()
{
Container = MainAppContainerBuilder.BuildContainer();
InitDatabase();
_bootstrapper = new NancyBootstrapper(Container);
const string url = "http://localhost:1313";
_host = new NancyHost(new Uri(url), _bootstrapper);
RestClient = new RestClient(url + "/api/");
Series = new SeriesClient(RestClient);
_host.Start();
}
[TearDown]
public void SmokeTestTearDown()
{
_host.Stop();
_bootstrapper.Shutdown();
}
}
}
using System;
using System.IO;
using NLog;
using NLog.Config;
using NLog.Targets;
using NUnit.Framework;
using Nancy.Hosting.Self;
using NzbDrone.Api;
using NzbDrone.Api.RootFolders;
using NzbDrone.Common;
using NzbDrone.Core.Datastore;
using NzbDrone.Integration.Test.Client;
using RestSharp;
using TinyIoC;
namespace NzbDrone.Integration.Test
{
[TestFixture]
public abstract class IntegrationTest
{
private NancyBootstrapper _bootstrapper;
private NancyHost _host;
protected RestClient RestClient { get; private set; }
private static readonly Logger Logger = LogManager.GetLogger("TEST");
protected TinyIoCContainer Container { get; private set; }
protected SeriesClient Series;
protected ClientBase<RootFolderResource> RootFolders;
static IntegrationTest()
{
if (LogManager.Configuration == null || LogManager.Configuration is XmlLoggingConfiguration)
{
LogManager.Configuration = new LoggingConfiguration();
var consoleTarget = new ConsoleTarget { Layout = "${logger} - ${message} ${exception}" };
LogManager.Configuration.AddTarget(consoleTarget.GetType().Name, consoleTarget);
LogManager.Configuration.LoggingRules.Add(new LoggingRule("*", LogLevel.Info, consoleTarget));
}
LogManager.ReconfigExistingLoggers();
}
private void InitDatabase()
{
Logger.Info("Registering Database...");
//TODO: move this to factory
var environmentProvider = new EnvironmentProvider();
var appDataPath = environmentProvider.GetAppDataPath();
if (!Directory.Exists(appDataPath))
{
Directory.CreateDirectory(appDataPath);
}
var dbPath = Path.Combine(environmentProvider.WorkingDirectory, DateTime.Now.Ticks + ".db");
Logger.Info("Working Folder: {0}", environmentProvider.WorkingDirectory);
Logger.Info("Data Folder: {0}", environmentProvider.GetAppDataPath());
Logger.Info("DB Na: {0}", dbPath);
Container.Register((c, p) => c.Resolve<IDbFactory>().Create(dbPath));
}
[SetUp]
public void SmokeTestSetup()
{
Container = MainAppContainerBuilder.BuildContainer();
InitDatabase();
_bootstrapper = new NancyBootstrapper(Container);
const string url = "http://localhost:1313";
_host = new NancyHost(new Uri(url), _bootstrapper);
RestClient = new RestClient(url + "/api/");
Series = new SeriesClient(RestClient);
RootFolders = new ClientBase<RootFolderResource>(RestClient);
_host.Start();
}
[TearDown]
public void SmokeTestTearDown()
{
_host.Stop();
_bootstrapper.Shutdown();
}
}
}

@ -76,9 +76,10 @@
<ItemGroup>
<Compile Include="Client\ClientBase.cs" />
<Compile Include="Client\SeriesClient.cs" />
<Compile Include="SmokeTestBase.cs" />
<Compile Include="IntegrationTest.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="SeriesTest.cs" />
<Compile Include="RootFolderIntegrationTest.cs" />
<Compile Include="SeriesIntegrationTest.cs" />
</ItemGroup>
<ItemGroup>
<None Include="..\NzbDrone.Test.Common\App.config">

@ -0,0 +1,37 @@
using System.IO;
using FluentAssertions;
using NUnit.Framework;
using NzbDrone.Api.RootFolders;
namespace NzbDrone.Integration.Test
{
[TestFixture]
public class RootFolderIntegrationTest : IntegrationTest
{
[Test]
public void should_have_no_root_folder_initially()
{
RootFolders.All().Should().BeEmpty();
var rootFolder = new RootFolderResource
{
Path = Directory.GetCurrentDirectory()
};
var postResponse = RootFolders.Post(rootFolder);
postResponse.Id.Should().NotBe(0);
postResponse.FreeSpace.Should().NotBe(0);
RootFolders.All().Should().OnlyContain(c => c.Id == postResponse.Id);
RootFolders.Delete(postResponse.Id);
RootFolders.All().Should().BeEmpty();
}
}
}

@ -2,16 +2,17 @@
using FluentAssertions;
using NUnit.Framework;
using NzbDrone.Api.Series;
using System.Linq;
namespace NzbDrone.Integration.Test
{
[TestFixture]
public class SeriesTest : SmokeTestBase
public class SeriesIntegrationTest : IntegrationTest
{
[Test]
public void should_have_no_series_on_start_application()
{
Series.GetAll().Should().BeEmpty();
Series.All().Should().BeEmpty();
}
[Test]
@ -30,5 +31,14 @@ namespace NzbDrone.Integration.Test
errors.Should().NotBeEmpty();
}
[Test]
public void should_be_able_to_add_series()
{
var series = Series.Lookup("archer").First();
Series.Post(series);
Series.All().Should().HaveCount(1);
}
}
}
Loading…
Cancel
Save