Lot's of refactoring

pull/1488/head
Jamie.Rees 7 years ago
parent c6865d9dcc
commit 263240c648

@ -1,4 +1,8 @@
using System.Linq;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Moq;
@ -18,5 +22,15 @@ namespace Ombi.Core.Tests
return dbSet.Object;
}
public static IQueryable<T> GetQueryable<T>(params T[] sourceList) where T : class
{
var mock = new Mock<IQueryable<T>>();
mock.As<IQueryable<T>>().Setup(x => x.ToListAsync(It.IsAny<CancellationToken>())).ReturnsAsync(sourceList.ToList());
return mock.Object;
}
}
}

@ -4,8 +4,8 @@
//using Moq;
//using Ombi.Core.Engine;
//using Ombi.Core.Models.Requests;
//using Ombi.Core.Models.Requests.Movie;
//using Ombi.Core.Requests.Models;
//using Ombi.Store.Entities.Requests;
//using Ombi.Store.Repository;
//using Xunit;
//namespace Ombi.Core.Tests.Engine
@ -14,118 +14,120 @@
// {
// public MovieRequestEngineTests()
// {
// RequestService = new Mock<IRequestService<MovieRequestModel>>();
// RequestService = new Mock<IMovieRequestRepository>();
// var requestService = new RequestService(null, RequestService.Object);
// Engine = new MovieRequestEngine(null, requestService, null, null, null, null, null);
// Engine = new MovieRequestEngine(null, requestService, null, null, null, null, null, null);
// }
// private MovieRequestEngine Engine { get; }
// private Mock<IRequestService<MovieRequestModel>> RequestService { get; }
// private Mock<IMovieRequestRepository> RequestService { get; }
// [Fact]
// public async Task GetNewRequests_Should_ReturnEmpty_WhenThereAreNoNewRequests()
// {
// var requests = new List<MovieRequestModel>
// var requests = new List<MovieRequests>
// {
// new MovieRequestModel { Available = true },
// new MovieRequestModel { Approved = true },
// new MovieRequests { Available = true },
// new MovieRequests { Approved = true },
// };
// RequestService.Setup(x => x.GetAllAsync()).ReturnsAsync(requests);
// var result = await Engine.GetNewRequests();
// Assert.False(result.Any());
// }
// [Fact]
// public async Task GetNewRequests_Should_ReturnOnlyNewRequests_WhenThereAreMultipleRequests()
// {
// var requests = new List<MovieRequestModel>
// {
// new MovieRequestModel { Available = true },
// new MovieRequestModel { Approved = true },
// new MovieRequestModel(),
// };
// RequestService.Setup(x => x.GetAllAsync()).ReturnsAsync(requests);
// var r = DbHelper.GetQueryable(requests[0], requests[1]);
// RequestService.Setup(x => x.Get()).Returns(r);
// var result = await Engine.GetNewRequests();
// Assert.Equal(result.Count(), 1);
// Assert.All(result, x =>
// {
// Assert.Equal(x.Available, false);
// Assert.Equal(x.Approved, false);
// });
// }
// [Fact]
// public async Task GetApprovedRequests_Should_ReturnEmpty_WhenThereAreNoApprovedRequests()
// {
// var requests = new List<MovieRequestModel>
// {
// new MovieRequestModel { Available = true },
// };
// RequestService.Setup(x => x.GetAllAsync()).ReturnsAsync(requests);
// var result = await Engine.GetApprovedRequests();
// Assert.False(result.Any());
// }
// [Fact]
// public async Task GetApprovedRequests_Should_ReturnOnlyApprovedRequests_WhenThereAreMultipleRequests()
// {
// var requests = new List<MovieRequestModel>
// {
// new MovieRequestModel { Available = true },
// new MovieRequestModel { Approved = true },
// new MovieRequestModel(),
// };
// RequestService.Setup(x => x.GetAllAsync()).ReturnsAsync(requests);
// var result = await Engine.GetApprovedRequests();
// Assert.Equal(result.Count(), 1);
// Assert.All(result, x =>
// {
// Assert.Equal(x.Available, false);
// Assert.Equal(x.Approved, true);
// });
// }
// [Fact]
// public async Task GetAvailableRequests_Should_ReturnEmpty_WhenThereAreNoAvailableRequests()
// {
// var requests = new List<MovieRequestModel>
// {
// new MovieRequestModel { Approved = true },
// };
// RequestService.Setup(x => x.GetAllAsync()).ReturnsAsync(requests);
// var result = await Engine.GetAvailableRequests();
// Assert.False(result.Any());
// }
// [Fact]
// public async Task GetAvailableRequests_Should_ReturnOnlyAvailableRequests_WhenThereAreMultipleRequests()
// {
// var requests = new List<MovieRequestModel>
// {
// new MovieRequestModel { Available = true },
// new MovieRequestModel { Approved = true },
// new MovieRequestModel(),
// };
// RequestService.Setup(x => x.GetAllAsync()).ReturnsAsync(requests);
// var result = await Engine.GetAvailableRequests();
// Assert.Equal(result.Count(), 1);
// Assert.All(result, x =>
// {
// Assert.Equal(x.Available, true);
// Assert.Equal(x.Approved, false);
// });
// }
// //[Fact]
// //public async Task GetNewRequests_Should_ReturnOnlyNewRequests_WhenThereAreMultipleRequests()
// //{
// // var requests = new List<MovieRequestModel>
// // {
// // new MovieRequestModel { Available = true },
// // new MovieRequestModel { Approved = true },
// // new MovieRequestModel(),
// // };
// // RequestService.Setup(x => x.GetAllAsync()).ReturnsAsync(requests);
// // var result = await Engine.GetNewRequests();
// // Assert.Equal(result.Count(), 1);
// // Assert.All(result, x =>
// // {
// // Assert.Equal(x.Available, false);
// // Assert.Equal(x.Approved, false);
// // });
// //}
// //[Fact]
// //public async Task GetApprovedRequests_Should_ReturnEmpty_WhenThereAreNoApprovedRequests()
// //{
// // var requests = new List<MovieRequestModel>
// // {
// // new MovieRequestModel { Available = true },
// // };
// // RequestService.Setup(x => x.GetAllAsync()).ReturnsAsync(requests);
// // var result = await Engine.GetApprovedRequests();
// // Assert.False(result.Any());
// //}
// //[Fact]
// //public async Task GetApprovedRequests_Should_ReturnOnlyApprovedRequests_WhenThereAreMultipleRequests()
// //{
// // var requests = new List<MovieRequestModel>
// // {
// // new MovieRequestModel { Available = true },
// // new MovieRequestModel { Approved = true },
// // new MovieRequestModel(),
// // };
// // RequestService.Setup(x => x.GetAllAsync()).ReturnsAsync(requests);
// // var result = await Engine.GetApprovedRequests();
// // Assert.Equal(result.Count(), 1);
// // Assert.All(result, x =>
// // {
// // Assert.Equal(x.Available, false);
// // Assert.Equal(x.Approved, true);
// // });
// //}
// //[Fact]
// //public async Task GetAvailableRequests_Should_ReturnEmpty_WhenThereAreNoAvailableRequests()
// //{
// // var requests = new List<MovieRequestModel>
// // {
// // new MovieRequestModel { Approved = true },
// // };
// // RequestService.Setup(x => x.GetAllAsync()).ReturnsAsync(requests);
// // var result = await Engine.GetAvailableRequests();
// // Assert.False(result.Any());
// //}
// //[Fact]
// //public async Task GetAvailableRequests_Should_ReturnOnlyAvailableRequests_WhenThereAreMultipleRequests()
// //{
// // var requests = new List<MovieRequestModel>
// // {
// // new MovieRequestModel { Available = true },
// // new MovieRequestModel { Approved = true },
// // new MovieRequestModel(),
// // };
// // RequestService.Setup(x => x.GetAllAsync()).ReturnsAsync(requests);
// // var result = await Engine.GetAvailableRequests();
// // Assert.Equal(result.Count(), 1);
// // Assert.All(result, x =>
// // {
// // Assert.Equal(x.Available, true);
// // Assert.Equal(x.Approved, false);
// // });
// //}
// }
//}

@ -1,11 +1,10 @@
//using System.Collections.Generic;
//using System.Linq;
//using System.Threading.Tasks;
//using Moq;
//using Ombi.Core.Engine;
//using Ombi.Core.Models.Requests;
//using Ombi.Core.Models.Requests.Tv;
//using Ombi.Core.Requests.Models;
//using Ombi.Store.Entities.Requests;
//using Ombi.Store.Repository.Requests;
//using Xunit;
//namespace Ombi.Core.Tests.Engine
@ -14,49 +13,49 @@
// {
// public TvRequestEngineTests()
// {
// RequestService = new Mock<IRequestService<TvRequestModel>>();
// RequestService = new Mock<ITvRequestRepository>();
// var requestService = new RequestService(RequestService.Object, null);
// Engine = new TvRequestEngine(null, requestService, null, null, null, null);
// Engine = new TvRequestEngine(null, requestService, null, null, null, null, null, null);
// }
// private TvRequestEngine Engine { get; }
// private Mock<IRequestService<TvRequestModel>> RequestService { get; }
// [Fact]
// public async Task GetNewRequests_Should_ReturnEmpty_WhenThereAreNoNewRequests()
// {
// var requests = new List<TvRequestModel>
// {
// new TvRequestModel { Available = true },
// new TvRequestModel { Approved = true },
// };
// RequestService.Setup(x => x.GetAllAsync()).ReturnsAsync(requests);
// var result = await Engine.GetNewRequests();
// Assert.False(result.Any());
// }
// [Fact]
// public async Task GetNewRequests_Should_ReturnOnlyNewRequests_WhenThereAreMultipleRequests()
// {
// var requests = new List<TvRequestModel>
// {
// new TvRequestModel { Available = true },
// new TvRequestModel { Approved = true },
// new TvRequestModel(),
// };
// RequestService.Setup(x => x.GetAllAsync()).ReturnsAsync(requests);
// var result = await Engine.GetNewRequests();
// Assert.Equal(result.Count(), 1);
// Assert.All(result, x =>
// {
// Assert.Equal(x.Available, false);
// Assert.Equal(x.Approved, false);
// });
// }
// private Mock<ITvRequestRepository> RequestService { get; }
// //[Fact]
// //public async Task GetNewRequests_Should_ReturnEmpty_WhenThereAreNoNewRequests()
// //{
// // var requests = new List<TvRequests>
// // {
// // new TvRequests { Available = true },
// // new TvRequests { Approved = true },
// // };
// // RequestService.Setup(x => x.GetAllAsync()).ReturnsAsync(requests);
// // var result = await Engine.GetNewRequests();
// // Assert.False(result.Any());
// //}
// //[Fact]
// //public async Task GetNewRequests_Should_ReturnOnlyNewRequests_WhenThereAreMultipleRequests()
// //{
// // var requests = new List<TvRequestModel>
// // {
// // new TvRequestModel { Available = true },
// // new TvRequestModel { Approved = true },
// // new TvRequestModel(),
// // };
// // RequestService.Setup(x => x.GetAllAsync()).ReturnsAsync(requests);
// // var result = await Engine.GetNewRequests();
// // Assert.Equal(result.Count(), 1);
// // Assert.All(result, x =>
// // {
// // Assert.Equal(x.Available, false);
// // Assert.Equal(x.Approved, false);
// // });
// //}
// [Fact]
// public async Task GetApprovedRequests_Should_ReturnEmpty_WhenThereAreNoApprovedRequests()

@ -1,89 +1,86 @@
//using System.Security.Principal;
//using System.Threading.Tasks;
//using Moq;
//using Ombi.Core.Claims;
//using Ombi.Core.Models.Requests;
//using Ombi.Core.Rule.Rules;
//using Ombi.Core.Rule.Rules.Request;
//using Xunit;
//namespace Ombi.Core.Tests.Rule
//{
// public class AutoApproveRuleTests
// {
// public AutoApproveRuleTests()
// {
// PrincipalMock = new Mock<IPrincipal>();
// Rule = new AutoApproveRule(PrincipalMock.Object);
// }
// private AutoApproveRule Rule { get; }
// private Mock<IPrincipal> PrincipalMock { get; }
// [Fact]
// public async Task Should_ReturnSuccess_WhenAdminAndRequestMovie()
// {
// PrincipalMock.Setup(x => x.IsInRole(OmbiClaims.Admin)).Returns(true);
// var request = new BaseRequestModel() { Type = Store.Entities.RequestType.Movie };
// var result = await Rule.Execute(request);
// Assert.Equal(result.Success, true);
// Assert.Equal(request.Approved, true);
// }
// [Fact]
// public async Task Should_ReturnSuccess_WhenAdminAndRequestTV()
// {
// PrincipalMock.Setup(x => x.IsInRole(OmbiClaims.Admin)).Returns(true);
// var request = new BaseRequestModel() { Type = Store.Entities.RequestType.TvShow };
// var result = await Rule.Execute(request);
// Assert.Equal(result.Success, true);
// Assert.Equal(request.Approved, true);
// }
// [Fact]
// public async Task Should_ReturnSuccess_WhenAutoApproveMovieAndRequestMovie()
// {
// PrincipalMock.Setup(x => x.IsInRole(OmbiClaims.AutoApproveMovie)).Returns(true);
// var request = new BaseRequestModel() { Type = Store.Entities.RequestType.Movie };
// var result = await Rule.Execute(request);
// Assert.Equal(result.Success, true);
// Assert.Equal(request.Approved, true);
// }
// [Fact]
// public async Task Should_ReturnSuccess_WhenAutoApproveTVAndRequestTV()
// {
// PrincipalMock.Setup(x => x.IsInRole(OmbiClaims.AutoApproveTv)).Returns(true);
// var request = new BaseRequestModel() { Type = Store.Entities.RequestType.TvShow };
// var result = await Rule.Execute(request);
// Assert.Equal(result.Success, true);
// Assert.Equal(request.Approved, true);
// }
// [Fact]
// public async Task Should_ReturnFail_WhenNoClaimsAndRequestMovie()
// {
// var request = new BaseRequestModel() { Type = Store.Entities.RequestType.Movie };
// var result = await Rule.Execute(request);
// Assert.Equal(result.Success, true);
// Assert.Equal(request.Approved, false);
// }
// [Fact]
// public async Task Should_ReturnFail_WhenNoClaimsAndRequestTV()
// {
// var request = new BaseRequestModel() { Type = Store.Entities.RequestType.TvShow };
// var result = await Rule.Execute(request);
// Assert.Equal(result.Success, true);
// Assert.Equal(request.Approved, false);
// }
// }
//}
using System.Security.Principal;
using System.Threading.Tasks;
using Moq;
using Ombi.Core.Claims;
using Ombi.Core.Rule.Rules.Request;
using Ombi.Store.Entities.Requests;
using Xunit;
namespace Ombi.Core.Tests.Rule.Request
{
public class AutoApproveRuleTests
{
public AutoApproveRuleTests()
{
PrincipalMock = new Mock<IPrincipal>();
Rule = new AutoApproveRule(PrincipalMock.Object);
}
private AutoApproveRule Rule { get; }
private Mock<IPrincipal> PrincipalMock { get; }
[Fact]
public async Task Should_ReturnSuccess_WhenAdminAndRequestMovie()
{
PrincipalMock.Setup(x => x.IsInRole(OmbiClaims.Admin)).Returns(true);
var request = new BaseRequest() { RequestType = Store.Entities.RequestType.Movie };
var result = await Rule.Execute(request);
Assert.Equal(result.Success, true);
Assert.Equal(request.Approved, true);
}
[Fact]
public async Task Should_ReturnSuccess_WhenAdminAndRequestTV()
{
PrincipalMock.Setup(x => x.IsInRole(OmbiClaims.Admin)).Returns(true);
var request = new BaseRequest() { RequestType = Store.Entities.RequestType.TvShow };
var result = await Rule.Execute(request);
Assert.Equal(result.Success, true);
Assert.Equal(request.Approved, true);
}
[Fact]
public async Task Should_ReturnSuccess_WhenAutoApproveMovieAndRequestMovie()
{
PrincipalMock.Setup(x => x.IsInRole(OmbiClaims.AutoApproveMovie)).Returns(true);
var request = new BaseRequest() { RequestType = Store.Entities.RequestType.Movie };
var result = await Rule.Execute(request);
Assert.Equal(result.Success, true);
Assert.Equal(request.Approved, true);
}
[Fact]
public async Task Should_ReturnSuccess_WhenAutoApproveTVAndRequestTV()
{
PrincipalMock.Setup(x => x.IsInRole(OmbiClaims.AutoApproveTv)).Returns(true);
var request = new BaseRequest() { RequestType = Store.Entities.RequestType.TvShow };
var result = await Rule.Execute(request);
Assert.Equal(result.Success, true);
Assert.Equal(request.Approved, true);
}
[Fact]
public async Task Should_ReturnFail_WhenNoClaimsAndRequestMovie()
{
var request = new BaseRequest() { RequestType = Store.Entities.RequestType.Movie };
var result = await Rule.Execute(request);
Assert.Equal(result.Success, true);
Assert.Equal(request.Approved, false);
}
[Fact]
public async Task Should_ReturnFail_WhenNoClaimsAndRequestTV()
{
var request = new BaseRequest() { RequestType = Store.Entities.RequestType.TvShow };
var result = await Rule.Execute(request);
Assert.Equal(result.Success, true);
Assert.Equal(request.Approved, false);
}
}
}

@ -1,84 +1,85 @@
//using System.Security.Principal;
//using System.Threading.Tasks;
//using Moq;
//using Ombi.Core.Claims;
//using Ombi.Core.Models.Requests;
//using Ombi.Core.Rule.Rules;
//using Xunit;
using System.Security.Principal;
using System.Threading.Tasks;
using Moq;
using Ombi.Core.Claims;
using Ombi.Core.Models.Requests;
using Ombi.Core.Rule.Rules;
using Ombi.Store.Entities.Requests;
using Xunit;
//namespace Ombi.Core.Tests.Rule
//{
// public class CanRequestRuleTests
// {
// public CanRequestRuleTests()
// {
// PrincipalMock = new Mock<IPrincipal>();
// Rule = new CanRequestRule(PrincipalMock.Object);
// }
namespace Ombi.Core.Tests.Rule
{
public class CanRequestRuleTests
{
public CanRequestRuleTests()
{
PrincipalMock = new Mock<IPrincipal>();
Rule = new CanRequestRule(PrincipalMock.Object);
}
// private CanRequestRule Rule { get; }
// private Mock<IPrincipal> PrincipalMock { get; }
private CanRequestRule Rule { get; }
private Mock<IPrincipal> PrincipalMock { get; }
// [Fact]
// public async Task Should_ReturnSuccess_WhenRequestingMovieWithMovieRole()
// {
// PrincipalMock.Setup(x => x.IsInRole(OmbiClaims.RequestMovie)).Returns(true);
// var request = new BaseRequestModel() { Type = Store.Entities.RequestType.Movie };
// var result = await Rule.Execute(request);
[Fact]
public async Task Should_ReturnSuccess_WhenRequestingMovieWithMovieRole()
{
PrincipalMock.Setup(x => x.IsInRole(OmbiClaims.RequestMovie)).Returns(true);
var request = new BaseRequest() { RequestType = Store.Entities.RequestType.Movie };
var result = await Rule.Execute(request);
// Assert.Equal(result.Success, true);
// }
Assert.Equal(result.Success, true);
}
// [Fact]
// public async Task Should_ReturnFail_WhenRequestingMovieWithoutMovieRole()
// {
// PrincipalMock.Setup(x => x.IsInRole(OmbiClaims.RequestMovie)).Returns(false);
// var request = new BaseRequestModel() { Type = Store.Entities.RequestType.Movie };
// var result = await Rule.Execute(request);
[Fact]
public async Task Should_ReturnFail_WhenRequestingMovieWithoutMovieRole()
{
PrincipalMock.Setup(x => x.IsInRole(OmbiClaims.RequestMovie)).Returns(false);
var request = new BaseRequest() { RequestType = Store.Entities.RequestType.Movie };
var result = await Rule.Execute(request);
// Assert.Equal(result.Success, false);
// Assert.Equal(string.IsNullOrEmpty(result.Message), false);
// }
Assert.Equal(result.Success, false);
Assert.Equal(string.IsNullOrEmpty(result.Message), false);
}
// [Fact]
// public async Task Should_ReturnSuccess_WhenRequestingMovieWithAdminRole()
// {
// PrincipalMock.Setup(x => x.IsInRole(OmbiClaims.Admin)).Returns(true);
// var request = new BaseRequestModel() { Type = Store.Entities.RequestType.Movie };
// var result = await Rule.Execute(request);
[Fact]
public async Task Should_ReturnSuccess_WhenRequestingMovieWithAdminRole()
{
PrincipalMock.Setup(x => x.IsInRole(OmbiClaims.Admin)).Returns(true);
var request = new BaseRequest() { RequestType = Store.Entities.RequestType.Movie };
var result = await Rule.Execute(request);
// Assert.Equal(result.Success, true);
// }
Assert.Equal(result.Success, true);
}
// [Fact]
// public async Task Should_ReturnSuccess_WhenRequestingTVWithAdminRole()
// {
// PrincipalMock.Setup(x => x.IsInRole(OmbiClaims.Admin)).Returns(true);
// var request = new BaseRequestModel() { Type = Store.Entities.RequestType.TvShow };
// var result = await Rule.Execute(request);
[Fact]
public async Task Should_ReturnSuccess_WhenRequestingTVWithAdminRole()
{
PrincipalMock.Setup(x => x.IsInRole(OmbiClaims.Admin)).Returns(true);
var request = new BaseRequest() { RequestType = Store.Entities.RequestType.TvShow };
var result = await Rule.Execute(request);
// Assert.Equal(result.Success, true);
// }
Assert.Equal(result.Success, true);
}
// [Fact]
// public async Task Should_ReturnSuccess_WhenRequestingTVWithTVRole()
// {
// PrincipalMock.Setup(x => x.IsInRole(OmbiClaims.RequestTv)).Returns(true);
// var request = new BaseRequestModel() { Type = Store.Entities.RequestType.TvShow };
// var result = await Rule.Execute(request);
[Fact]
public async Task Should_ReturnSuccess_WhenRequestingTVWithTVRole()
{
PrincipalMock.Setup(x => x.IsInRole(OmbiClaims.RequestTv)).Returns(true);
var request = new BaseRequest() { RequestType = Store.Entities.RequestType.TvShow };
var result = await Rule.Execute(request);
// Assert.Equal(result.Success, true);
// }
Assert.Equal(result.Success, true);
}
// [Fact]
// public async Task Should_ReturnFail_WhenRequestingTVWithoutTVRole()
// {
// PrincipalMock.Setup(x => x.IsInRole(OmbiClaims.RequestTv)).Returns(false);
// var request = new BaseRequestModel() { Type = Store.Entities.RequestType.TvShow };
// var result = await Rule.Execute(request);
[Fact]
public async Task Should_ReturnFail_WhenRequestingTVWithoutTVRole()
{
PrincipalMock.Setup(x => x.IsInRole(OmbiClaims.RequestTv)).Returns(false);
var request = new BaseRequest() { RequestType = Store.Entities.RequestType.TvShow };
var result = await Rule.Execute(request);
// Assert.Equal(result.Success, false);
// Assert.Equal(string.IsNullOrEmpty(result.Message), false);
// }
// }
//}
Assert.Equal(result.Success, false);
Assert.Equal(string.IsNullOrEmpty(result.Message), false);
}
}
}

@ -1,110 +1,128 @@
//using System.Collections.Generic;
//using System.Threading.Tasks;
//using Moq;
//using Ombi.Core.Models.Requests;
//using Ombi.Core.Models.Requests.Movie;
//using Ombi.Core.Models.Requests.Tv;
//using Ombi.Core.Models.Search;
//using Ombi.Core.Requests.Models;
//using Ombi.Core.Rule.Rules.Search;
//using Xunit;
//namespace Ombi.Core.Tests.Rule.Search
//{
// public class ExistignRequestRuleTests
// {
// public ExistignRequestRuleTests()
// {
// MovieMock = new Mock<IRequestService<MovieRequestModel>>();
// TvMock = new Mock<IRequestService<TvRequestModel>>();
// Rule = new ExistingRequestRule(MovieMock.Object, TvMock.Object);
// }
// private ExistingRequestRule Rule { get; }
// private Mock<IRequestService<MovieRequestModel>> MovieMock { get; }
// private Mock<IRequestService<TvRequestModel>> TvMock { get; }
// [Fact]
// public async Task ShouldBe_Requested_WhenExisitngMovie()
// {
// var list = new List<MovieRequestModel>{new MovieRequestModel
// {
// ProviderId = 123,
// Approved = true
// }};
// MovieMock.Setup(x => x.GetAllAsync()).ReturnsAsync(list);
// var search = new SearchMovieViewModel
// {
// Id = 123,
// };
// var result = await Rule.Execute(search);
// Assert.True(result.Success);
// Assert.Equal(search.Approved, true);
// }
// [Fact]
// public async Task ShouldBe_NotRequested_WhenNewMovie()
// {
// var list = new List<MovieRequestModel>{new MovieRequestModel
// {
// ProviderId = 123,
// Approved = true
// }};
// MovieMock.Setup(x => x.GetAllAsync()).ReturnsAsync(list);
// var search = new SearchMovieViewModel
// {
// Id = 999,
// };
// var result = await Rule.Execute(search);
// Assert.True(result.Success);
// Assert.Equal(search.Approved, false);
// }
// [Fact]
// public async Task ShouldBe_Requested_WhenExisitngTv()
// {
// var list = new List<TvRequestModel>{new TvRequestModel
// {
// ProviderId = 123,
// Approved = true
// }};
// TvMock.Setup(x => x.GetAllAsync()).ReturnsAsync(list);
// var search = new SearchTvShowViewModel
// {
// Id = 123,
// };
// var result = await Rule.Execute(search);
// Assert.True(result.Success);
// Assert.Equal(search.Approved, true);
// }
// [Fact]
// public async Task ShouldBe_NotRequested_WhenNewTv()
// {
// var list = new List<TvRequestModel>{new TvRequestModel
// {
// ProviderId = 123,
// Approved = true
// }};
// TvMock.Setup(x => x.GetAllAsync()).ReturnsAsync(list);
// var search = new SearchTvShowViewModel()
// {
// Id = 999,
// };
// var result = await Rule.Execute(search);
// Assert.True(result.Success);
// Assert.Equal(search.Approved, false);
// }
// }
//}
using System.Collections.Generic;
using System.Threading.Tasks;
using Moq;
using Ombi.Core.Models.Search;
using Ombi.Core.Rule.Rules.Search;
using Ombi.Store.Entities.Requests;
using Ombi.Store.Repository;
using Ombi.Store.Repository.Requests;
using Xunit;
namespace Ombi.Core.Tests.Rule.Search
{
public class ExistignRequestRuleTests
{
public ExistignRequestRuleTests()
{
MovieMock = new Mock<IMovieRequestRepository>();
TvMock = new Mock<ITvRequestRepository>();
Rule = new ExistingRule(MovieMock.Object, TvMock.Object);
}
private ExistingRule Rule { get; }
private Mock<IMovieRequestRepository> MovieMock { get; }
private Mock<ITvRequestRepository> TvMock { get; }
[Fact]
public async Task ShouldBe_Requested_WhenExisitngMovie()
{
var list = new MovieRequests
{
TheMovieDbId = 123,
Approved = true
};
MovieMock.Setup(x => x.GetRequest(123)).ReturnsAsync(list);
var search = new SearchMovieViewModel
{
Id = 123,
};
var result = await Rule.Execute(search);
Assert.True(result.Success);
Assert.Equal(search.Approved, true);
}
[Fact]
public async Task ShouldBe_NotRequested_WhenNewMovie()
{
var list = new MovieRequests
{
TheMovieDbId = 123,
Approved = true
};
MovieMock.Setup(x => x.GetRequest(123)).ReturnsAsync(list);
var search = new SearchMovieViewModel
{
Id = 999,
};
var result = await Rule.Execute(search);
Assert.True(result.Success);
Assert.Equal(search.Approved, false);
}
[Fact]
public async Task ShouldBe_Requested_WhenExisitngTv()
{
var list = new TvRequests
{
TvDbId = 123,
ChildRequests = new List<ChildRequests>
{
new ChildRequests()
{
Approved = true
}
}
};
TvMock.Setup(x => x.GetRequest(123)).ReturnsAsync(list);
var search = new SearchTvShowViewModel
{
Id = 123,
};
var result = await Rule.Execute(search);
Assert.True(result.Success);
Assert.Equal(search.Approved, true);
}
[Fact]
public async Task ShouldBe_NotRequested_WhenNewTv()
{
var list = new TvRequests
{
TvDbId = 123,
ChildRequests = new List<ChildRequests>
{
new ChildRequests()
{
Approved = true
}
}
};
TvMock.Setup(x => x.GetRequest(123)).ReturnsAsync(list);
var search = new SearchTvShowViewModel()
{
Id = 999,
};
var result = await Rule.Execute(search);
Assert.True(result.Success);
Assert.Equal(search.Approved, false);
}
}
}

@ -1,6 +1,5 @@
using Ombi.Core.Engine.Interfaces;
using Ombi.Core.Models.Requests;
using Ombi.Core.Rules;
using Ombi.Helpers;
using System;
using System.Collections.Generic;
@ -8,6 +7,7 @@ using System.Linq;
using System.Security.Principal;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Ombi.Core.Rule.Interfaces;
using Ombi.Store.Entities.Requests;
using Ombi.Store.Repository;
using Ombi.Store.Repository.Requests;

@ -1,10 +1,10 @@
using Ombi.Core.Claims;
using Ombi.Core.Rule;
using Ombi.Core.Rules;
using System.Collections.Generic;
using System.Security.Principal;
using System.Threading.Tasks;
using Ombi.Core.Models.Search;
using Ombi.Core.Rule.Interfaces;
using Ombi.Store.Entities.Requests;
namespace Ombi.Core.Engine.Interfaces
@ -48,5 +48,10 @@ namespace Ombi.Core.Engine.Interfaces
var ruleResults = await Rules.StartSearchRules(model);
return ruleResults;
}
public async Task<RuleResult> RunSpecificRule(object model, SpecificRules rule)
{
var ruleResults = await Rules.StartSpecificRules(model, rule);
return ruleResults;
}
}
}

@ -15,8 +15,7 @@ namespace Ombi.Core
Task<IEnumerable<SearchMovieViewModel>> TopRatedMovies();
Task<IEnumerable<SearchMovieViewModel>> UpcomingMovies();
Task<IEnumerable<SearchMovieViewModel>> LookupImdbInformation(IEnumerable<SearchMovieViewModel> movies);
Task<SearchMovieViewModel> LookupImdbInformation(int theMovieDbId);
}
}

@ -1,7 +1,6 @@
using Ombi.Api.TheMovieDb;
using Ombi.Core.Models.Requests;
using Ombi.Core.Models.Search;
using Ombi.Core.Rules;
using Ombi.Helpers;
using Ombi.Store.Entities;
using System;
@ -14,7 +13,7 @@ using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Ombi.Core.Engine.Interfaces;
using Ombi.Core.IdentityResolver;
using Ombi.Core.Rule;
using Ombi.Core.Rule.Interfaces;
using Ombi.Store.Entities.Requests;
namespace Ombi.Core.Engine
@ -37,6 +36,11 @@ namespace Ombi.Core.Engine
private ILogger<MovieRequestEngine> Logger { get; }
private IUserIdentityManager UserManager { get; }
/// <summary>
/// Requests the movie.
/// </summary>
/// <param name="model">The model.</param>
/// <returns></returns>
public async Task<RequestEngineResult> RequestMovie(SearchMovieViewModel model)
{
var movieInfo = await MovieApi.GetMovieInformation(model.Id);
@ -52,42 +56,6 @@ namespace Ombi.Core.Engine
var fullMovieName =
$"{movieInfo.Title}{(!string.IsNullOrEmpty(movieInfo.ReleaseDate) ? $" ({DateTime.Parse(movieInfo.ReleaseDate).Year})" : string.Empty)}";
var existingRequest = await MovieRepository.GetRequest(model.Id);
if (existingRequest != null)
{
return new RequestEngineResult
{
RequestAdded = false,
Message = $"{fullMovieName} has already been requested"
};
}
// TODO
//try
//{
// var content = PlexContentRepository.GetAll();
// var movies = PlexChecker.GetPlexMovies(content);
// if (PlexChecker.IsMovieAvailable(movies.ToArray(), movieInfo.Title, movieInfo.ReleaseDate?.Year.ToString()))
// {
// return
// Response.AsJson(new JsonResponseModel
// {
// Result = false,
// Message = $"{fullMovieName} is already in Plex!"
// });
// }
//}
//catch (Exception e)
//{
// Log.Error(e);
// return
// Response.AsJson(new JsonResponseModel
// {
// Result = false,
// Message = string.Format(Resources.UI.Search_CouldNotCheckPlex, fullMovieName, GetMediaServerName())
// });
//}
var userDetails = await UserManager.GetUser(User.Identity.Name);
var requestModel = new MovieRequests
@ -107,13 +75,12 @@ namespace Ombi.Core.Engine
RequestedUserId = userDetails.Id,
};
var ruleResults = await RunRequestRules(requestModel);
var results = ruleResults as RuleResult[] ?? ruleResults.ToArray();
if (results.Any(x => !x.Success))
var ruleResults = (await RunRequestRules(requestModel)).ToList();
if (ruleResults.Any(x => !x.Success))
{
return new RequestEngineResult
{
ErrorMessage = results.FirstOrDefault(x => !string.IsNullOrEmpty(x.Message)).Message
ErrorMessage = ruleResults.FirstOrDefault(x => !string.IsNullOrEmpty(x.Message)).Message
};
}
@ -122,8 +89,7 @@ namespace Ombi.Core.Engine
var result = await Sender.Send(requestModel);
if (result.Success && result.MovieSent)
{
return await AddMovieRequest(requestModel, /*settings,*/
$"{fullMovieName} has been successfully added!");
return await AddMovieRequest(requestModel, fullMovieName);
}
if (!result.Success)
{
@ -138,24 +104,37 @@ namespace Ombi.Core.Engine
// If there are no providers then it's successful but movie has not been sent
}
return await AddMovieRequest(requestModel, /*settings,*/
$"{fullMovieName} has been successfully added!");
return await AddMovieRequest(requestModel, fullMovieName);
}
/// <summary>
/// Gets the requests.
/// </summary>
/// <param name="count">The count.</param>
/// <param name="position">The position.</param>
/// <returns></returns>
public async Task<IEnumerable<MovieRequests>> GetRequests(int count, int position)
{
var allRequests = await MovieRepository.Get().Skip(position).Take(count).ToListAsync();
return allRequests;
}
/// <summary>
/// Gets the requests.
/// </summary>
/// <returns></returns>
public async Task<IEnumerable<MovieRequests>> GetRequests()
{
var allRequests = await MovieRepository.Get().ToListAsync();
return allRequests;
}
/// <summary>
/// Searches the movie request.
/// </summary>
/// <param name="search">The search.</param>
/// <returns></returns>
public async Task<IEnumerable<MovieRequests>> SearchMovieRequest(string search)
{
var allRequests = await MovieRepository.Get().ToListAsync();
@ -163,6 +142,11 @@ namespace Ombi.Core.Engine
return results;
}
/// <summary>
/// Updates the movie request.
/// </summary>
/// <param name="request">The request.</param>
/// <returns></returns>
public async Task<MovieRequests> UpdateMovieRequest(MovieRequests request)
{
var allRequests = await MovieRepository.Get().ToListAsync();
@ -183,13 +167,18 @@ namespace Ombi.Core.Engine
return results;
}
/// <summary>
/// Removes the movie request.
/// </summary>
/// <param name="requestId">The request identifier.</param>
/// <returns></returns>
public async Task RemoveMovieRequest(int requestId)
{
var request = await MovieRepository.Get().FirstOrDefaultAsync(x => x.Id == requestId);
await MovieRepository.Delete(request);
}
private async Task<RequestEngineResult> AddMovieRequest(MovieRequests model, string message)
private async Task<RequestEngineResult> AddMovieRequest(MovieRequests model, string movieName)
{
await MovieRepository.Add(model);
@ -198,25 +187,7 @@ namespace Ombi.Core.Engine
NotificationHelper.NewRequest(model);
}
//var limit = await RequestLimitRepo.GetAllAsync();
//var usersLimit = limit.FirstOrDefault(x => x.Username == Username && x.RequestType == model.Type);
//if (usersLimit == null)
//{
// await RequestLimitRepo.InsertAsync(new RequestLimit
// {
// Username = Username,
// RequestType = model.Type,
// FirstRequestDate = DateTime.UtcNow,
// RequestCount = 1
// });
//}
//else
//{
// usersLimit.RequestCount++;
// await RequestLimitRepo.UpdateAsync(usersLimit);
//}
return new RequestEngineResult { RequestAdded = true, Message = message };
return new RequestEngineResult { RequestAdded = true, Message = $"{movieName} has been successfully added!" };
}
public async Task<IEnumerable<MovieRequests>> GetApprovedRequests()

@ -4,7 +4,6 @@ using Ombi.Api.TheMovieDb;
using Ombi.Api.TheMovieDb.Models;
using Ombi.Core.Models.Requests;
using Ombi.Core.Models.Search;
using Ombi.Core.Rules;
using Ombi.Core.Settings;
using Ombi.Core.Settings.Models.External;
using Ombi.Store.Repository;
@ -12,6 +11,7 @@ using System.Collections.Generic;
using System.Linq;
using System.Security.Principal;
using System.Threading.Tasks;
using Ombi.Core.Rule.Interfaces;
using StackExchange.Profiling;
namespace Ombi.Core.Engine
@ -19,60 +19,36 @@ namespace Ombi.Core.Engine
public class MovieSearchEngine : BaseMediaEngine, IMovieEngine
{
public MovieSearchEngine(IPrincipal identity, IRequestServiceMain service, IMovieDbApi movApi, IMapper mapper,
ISettingsService<PlexSettings> plexSettings,
ISettingsService<EmbySettings> embySettings, IPlexContentRepository repo,
ILogger<MovieSearchEngine> logger, IRuleEvaluator r)
: base(identity, service, r)
{
MovieApi = movApi;
Mapper = mapper;
PlexSettings = plexSettings;
EmbySettings = embySettings;
Logger = logger;
PlexContentRepo = repo;
}
private IMovieDbApi MovieApi { get; }
private IMapper Mapper { get; }
private ISettingsService<PlexSettings> PlexSettings { get; }
private ISettingsService<EmbySettings> EmbySettings { get; }
private ILogger<MovieSearchEngine> Logger { get; }
private IPlexContentRepository PlexContentRepo { get; }
public async Task<IEnumerable<SearchMovieViewModel>> LookupImdbInformation(
IEnumerable<SearchMovieViewModel> movies)
{
var searchMovieViewModels
= movies as IList<SearchMovieViewModel> ?? movies.ToList();
if (searchMovieViewModels == null || !searchMovieViewModels.Any())
return new List<SearchMovieViewModel>();
var retVal = new List<SearchMovieViewModel>();
var plexSettings = await PlexSettings.GetSettingsAsync();
var embySettings = await EmbySettings.GetSettingsAsync();
foreach (var m in searchMovieViewModels)
{
var movieInfo = await MovieApi.GetMovieInformationWithVideo(m.Id);
var viewMovie = Mapper.Map<SearchMovieViewModel>(movieInfo);
retVal.Add(await ProcessSingleMovie(viewMovie, plexSettings, embySettings));
}
return retVal;
}
/// <summary>
/// Lookups the imdb information.
/// </summary>
/// <param name="theMovieDbId">The movie database identifier.</param>
/// <returns></returns>
public async Task<SearchMovieViewModel> LookupImdbInformation(int theMovieDbId)
{
var plexSettings = await PlexSettings.GetSettingsAsync();
var embySettings = await EmbySettings.GetSettingsAsync();
var movieInfo = await MovieApi.GetMovieInformationWithVideo(theMovieDbId);
var viewMovie = Mapper.Map<SearchMovieViewModel>(movieInfo);
return await ProcessSingleMovie(viewMovie, plexSettings, embySettings, true);
return await ProcessSingleMovie(viewMovie, true);
}
/// <summary>
/// Searches the specified movie.
/// </summary>
/// <param name="search">The search.</param>
/// <returns></returns>
public async Task<IEnumerable<SearchMovieViewModel>> Search(string search)
{
using (MiniProfiler.Current.Step("Starting Movie Search Engine"))
@ -89,12 +65,14 @@ namespace Ombi.Core.Engine
}
}
return null;
}
}
/// <summary>
/// Gets popular movies.
/// </summary>
/// <returns></returns>
public async Task<IEnumerable<SearchMovieViewModel>> PopularMovies()
{
var result = await MovieApi.PopularMovies();
@ -106,6 +84,10 @@ namespace Ombi.Core.Engine
return null;
}
/// <summary>
/// Gets top rated movies.
/// </summary>
/// <returns></returns>
public async Task<IEnumerable<SearchMovieViewModel>> TopRatedMovies()
{
var result = await MovieApi.TopRated();
@ -117,6 +99,10 @@ namespace Ombi.Core.Engine
return null;
}
/// <summary>
/// Gets upcoming movies.
/// </summary>
/// <returns></returns>
public async Task<IEnumerable<SearchMovieViewModel>> UpcomingMovies()
{
var result = await MovieApi.Upcoming();
@ -128,6 +114,10 @@ namespace Ombi.Core.Engine
return null;
}
/// <summary>
/// Gets now playing movies.
/// </summary>
/// <returns></returns>
public async Task<IEnumerable<SearchMovieViewModel>> NowPlayingMovies()
{
var result = await MovieApi.NowPlaying();
@ -142,45 +132,20 @@ namespace Ombi.Core.Engine
private async Task<List<SearchMovieViewModel>> TransformMovieResultsToResponse(
IEnumerable<MovieSearchResult> movies)
{
var viewMovies = new List<SearchMovieViewModel>();
Settings.Models.External.PlexSettings plexSettings;
Settings.Models.External.EmbySettings embySettings;
using (MiniProfiler.Current.Step("Gettings Movies and Settings"))
{
plexSettings = await PlexSettings.GetSettingsAsync();
embySettings = await EmbySettings.GetSettingsAsync();
}
foreach (var movie in movies)
{
viewMovies.Add(await ProcessSingleMovie(movie, plexSettings, embySettings));
viewMovies.Add(await ProcessSingleMovie(movie));
}
return viewMovies;
}
private async Task<SearchMovieViewModel> ProcessSingleMovie(SearchMovieViewModel viewMovie,
PlexSettings plexSettings, EmbySettings embySettings, bool lookupExtraInfo = false)
private async Task<SearchMovieViewModel> ProcessSingleMovie(SearchMovieViewModel viewMovie, bool lookupExtraInfo = false)
{
if (plexSettings.Enable)
{
if (lookupExtraInfo)
{
var showInfo = await MovieApi.GetMovieInformation(viewMovie.Id);
viewMovie.Id = showInfo.Id; // TheMovieDbId
}
}
if (embySettings.Enable)
if (lookupExtraInfo)
{
// var embyContent = EmbyContentRepository.GetAll();
// var embyMovies = EmbyChecker.GetEmbyMovies(embyContent);
// var embyMovie = EmbyChecker.GetMovie(embyMovies.ToArray(), movie.Title,
// movie.ReleaseDate?.Year.ToString(), viewMovie.ImdbId);
// if (embyMovie != null)
// {
// viewMovie.Available = true;
// }
var showInfo = await MovieApi.GetMovieInformation(viewMovie.Id);
viewMovie.Id = showInfo.Id; // TheMovieDbId
}
await RunSearchRules(viewMovie);
@ -189,10 +154,10 @@ namespace Ombi.Core.Engine
}
private async Task<SearchMovieViewModel> ProcessSingleMovie(MovieSearchResult movie, PlexSettings plexSettings, EmbySettings embySettings)
private async Task<SearchMovieViewModel> ProcessSingleMovie(MovieSearchResult movie)
{
var viewMovie = Mapper.Map<SearchMovieViewModel>(movie);
return await ProcessSingleMovie(viewMovie, plexSettings, embySettings);
return await ProcessSingleMovie(viewMovie);
}
}
}

@ -2,7 +2,6 @@
using Ombi.Api.TvMaze;
using Ombi.Core.Models.Requests;
using Ombi.Core.Models.Search;
using Ombi.Core.Rules;
using Ombi.Helpers;
using Ombi.Store.Entities;
using System;
@ -15,6 +14,7 @@ using Microsoft.EntityFrameworkCore;
using Ombi.Core.Engine.Interfaces;
using Ombi.Core.IdentityResolver;
using Ombi.Core.Rule;
using Ombi.Core.Rule.Interfaces;
using Ombi.Store.Entities.Requests;
using Ombi.Store.Repository.Requests;
@ -71,11 +71,6 @@ namespace Ombi.Core.Engine
{
Id = tv.Id,
RequestType = RequestType.TvShow,
//Overview = showInfo.summary.RemoveHtml(),
//PosterPath = posterPath,
//Title = showInfo.name,
//ReleaseDate = firstAir,
//Status = showInfo.status,
RequestedDate = DateTime.UtcNow,
Approved = false,
RequestedUserId = user.Id,
@ -85,10 +80,8 @@ namespace Ombi.Core.Engine
if (tv.RequestAll)
{
var episodes = await TvApi.EpisodeLookup(showInfo.id);
var seasonRequests = new List<SeasonRequests>();
foreach (var ep in episodes)
{
var episodesRequests = new List<EpisodeRequests>();
var season = childRequest.SeasonRequests.FirstOrDefault(x => x.SeasonNumber == ep.season);
if (season == null)
{
@ -184,7 +177,6 @@ namespace Ombi.Core.Engine
if (existingRequest != null)
{
// Remove requests we already have, we just want new ones
var existingSeasons = existingRequest.ChildRequests.Select(x => x.SeasonRequests);
foreach (var existingSeason in existingRequest.ChildRequests)
foreach (var existing in existingSeason.SeasonRequests)
{
@ -259,7 +251,6 @@ namespace Ombi.Core.Engine
results = Mapper.Map<TvRequests>(request);
// TODO need to check if we need to approve any child requests since they may have updated
await TvRepository.Update(results);
return results;
}
@ -277,10 +268,6 @@ namespace Ombi.Core.Engine
await TvRepository.Update(existingRequest);
if (newRequest.Approved) // The auto approve rule
{
// TODO Auto Approval Code
}
return await AfterRequest(newRequest);
}
@ -291,9 +278,10 @@ namespace Ombi.Core.Engine
return await AfterRequest(model.ChildRequests.FirstOrDefault());
}
private Task<RequestEngineResult> AfterRequest(ChildRequests model)
private async Task<RequestEngineResult> AfterRequest(ChildRequests model)
{
if (ShouldSendNotification(model))
var sendRuleResult = await RunSpecificRule(model, SpecificRules.CanSendNotification);
if (sendRuleResult.Success)
{
NotificationHelper.NewRequest(model);
}
@ -301,28 +289,10 @@ namespace Ombi.Core.Engine
if(model.Approved)
{
// Autosend
TvSender.SendToSonarr(model);
await TvSender.SendToSonarr(model);
}
//var limit = await RequestLimitRepo.GetAllAsync();
//var usersLimit = limit.FirstOrDefault(x => x.Username == Username && x.RequestType == model.Type);
//if (usersLimit == null)
//{
// await RequestLimitRepo.InsertAsync(new RequestLimit
// {
// Username = Username,
// RequestType = model.Type,
// FirstRequestDate = DateTime.UtcNow,
// RequestCount = 1
// });
//}
//else
//{
// usersLimit.RequestCount++;
// await RequestLimitRepo.UpdateAsync(usersLimit);
//}
return Task.FromResult(new RequestEngineResult { RequestAdded = true });
return new RequestEngineResult { RequestAdded = true };
}
//public async Task<IEnumerable<TvRequests>> GetApprovedRequests()

@ -5,7 +5,6 @@ using Ombi.Api.TvMaze;
using Ombi.Core.Engine.Interfaces;
using Ombi.Core.Models.Requests;
using Ombi.Core.Models.Search;
using Ombi.Core.Rules;
using Ombi.Core.Settings;
using Ombi.Core.Settings.Models.External;
using Ombi.Store.Repository;
@ -15,6 +14,7 @@ using System.Collections.Generic;
using System.Linq;
using System.Security.Principal;
using System.Threading.Tasks;
using Ombi.Core.Rule.Interfaces;
using Ombi.Store.Entities.Requests;
using Ombi.Store.Repository.Requests;

@ -9,7 +9,7 @@
public RuleResult Fail(string message)
{
return new RuleResult {Message = message};
return new RuleResult { Message = message };
}
}
}

@ -1,15 +1,14 @@
using Ombi.Core.Models.Requests;
using Ombi.Core.Rule;
using System.Collections.Generic;
using System.Collections.Generic;
using System.Threading.Tasks;
using Ombi.Core.Models.Search;
using Ombi.Store.Entities.Requests;
namespace Ombi.Core.Rules
namespace Ombi.Core.Rule.Interfaces
{
public interface IRuleEvaluator
{
Task<IEnumerable<RuleResult>> StartRequestRules(BaseRequest obj);
Task<IEnumerable<RuleResult>> StartSearchRules(SearchViewModel obj);
Task<RuleResult> StartSpecificRules(object obj, SpecificRules selectedRule);
}
}

@ -3,7 +3,7 @@ using Ombi.Core.Models.Requests;
namespace Ombi.Core.Rule.Interfaces
{
public interface IRequestRules<T> where T : new()
public interface IRules<T> where T : new()
{
Task<RuleResult> Execute(T obj);
}

@ -0,0 +1,11 @@
using System.Threading.Tasks;
using Ombi.Core.Models.Requests;
namespace Ombi.Core.Rule.Interfaces
{
public interface ISpecificRule<T> where T : new()
{
Task<RuleResult> Execute(T obj);
SpecificRules Rule { get; }
}
}

@ -0,0 +1,7 @@
namespace Ombi.Core.Rule.Interfaces
{
public enum SpecificRules
{
CanSendNotification,
}
}

@ -1,5 +1,4 @@
using Ombi.Core.Models.Requests;
using Ombi.Core.Rules;
using System;
using System.Collections.Generic;
using System.Linq;
@ -7,6 +6,7 @@ using System.Reflection;
using System.Threading.Tasks;
using Ombi.Core.Models.Search;
using Ombi.Core.Rule.Interfaces;
using Ombi.Helpers;
using Ombi.Store.Entities.Requests;
namespace Ombi.Core.Rule
@ -15,13 +15,66 @@ namespace Ombi.Core.Rule
{
public RuleEvaluator(IServiceProvider provider)
{
RequestRules = new List<IRequestRules<BaseRequest>>();
SearchRules = new List<IRequestRules<SearchViewModel>>();
RequestRules = new List<IRules<BaseRequest>>();
SearchRules = new List<IRules<SearchViewModel>>();
SpecificRules = new List<ISpecificRule<object>>();
var baseSearchType = typeof(BaseRequestRule).FullName;
var baseRequestType = typeof(BaseSearchRule).FullName;
var baseSpecificRuleType = typeof(SpecificRule).FullName;
var ass = typeof(RuleEvaluator).GetTypeInfo().Assembly;
GetTypes(provider, ass, baseSearchType, RequestRules);
GetTypes(provider, ass, baseRequestType, SearchRules);
GetTypes(provider, ass, baseSpecificRuleType, SpecificRules);
}
private List<IRules<BaseRequest>> RequestRules { get; }
private List<IRules<SearchViewModel>> SearchRules { get; }
private List<ISpecificRule<object>> SpecificRules { get; }
public async Task<IEnumerable<RuleResult>> StartRequestRules(BaseRequest obj)
{
var results = new List<RuleResult>();
foreach (var rule in RequestRules)
{
var result = await rule.Execute(obj);
results.Add(result);
}
return results;
}
public async Task<IEnumerable<RuleResult>> StartSearchRules(SearchViewModel obj)
{
var results = new List<RuleResult>();
foreach (var rule in SearchRules)
{
var result = await rule.Execute(obj);
results.Add(result);
}
return results;
}
public async Task<RuleResult> StartSpecificRules(object obj, SpecificRules selectedRule)
{
foreach (var rule in SpecificRules)
{
if (selectedRule == rule.Rule)
{
var result = await rule.Execute(obj);
return result;
}
}
throw new RuleNotFoundException(nameof(selectedRule));
}
private void GetTypes<T>(IServiceProvider provider, Assembly ass, string baseSearchType, List<IRules<T>> ruleList) where T : new()
{
foreach (var ti in ass.DefinedTypes)
{
if (ti?.BaseType?.FullName == baseSearchType)
@ -37,13 +90,16 @@ namespace Ombi.Core.Rule
}
var item = Activator.CreateInstance(type, services.ToArray());
RequestRules.Add((IRequestRules<BaseRequest>) item);
ruleList.Add((IRules<T>)item);
}
}
}
private void GetTypes<T>(IServiceProvider provider, Assembly ass, string baseSearchType, ICollection<ISpecificRule<T>> ruleList) where T : new()
{
foreach (var ti in ass.DefinedTypes)
{
if (ti?.BaseType?.FullName == baseRequestType)
if (ti?.BaseType?.FullName == baseSearchType)
{
var type = ti?.AsType();
var ctors = type.GetConstructors();
@ -56,36 +112,9 @@ namespace Ombi.Core.Rule
}
var item = Activator.CreateInstance(type, services.ToArray());
SearchRules.Add((IRequestRules<SearchViewModel>) item);
ruleList.Add((ISpecificRule<T>)item);
}
}
}
private List<IRequestRules<BaseRequest>> RequestRules { get; }
private List<IRequestRules<SearchViewModel>> SearchRules { get; }
public async Task<IEnumerable<RuleResult>> StartRequestRules(BaseRequest obj)
{
var results = new List<RuleResult>();
foreach (var rule in RequestRules)
{
var result = await rule.Execute(obj);
results.Add(result);
}
return results;
}
public async Task<IEnumerable<RuleResult>> StartSearchRules(SearchViewModel obj)
{
var results = new List<RuleResult>();
foreach (var rule in SearchRules)
{
var result = await rule.Execute(obj);
results.Add(result);
}
return results;
}
}
}

@ -8,7 +8,7 @@ using Ombi.Store.Entities.Requests;
namespace Ombi.Core.Rule.Rules.Request
{
public class AutoApproveRule : BaseRequestRule, IRequestRules<BaseRequest>
public class AutoApproveRule : BaseRequestRule, IRules<BaseRequest>
{
public AutoApproveRule(IPrincipal principal)
{

@ -7,7 +7,7 @@ using Ombi.Store.Entities.Requests;
namespace Ombi.Core.Rule.Rules
{
public class CanRequestRule : BaseRequestRule, IRequestRules<BaseRequest>
public class CanRequestRule : BaseRequestRule, IRules<BaseRequest>
{
public CanRequestRule(IPrincipal principal)
{

@ -0,0 +1,39 @@
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Ombi.Core.Rule.Interfaces;
using Ombi.Store.Entities;
using Ombi.Store.Entities.Requests;
using Ombi.Store.Repository;
namespace Ombi.Core.Rule.Rules.Request
{
public class ExistingMovieRequestRule : BaseRequestRule, IRules<BaseRequest>
{
public ExistingMovieRequestRule(IMovieRequestRepository movie)
{
Movie = movie;
}
private IMovieRequestRepository Movie { get; }
/// <summary>
/// We check if the request exists, if it does then we don't want to re-request it.
/// </summary>
/// <param name="obj">The object.</param>
/// <returns></returns>
public async Task<RuleResult> Execute(BaseRequest obj)
{
if (obj.RequestType == RequestType.Movie)
{
var movieRequests = Movie.Get();
var existing = await movieRequests.FirstOrDefaultAsync(x => x.TheMovieDbId == obj.Id);
if (existing != null) // Do we already have a request for this?
{
return Fail($"{obj.Title} has already been requested");
}
}
return Success();
}
}
}

@ -1,50 +0,0 @@
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Ombi.Core.Models.Search;
using Ombi.Core.Rule.Interfaces;
using Ombi.Store.Repository;
using Ombi.Store.Repository.Requests;
namespace Ombi.Core.Rule.Rules.Search
{
public class ExistingRequestRule : BaseSearchRule, IRequestRules<SearchViewModel>
{
public ExistingRequestRule(IMovieRequestRepository movie, ITvRequestRepository tv)
{
Movie = movie;
Tv = tv;
}
private IMovieRequestRepository Movie { get; }
private ITvRequestRepository Tv { get; }
public async Task<RuleResult> Execute(SearchViewModel obj)
{
var movieRequests = Movie.Get();
var existing = await movieRequests.FirstOrDefaultAsync(x => x.TheMovieDbId == obj.Id);
if (existing != null) // Do we already have a request for this?
{
obj.Requested = true;
obj.Approved = existing.Approved;
obj.Available = existing.Available;
return Success();
}
var tvRequests = Tv.Get();
var tv = await tvRequests.FirstOrDefaultAsync(x => x.TvDbId == obj.Id);
if (tv != null) // Do we already have a request for this?
{
obj.Requested = true;
obj.Approved = tv.ChildRequests.Any(x => x.Approved);
obj.Available = tv.ChildRequests.Any(x => x.Available);
return Success();
}
return Success();
}
}
}

@ -0,0 +1,48 @@
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Ombi.Core.Models.Search;
using Ombi.Core.Rule.Interfaces;
using Ombi.Store.Repository;
using Ombi.Store.Repository.Requests;
namespace Ombi.Core.Rule.Rules.Search
{
public class ExistingRule : BaseSearchRule, IRules<SearchViewModel>
{
public ExistingRule(IMovieRequestRepository movie, ITvRequestRepository tv)
{
Movie = movie;
Tv = tv;
}
private IMovieRequestRepository Movie { get; }
private ITvRequestRepository Tv { get; }
public async Task<RuleResult> Execute(SearchViewModel obj)
{
var movieRequests = await Movie.GetRequest(obj.Id);
if (movieRequests != null) // Do we already have a request for this?
{
obj.Requested = true;
obj.Approved = movieRequests.Approved;
obj.Available = movieRequests.Available;
return Success();
}
var tvRequests = await Tv.GetRequest(obj.Id);
if (tvRequests != null) // Do we already have a request for this?
{
obj.Requested = true;
obj.Approved = tvRequests.ChildRequests.Any(x => x.Approved);
obj.Available = tvRequests.ChildRequests.Any(x => x.Available);
return Success();
}
return Success();
}
}
}

@ -5,7 +5,7 @@ using Ombi.Store.Repository;
namespace Ombi.Core.Rule.Rules.Search
{
public class PlexAvailabilityRule : BaseSearchRule, IRequestRules<SearchViewModel>
public class PlexAvailabilityRule : BaseSearchRule, IRules<SearchViewModel>
{
public PlexAvailabilityRule(IPlexContentRepository repo)
{

@ -6,7 +6,7 @@ using Ombi.Store.Context;
namespace Ombi.Core.Rule.Rules.Search
{
public class RadarrCacheRule : BaseSearchRule, IRequestRules<SearchViewModel>
public class RadarrCacheRule : BaseSearchRule, IRules<SearchViewModel>
{
public RadarrCacheRule(IOmbiContext ctx)
{

@ -0,0 +1,32 @@
using System.Security.Principal;
using System.Threading.Tasks;
using Ombi.Core.Claims;
using Ombi.Core.Rule.Interfaces;
using Ombi.Store.Entities.Requests;
namespace Ombi.Core.Rule.Rules.Specific
{
public class SendNotificationRule : SpecificRule, ISpecificRule<object>
{
public SendNotificationRule(IPrincipal principal)
{
User = principal;
}
public override SpecificRules Rule => SpecificRules.CanSendNotification;
private IPrincipal User { get; }
public Task<RuleResult> Execute(object obj)
{
var req = (BaseRequest)obj;
var sendNotification = !req.Approved; /*|| !prSettings.IgnoreNotifyForAutoApprovedRequests;*/
if (User.IsInRole(OmbiClaims.Admin))
sendNotification = false; // Don't bother sending a notification if the user is an admin
return Task.FromResult(new RuleResult
{
Success = sendNotification
});
}
}
}

@ -0,0 +1,19 @@
using Ombi.Core.Rule.Interfaces;
namespace Ombi.Core.Rule
{
public abstract class SpecificRule
{
public RuleResult Success()
{
return new RuleResult { Success = true };
}
public RuleResult Fail(string message)
{
return new RuleResult { Message = message };
}
public abstract SpecificRules Rule { get; }
}
}

@ -25,10 +25,10 @@ using Ombi.Schedule.Jobs;
using Ombi.Settings.Settings;
using Ombi.Store.Context;
using Ombi.Store.Repository;
using Ombi.Core.Rules;
using Ombi.Notifications.Agents;
using Ombi.Schedule.Jobs.Radarr;
using Ombi.Api;
using Ombi.Core.Rule.Interfaces;
using Ombi.Store.Repository.Requests;
namespace Ombi.DependencyInjection

@ -0,0 +1,12 @@
using System;
namespace Ombi.Helpers
{
public class RuleNotFoundException : Exception
{
public RuleNotFoundException(string rule) : base($"rule: {rule} was not found")
{
}
}
}

@ -6,7 +6,7 @@ namespace Ombi.Store.Entities.Requests
{
public class BaseRequest : Entity
{
public string Title { get; set; }
public bool Approved { get; set; }
public DateTime RequestedDate { get; set; }
public bool Available { get; set; }

@ -8,7 +8,6 @@ namespace Ombi.Store.Entities.Requests
{
public string ImdbId { get; set; }
public string Overview { get; set; }
public string Title { get; set; }
public string PosterPath { get; set; }
public DateTime ReleaseDate { get; set; }
public string Status { get; set; }

@ -146,7 +146,8 @@ namespace Ombi.Store.Migrations
ParentRequestId = table.Column<int>(nullable: false),
RequestType = table.Column<int>(nullable: false),
RequestedDate = table.Column<DateTime>(nullable: false),
RequestedUserId = table.Column<int>(nullable: false)
RequestedUserId = table.Column<int>(nullable: false),
Title = table.Column<string>(nullable: true)
},
constraints: table =>
{

@ -29,9 +29,6 @@ export class SearchService extends ServiceAuthHelpers {
topRatedMovies(): Observable<ISearchMovieResult[]> {
return this.http.get(`${this.url}/Movie/toprated`).map(this.extractData);
}
extraInfo(movies: ISearchMovieResult[]): Observable<ISearchMovieResult[]> {
return this.http.post(`${this.url}/Movie/extrainfo`, JSON.stringify(movies), { headers: this.headers }).map(this.extractData);
}
getMovieInformation(theMovieDbId: number): Observable<ISearchMovieResult> {
return this.http.get(`${this.url}/Movie/info/${theMovieDbId}`).map(this.extractData);
}

@ -25,5 +25,5 @@ export class NotificationTemplate {
{LongTime} : 16:02:34 <br/>
{ShortTime} : 16:02 <br/>
`
`;
}

@ -44,18 +44,6 @@ namespace Ombi.Controllers
}
}
/// <summary>
/// Gets extra information on the movie e.g. IMDBId
/// </summary>
/// <remarks>We use TheMovieDb as the Movie Provider</remarks>
/// <param name="model">The model.</param>
/// <returns></returns>
[HttpPost("movie/extrainfo")]
public async Task<IEnumerable<SearchMovieViewModel>> GetImdbInfo([FromBody]IEnumerable<SearchMovieViewModel> model)
{
return await MovieEngine.LookupImdbInformation(model);
}
/// <summary>
/// Gets extra information on the movie e.g. IMDBId
/// </summary>

Loading…
Cancel
Save