small cleanup #865

pull/1425/head
Jamie.Rees 8 years ago
parent ecae241049
commit e0018f63fa

@ -1,30 +1,4 @@
#region Copyright namespace Ombi.Core.Claims
// /************************************************************************
// Copyright (c) 2017 Jamie Rees
// File: OmbiClaims.cs
// Created By: Jamie Rees
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ************************************************************************/
#endregion
namespace Ombi.Core.Claims
{ {
public static class OmbiClaims public static class OmbiClaims
{ {

@ -1,20 +1,25 @@
using System; using Ombi.Core.Engine.Interfaces;
using System.Collections.Generic;
using System.Linq;
using System.Security.Principal;
using System.Threading.Tasks;
using Ombi.Core.Claims;
using Ombi.Core.Engine.Interfaces;
using Ombi.Core.Models.Requests; using Ombi.Core.Models.Requests;
using Ombi.Core.Models.Requests.Movie; using Ombi.Core.Models.Requests.Movie;
using Ombi.Core.Requests.Models; using Ombi.Core.Requests.Models;
using Ombi.Core.Rules;
using Ombi.Helpers; using Ombi.Helpers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Principal;
using System.Threading.Tasks;
namespace Ombi.Core.Engine namespace Ombi.Core.Engine
{ {
public abstract class BaseMediaEngine : BaseEngine public abstract class BaseMediaEngine : BaseEngine
{ {
protected BaseMediaEngine(IPrincipal identity, IRequestServiceMain requestService) : base(identity) private long _cacheTime;
private Dictionary<int, MovieRequestModel> _dbMovies;
private Dictionary<int, TvRequestModel> _dbTv;
protected BaseMediaEngine(IPrincipal identity, IRequestServiceMain requestService,
IRuleEvaluator rules) : base(identity, rules)
{ {
RequestService = requestService; RequestService = requestService;
} }
@ -23,13 +28,10 @@ namespace Ombi.Core.Engine
protected IRequestService<MovieRequestModel> MovieRequestService => RequestService.MovieRequestService; protected IRequestService<MovieRequestModel> MovieRequestService => RequestService.MovieRequestService;
protected IRequestService<TvRequestModel> TvRequestService => RequestService.TvRequestService; protected IRequestService<TvRequestModel> TvRequestService => RequestService.TvRequestService;
private long _cacheTime = 0;
private Dictionary<int, MovieRequestModel> _dbMovies;
private Dictionary<int, TvRequestModel> _dbTv;
protected async Task<Dictionary<int, MovieRequestModel>> GetMovieRequests() protected async Task<Dictionary<int, MovieRequestModel>> GetMovieRequests()
{ {
long now = DateTime.Now.Ticks; var now = DateTime.Now.Ticks;
if (_dbMovies == null || (now - _cacheTime) > 10000) if (_dbMovies == null || now - _cacheTime > 10000)
{ {
var allResults = await MovieRequestService.GetAllAsync(); var allResults = await MovieRequestService.GetAllAsync();
@ -42,8 +44,8 @@ namespace Ombi.Core.Engine
protected async Task<Dictionary<int, TvRequestModel>> GetTvRequests() protected async Task<Dictionary<int, TvRequestModel>> GetTvRequests()
{ {
long now = DateTime.Now.Ticks; var now = DateTime.Now.Ticks;
if (_dbTv == null || (now - _cacheTime) > 10000) if (_dbTv == null || now - _cacheTime > 10000)
{ {
var allResults = await TvRequestService.GetAllAsync(); var allResults = await TvRequestService.GetAllAsync();

@ -1,18 +1,26 @@
using System.Security.Principal; using Ombi.Core.Claims;
using Ombi.Core.Claims; using Ombi.Core.Models.Requests;
using Ombi.Core.Rule;
using Ombi.Core.Rules;
using Ombi.Store.Entities; using Ombi.Store.Entities;
using System.Collections.Generic;
using System.Linq;
using System.Security.Principal;
namespace Ombi.Core.Engine.Interfaces namespace Ombi.Core.Engine.Interfaces
{ {
public abstract class BaseEngine public abstract class BaseEngine
{ {
protected BaseEngine(IPrincipal user) protected BaseEngine(IPrincipal user, IRuleEvaluator rules)
{ {
User = user; User = user;
Rules = rules;
} }
protected IPrincipal User { get; } protected IPrincipal User { get; }
protected IRuleEvaluator Rules { get; }
protected string Username => User.Identity.Name; protected string Username => User.Identity.Name;
protected bool HasRole(string roleName) protected bool HasRole(string roleName)
@ -25,10 +33,7 @@ namespace Ombi.Core.Engine.Interfaces
var sendNotification = !ShouldAutoApprove(type); /*|| !prSettings.IgnoreNotifyForAutoApprovedRequests;*/ var sendNotification = !ShouldAutoApprove(type); /*|| !prSettings.IgnoreNotifyForAutoApprovedRequests;*/
if (HasRole(OmbiClaims.Admin)) if (HasRole(OmbiClaims.Admin))
{
sendNotification = false; // Don't bother sending a notification if the user is an admin sendNotification = false; // Don't bother sending a notification if the user is an admin
}
return sendNotification; return sendNotification;
} }
@ -43,13 +48,19 @@ namespace Ombi.Core.Engine.Interfaces
{ {
case RequestType.Movie: case RequestType.Movie:
return HasRole(OmbiClaims.AutoApproveMovie); return HasRole(OmbiClaims.AutoApproveMovie);
case RequestType.TvShow: case RequestType.TvShow:
return HasRole(OmbiClaims.AutoApproveTv); return HasRole(OmbiClaims.AutoApproveTv);
default: default:
return false; return false;
} }
} }
public IEnumerable<RuleResult> RunRules(BaseRequestModel model)
{
var ruleResults = Rules.StartRequestRules(model).ToList();
return ruleResults;
}
} }
} }

@ -1,16 +1,21 @@
using System.Collections.Generic; using Ombi.Core.Models.Search;
using System.Collections.Generic;
using System.Threading.Tasks; using System.Threading.Tasks;
using Ombi.Core.Models.Search;
namespace Ombi.Core namespace Ombi.Core
{ {
public interface IMovieEngine public interface IMovieEngine
{ {
Task<IEnumerable<SearchMovieViewModel>> NowPlayingMovies(); Task<IEnumerable<SearchMovieViewModel>> NowPlayingMovies();
Task<IEnumerable<SearchMovieViewModel>> PopularMovies(); Task<IEnumerable<SearchMovieViewModel>> PopularMovies();
Task<IEnumerable<SearchMovieViewModel>> Search(string search); Task<IEnumerable<SearchMovieViewModel>> Search(string search);
Task<IEnumerable<SearchMovieViewModel>> TopRatedMovies(); Task<IEnumerable<SearchMovieViewModel>> TopRatedMovies();
Task<IEnumerable<SearchMovieViewModel>> UpcomingMovies(); Task<IEnumerable<SearchMovieViewModel>> UpcomingMovies();
Task<IEnumerable<SearchMovieViewModel>> LookupImdbInformation(IEnumerable<SearchMovieViewModel> movies); Task<IEnumerable<SearchMovieViewModel>> LookupImdbInformation(IEnumerable<SearchMovieViewModel> movies);
} }
} }

@ -1,20 +1,26 @@
using System.Collections.Generic; using Ombi.Core.Models.Requests;
using System.Threading.Tasks;
using Ombi.Core.Models.Requests;
using Ombi.Core.Models.Requests.Movie; using Ombi.Core.Models.Requests.Movie;
using Ombi.Core.Models.Search; using Ombi.Core.Models.Search;
using Ombi.Store.Entities; using Ombi.Store.Entities;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Ombi.Core.Engine namespace Ombi.Core.Engine
{ {
public interface IMovieRequestEngine public interface IMovieRequestEngine
{ {
Task<RequestEngineResult> RequestMovie(SearchMovieViewModel model); Task<RequestEngineResult> RequestMovie(SearchMovieViewModel model);
bool ShouldAutoApprove(RequestType requestType); bool ShouldAutoApprove(RequestType requestType);
Task<IEnumerable<MovieRequestModel>> GetMovieRequests(int count, int position); Task<IEnumerable<MovieRequestModel>> GetMovieRequests(int count, int position);
Task<IEnumerable<MovieRequestModel>> SearchMovieRequest(string search); Task<IEnumerable<MovieRequestModel>> SearchMovieRequest(string search);
Task RemoveMovieRequest(int requestId); Task RemoveMovieRequest(int requestId);
Task<MovieRequestModel> UpdateMovieRequest(MovieRequestModel request); Task<MovieRequestModel> UpdateMovieRequest(MovieRequestModel request);
RequestCountModel RequestCount(); RequestCountModel RequestCount();
} }
} }

@ -1,17 +1,22 @@
using System.Collections.Generic; using Ombi.Core.Models.Requests;
using System.Threading.Tasks;
using Ombi.Core.Models.Requests;
using Ombi.Core.Models.Search; using Ombi.Core.Models.Search;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Ombi.Core.Engine namespace Ombi.Core.Engine
{ {
public interface ITvRequestEngine public interface ITvRequestEngine
{ {
Task<IEnumerable<TvRequestModel>> GetTvRequests(int count, int position); Task<IEnumerable<TvRequestModel>> GetTvRequests(int count, int position);
Task RemoveTvRequest(int requestId); Task RemoveTvRequest(int requestId);
Task<RequestEngineResult> RequestTvShow(SearchTvShowViewModel tv); Task<RequestEngineResult> RequestTvShow(SearchTvShowViewModel tv);
Task<IEnumerable<TvRequestModel>> SearchTvRequest(string search); Task<IEnumerable<TvRequestModel>> SearchTvRequest(string search);
Task<TvRequestModel> UpdateTvRequest(TvRequestModel request); Task<TvRequestModel> UpdateTvRequest(TvRequestModel request);
RequestCountModel RequestCount(); RequestCountModel RequestCount();
} }
} }

@ -1,6 +1,6 @@
using System.Collections.Generic; using Ombi.Core.Models.Search;
using System.Collections.Generic;
using System.Threading.Tasks; using System.Threading.Tasks;
using Ombi.Core.Models.Search;
namespace Ombi.Core.Engine.Interfaces namespace Ombi.Core.Engine.Interfaces
{ {
@ -9,10 +9,13 @@ namespace Ombi.Core.Engine.Interfaces
Task<IEnumerable<SearchTvShowViewModel>> Search(string searchTerm); Task<IEnumerable<SearchTvShowViewModel>> Search(string searchTerm);
Task<SearchTvShowViewModel> GetShowInformation(int tvdbId); Task<SearchTvShowViewModel> GetShowInformation(int tvdbId);
Task<IEnumerable<SearchTvShowViewModel>> Popular(); Task<IEnumerable<SearchTvShowViewModel>> Popular();
Task<IEnumerable<SearchTvShowViewModel>> Anticipated(); Task<IEnumerable<SearchTvShowViewModel>> Anticipated();
Task<IEnumerable<SearchTvShowViewModel>> MostWatches(); Task<IEnumerable<SearchTvShowViewModel>> MostWatches();
Task<IEnumerable<SearchTvShowViewModel>> Trending();
Task<IEnumerable<SearchTvShowViewModel>> Trending();
} }
} }

@ -1,62 +1,58 @@
using System; using Hangfire;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Security.Principal;
using System.Threading.Tasks;
using Hangfire;
using Ombi.Api.TheMovieDb; using Ombi.Api.TheMovieDb;
using Ombi.Api.TvMaze;
using Ombi.Core.Models.Requests; using Ombi.Core.Models.Requests;
using Ombi.Core.Models.Requests.Movie; using Ombi.Core.Models.Requests.Movie;
using Ombi.Core.Models.Search; using Ombi.Core.Models.Search;
using Ombi.Core.Requests.Models; using Ombi.Core.Rules;
using Ombi.Store.Entities;
using Ombi.Helpers; using Ombi.Helpers;
using Ombi.Notifications; using Ombi.Notifications;
using Ombi.Notifications.Models; using Ombi.Notifications.Models;
using Ombi.Store.Entities;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Security.Principal;
using System.Threading.Tasks;
namespace Ombi.Core.Engine namespace Ombi.Core.Engine
{ {
public class MovieRequestEngine : BaseMediaEngine, IMovieRequestEngine public class MovieRequestEngine : BaseMediaEngine, IMovieRequestEngine
{ {
public MovieRequestEngine(IMovieDbApi movieApi, IRequestServiceMain requestService, IPrincipal user, INotificationService notificationService) : base(user, requestService) public MovieRequestEngine(IMovieDbApi movieApi, IRequestServiceMain requestService, IPrincipal user,
INotificationService notificationService, IRuleEvaluator r) : base(user, requestService, r)
{ {
MovieApi = movieApi; MovieApi = movieApi;
NotificationService = notificationService; NotificationService = notificationService;
} }
private IMovieDbApi MovieApi { get; } private IMovieDbApi MovieApi { get; }
private INotificationService NotificationService { get; } private INotificationService NotificationService { get; }
public async Task<RequestEngineResult> RequestMovie(SearchMovieViewModel model) public async Task<RequestEngineResult> RequestMovie(SearchMovieViewModel model)
{ {
var movieInfo = await MovieApi.GetMovieInformation(model.Id); var movieInfo = await MovieApi.GetMovieInformation(model.Id);
if (movieInfo == null) if (movieInfo == null)
{
return new RequestEngineResult return new RequestEngineResult
{ {
RequestAdded = false, RequestAdded = false,
Message = "There was an issue adding this movie!", Message = "There was an issue adding this movie!",
ErrorMessage = $"TheMovieDb didn't have any information for ID {model.Id}" ErrorMessage = $"TheMovieDb didn't have any information for ID {model.Id}"
}; };
}
var fullMovieName = var fullMovieName =
$"{movieInfo.Title}{(!string.IsNullOrEmpty(movieInfo.ReleaseDate) ? $" ({DateTime.Parse(movieInfo.ReleaseDate).Year})" : string.Empty)}"; $"{movieInfo.Title}{(!string.IsNullOrEmpty(movieInfo.ReleaseDate) ? $" ({DateTime.Parse(movieInfo.ReleaseDate).Year})" : string.Empty)}";
var existingRequest = await MovieRequestService.CheckRequestAsync(model.Id); var existingRequest = await MovieRequestService.CheckRequestAsync(model.Id);
if (existingRequest != null) if (existingRequest != null)
{
return new RequestEngineResult return new RequestEngineResult
{ {
RequestAdded = false, RequestAdded = false,
Message = $"{fullMovieName} has already been requested" Message = $"{fullMovieName} has already been requested"
}; };
}
// TODO // TODO
//try //try
//{ //{
// var content = PlexContentRepository.GetAll(); // var content = PlexContentRepository.GetAll();
// var movies = PlexChecker.GetPlexMovies(content); // var movies = PlexChecker.GetPlexMovies(content);
// if (PlexChecker.IsMovieAvailable(movies.ToArray(), movieInfo.Title, movieInfo.ReleaseDate?.Year.ToString())) // if (PlexChecker.IsMovieAvailable(movies.ToArray(), movieInfo.Title, movieInfo.ReleaseDate?.Year.ToString()))
@ -88,20 +84,27 @@ namespace Ombi.Core.Engine
ImdbId = movieInfo.ImdbId, ImdbId = movieInfo.ImdbId,
PosterPath = movieInfo.PosterPath, PosterPath = movieInfo.PosterPath,
Title = movieInfo.Title, Title = movieInfo.Title,
ReleaseDate = !string.IsNullOrEmpty(movieInfo.ReleaseDate) ? DateTime.Parse(movieInfo.ReleaseDate) : DateTime.MinValue, ReleaseDate = !string.IsNullOrEmpty(movieInfo.ReleaseDate)
? DateTime.Parse(movieInfo.ReleaseDate)
: DateTime.MinValue,
Status = movieInfo.Status, Status = movieInfo.Status,
RequestedDate = DateTime.UtcNow, RequestedDate = DateTime.UtcNow,
Approved = false, Approved = false,
RequestedUsers = new List<string> {Username}, RequestedUsers = new List<string> {Username},
Issues = IssueState.None, Issues = IssueState.None
}; };
try try
{ {
if (ShouldAutoApprove(RequestType.Movie)) var ruleResults = RunRules(requestModel).ToList();
if (ruleResults.Any(x => !x.Success))
return new RequestEngineResult
{ {
model.Approved = true; ErrorMessage = ruleResults.FirstOrDefault(x => !string.IsNullOrEmpty(x.Message)).Message
};
if (requestModel.Approved) // The rules have auto approved this
{
// var result = await MovieSender.Send(model); // var result = await MovieSender.Send(model);
// if (result.Result) // if (result.Result)
// { // {
@ -120,7 +123,6 @@ namespace Ombi.Core.Engine
// } // }
// if (!result.MovieSendingEnabled) // if (!result.MovieSendingEnabled)
// { // {
// return await AddRequest(model, settings, $"{fullMovieName} {Resources.UI.Search_SuccessfullyAdded}"); // return await AddRequest(model, settings, $"{fullMovieName} {Resources.UI.Search_SuccessfullyAdded}");
// } // }
@ -131,10 +133,8 @@ namespace Ombi.Core.Engine
// }); // });
} }
return await AddMovieRequest(requestModel, /*settings,*/ return await AddMovieRequest(requestModel, /*settings,*/
$"{fullMovieName} has been successfully added!"); $"{fullMovieName} has been successfully added!");
} }
catch (Exception e) catch (Exception e)
{ {
@ -160,8 +160,48 @@ namespace Ombi.Core.Engine
return null; return null;
} }
public async Task<IEnumerable<MovieRequestModel>> GetMovieRequests(int count, int position)
{
var allRequests = await MovieRequestService.GetAllAsync(count, position);
return allRequests;
}
private IEnumerable<EpisodesModel> GetListDifferences(IEnumerable<EpisodesModel> existing, IEnumerable<EpisodesModel> request) public async Task<IEnumerable<MovieRequestModel>> SearchMovieRequest(string search)
{
var allRequests = await MovieRequestService.GetAllAsync();
var results = allRequests.Where(x => x.Title.Contains(search, CompareOptions.IgnoreCase));
return results;
}
public async Task<MovieRequestModel> UpdateMovieRequest(MovieRequestModel request)
{
var allRequests = await MovieRequestService.GetAllAsync();
var results = allRequests.FirstOrDefault(x => x.Id == request.Id);
results.Approved = request.Approved;
results.Available = request.Available;
results.Denied = request.Denied;
results.DeniedReason = request.DeniedReason;
results.AdminNote = request.AdminNote;
results.ImdbId = request.ImdbId;
results.IssueId = request.IssueId;
results.Issues = request.Issues;
results.OtherMessage = request.OtherMessage;
results.Overview = request.Overview;
results.PosterPath = request.PosterPath;
results.RequestedUsers = request.RequestedUsers?.ToList() ?? new List<string>();
var model = MovieRequestService.UpdateRequest(results);
return model;
}
public async Task RemoveMovieRequest(int requestId)
{
await MovieRequestService.DeleteRequestAsync(requestId);
}
private IEnumerable<EpisodesModel> GetListDifferences(IEnumerable<EpisodesModel> existing,
IEnumerable<EpisodesModel> request)
{ {
var newRequest = request var newRequest = request
.Select(r => .Select(r =>
@ -169,12 +209,12 @@ namespace Ombi.Core.Engine
{ {
SeasonNumber = r.SeasonNumber, SeasonNumber = r.SeasonNumber,
EpisodeNumber = r.EpisodeNumber EpisodeNumber = r.EpisodeNumber
}).ToList(); })
.ToList();
return newRequest.Except(existing); return newRequest.Except(existing);
} }
private async Task<RequestEngineResult> AddMovieRequest(MovieRequestModel model, string message) private async Task<RequestEngineResult> AddMovieRequest(MovieRequestModel model, string message)
{ {
await MovieRequestService.AddRequestAsync(model); await MovieRequestService.AddRequestAsync(model);
@ -188,7 +228,9 @@ namespace Ombi.Core.Engine
DateTime = DateTime.Now, DateTime = DateTime.Now,
NotificationType = NotificationType.NewRequest, NotificationType = NotificationType.NewRequest,
RequestType = model.Type, RequestType = model.Type,
ImgSrc = model.Type == RequestType.Movie ? $"https://image.tmdb.org/t/p/w300/{model.PosterPath}" : model.PosterPath ImgSrc = model.Type == RequestType.Movie
? $"https://image.tmdb.org/t/p/w300/{model.PosterPath}"
: model.PosterPath
}; };
BackgroundJob.Enqueue(() => NotificationService.Publish(notificationModel).Wait()); BackgroundJob.Enqueue(() => NotificationService.Publish(notificationModel).Wait());
@ -214,44 +256,5 @@ namespace Ombi.Core.Engine
return new RequestEngineResult {RequestAdded = true}; return new RequestEngineResult {RequestAdded = true};
} }
public async Task<IEnumerable<MovieRequestModel>> GetMovieRequests(int count, int position)
{
var allRequests = await MovieRequestService.GetAllAsync(count, position);
return allRequests;
}
public async Task<IEnumerable<MovieRequestModel>> SearchMovieRequest(string search)
{
var allRequests = await MovieRequestService.GetAllAsync();
var results = allRequests.Where(x => x.Title.Contains(search, CompareOptions.IgnoreCase));
return results;
}
public async Task<MovieRequestModel> UpdateMovieRequest(MovieRequestModel request)
{
var allRequests = await MovieRequestService.GetAllAsync();
var results = allRequests.FirstOrDefault(x => x.Id == request.Id);
results.Approved = request.Approved;
results.Available = request.Available;
results.Denied = request.Denied;
results.DeniedReason = request.DeniedReason;
results.AdminNote = request.AdminNote;
results.ImdbId = request.ImdbId;
results.IssueId = request.IssueId;
results.Issues = request.Issues;
results.OtherMessage = request.OtherMessage;
results.Overview = request.Overview;
results.PosterPath = request.PosterPath;
results.RequestedUsers = request.RequestedUsers?.ToList() ?? new List<string>();
var model = MovieRequestService.UpdateRequest(results);
return model;
}
public async Task RemoveMovieRequest(int requestId)
{
await MovieRequestService.DeleteRequestAsync(requestId);
}
} }
} }

@ -1,30 +1,28 @@
using System.Collections.Generic; using AutoMapper;
using System.Linq;
using System.Security.Principal;
using System.Threading.Tasks;
using AutoMapper;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Ombi.Api.TheMovieDb; using Ombi.Api.TheMovieDb;
using Ombi.Api.TheMovieDb.Models; using Ombi.Api.TheMovieDb.Models;
using Ombi.Core.IdentityResolver;
using Ombi.Core.Models.Requests; using Ombi.Core.Models.Requests;
using Ombi.Core.Models.Requests.Movie; using Ombi.Core.Models.Requests.Movie;
using Ombi.Core.Models.Search; using Ombi.Core.Models.Search;
using Ombi.Core.Requests.Models; using Ombi.Core.Rules;
using Ombi.Core.Settings; using Ombi.Core.Settings;
using Ombi.Core.Settings.Models.External; using Ombi.Core.Settings.Models.External;
using Ombi.Store.Entities;
using Ombi.Store.Repository; using Ombi.Store.Repository;
using System.Collections.Generic;
using System.Linq;
using System.Security.Principal;
using System.Threading.Tasks;
namespace Ombi.Core.Engine namespace Ombi.Core.Engine
{ {
public class MovieSearchEngine : BaseMediaEngine, IMovieEngine public class MovieSearchEngine : BaseMediaEngine, IMovieEngine
{ {
public MovieSearchEngine(IPrincipal identity, IRequestServiceMain service, IMovieDbApi movApi, IMapper mapper,
public MovieSearchEngine(IPrincipal identity, IRequestServiceMain service, IMovieDbApi movApi, IMapper mapper, ISettingsService<PlexSettings> plexSettings, ISettingsService<PlexSettings> plexSettings,
ISettingsService<EmbySettings> embySettings, IPlexContentRepository repo, ISettingsService<EmbySettings> embySettings, IPlexContentRepository repo,
ILogger<MovieSearchEngine> logger) ILogger<MovieSearchEngine> logger, IRuleEvaluator r)
: base(identity, service) : base(identity, service, r)
{ {
MovieApi = movApi; MovieApi = movApi;
Mapper = mapper; Mapper = mapper;
@ -41,18 +39,16 @@ namespace Ombi.Core.Engine
private ILogger<MovieSearchEngine> Logger { get; } private ILogger<MovieSearchEngine> Logger { get; }
private IPlexContentRepository PlexContentRepo { get; } private IPlexContentRepository PlexContentRepo { get; }
public async Task<IEnumerable<SearchMovieViewModel>> LookupImdbInformation(IEnumerable<SearchMovieViewModel> movies) public async Task<IEnumerable<SearchMovieViewModel>> LookupImdbInformation(
IEnumerable<SearchMovieViewModel> movies)
{ {
var searchMovieViewModels var searchMovieViewModels
= movies as IList<SearchMovieViewModel> ?? movies.ToList(); = movies as IList<SearchMovieViewModel> ?? movies.ToList();
if (searchMovieViewModels == null || !searchMovieViewModels.Any()) if (searchMovieViewModels == null || !searchMovieViewModels.Any())
{
return new List<SearchMovieViewModel>(); return new List<SearchMovieViewModel>();
}
var retVal = new List<SearchMovieViewModel>(); var retVal = new List<SearchMovieViewModel>();
Dictionary<int, MovieRequestModel> dbMovies = await GetMovieRequests(); var dbMovies = await GetMovieRequests();
var plexSettings = await PlexSettings.GetSettingsAsync(); var plexSettings = await PlexSettings.GetSettingsAsync();
var embySettings = await EmbySettings.GetSettingsAsync(); var embySettings = await EmbySettings.GetSettingsAsync();
@ -77,6 +73,7 @@ namespace Ombi.Core.Engine
} }
return null; return null;
} }
public async Task<IEnumerable<SearchMovieViewModel>> PopularMovies() public async Task<IEnumerable<SearchMovieViewModel>> PopularMovies()
{ {
var result = await MovieApi.PopularMovies(); var result = await MovieApi.PopularMovies();
@ -109,32 +106,28 @@ namespace Ombi.Core.Engine
} }
return null; return null;
} }
public async Task<IEnumerable<SearchMovieViewModel>> NowPlayingMovies() public async Task<IEnumerable<SearchMovieViewModel>> NowPlayingMovies()
{ {
var result = await MovieApi.NowPlaying(); var result = await MovieApi.NowPlaying();
if (result != null) if (result != null)
{ {
Logger.LogDebug("Search Result: {result}", result); Logger.LogDebug("Search Result: {result}", result);
return await TransformMovieResultsToResponse(result); return await TransformMovieResultsToResponse(result);
} }
return null; return null;
} }
private async Task<List<SearchMovieViewModel>> TransformMovieResultsToResponse(
private async Task<List<SearchMovieViewModel>> TransformMovieResultsToResponse(IEnumerable<MovieSearchResult> movies) IEnumerable<MovieSearchResult> movies)
{ {
var viewMovies = new List<SearchMovieViewModel>(); var viewMovies = new List<SearchMovieViewModel>();
Dictionary<int, MovieRequestModel> dbMovies = await GetMovieRequests(); var dbMovies = await GetMovieRequests();
var plexSettings = await PlexSettings.GetSettingsAsync(); var plexSettings = await PlexSettings.GetSettingsAsync();
var embySettings = await EmbySettings.GetSettingsAsync(); var embySettings = await EmbySettings.GetSettingsAsync();
foreach (var movie in movies) foreach (var movie in movies)
{
viewMovies.Add(await ProcessSingleMovie(movie, dbMovies, plexSettings, embySettings)); viewMovies.Add(await ProcessSingleMovie(movie, dbMovies, plexSettings, embySettings));
}
return viewMovies; return viewMovies;
} }
@ -144,8 +137,7 @@ namespace Ombi.Core.Engine
var showInfo = await MovieApi.GetMovieInformation(viewMovie.Id); var showInfo = await MovieApi.GetMovieInformation(viewMovie.Id);
if (plexSettings.Enable) if (plexSettings.Enable)
{ {
var item = await PlexContentRepo.Get(showInfo.ImdbId);
var item = await PlexContentRepo.Get(showInfo.ImdbId.ToString());
if (item != null) if (item != null)
{ {
viewMovie.Available = true; viewMovie.Available = true;
@ -186,11 +178,11 @@ namespace Ombi.Core.Engine
viewMovie.Available = requestedMovie.Available; viewMovie.Available = requestedMovie.Available;
} }
return viewMovie; return viewMovie;
} }
private async Task<SearchMovieViewModel> ProcessSingleMovie(MovieSearchResult movie, Dictionary<int, MovieRequestModel> existingRequests, PlexSettings plexSettings, EmbySettings embySettings) private async Task<SearchMovieViewModel> ProcessSingleMovie(MovieSearchResult movie,
Dictionary<int, MovieRequestModel> existingRequests, PlexSettings plexSettings, EmbySettings embySettings)
{ {
var viewMovie = Mapper.Map<SearchMovieViewModel>(movie); var viewMovie = Mapper.Map<SearchMovieViewModel>(movie);
return await ProcessSingleMovie(viewMovie, existingRequests, plexSettings, embySettings); return await ProcessSingleMovie(viewMovie, existingRequests, plexSettings, embySettings);

@ -1,36 +1,36 @@
using System; using AutoMapper;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Security.Principal;
using System.Threading.Tasks;
using AutoMapper;
using Hangfire; using Hangfire;
using Ombi.Api.TvMaze; using Ombi.Api.TvMaze;
using Ombi.Core.Models.Requests; using Ombi.Core.Models.Requests;
using Ombi.Core.Models.Search; using Ombi.Core.Models.Search;
using Ombi.Store.Entities; using Ombi.Core.Rules;
using Ombi.Helpers; using Ombi.Helpers;
using Ombi.Notifications; using Ombi.Notifications;
using Ombi.Notifications.Models; using Ombi.Notifications.Models;
using Ombi.Core.Rules; using Ombi.Store.Entities;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Security.Principal;
using System.Threading.Tasks;
namespace Ombi.Core.Engine namespace Ombi.Core.Engine
{ {
public class TvRequestEngine : BaseMediaEngine, ITvRequestEngine public class TvRequestEngine : BaseMediaEngine, ITvRequestEngine
{ {
public TvRequestEngine(ITvMazeApi tvApi, IRequestServiceMain requestService, IPrincipal user, INotificationService notificationService, IMapper map, public TvRequestEngine(ITvMazeApi tvApi, IRequestServiceMain requestService, IPrincipal user,
IRuleEvaluator rule) : base(user, requestService) INotificationService notificationService, IMapper map,
IRuleEvaluator rule) : base(user, requestService, rule)
{ {
TvApi = tvApi; TvApi = tvApi;
NotificationService = notificationService; NotificationService = notificationService;
Mapper = map; Mapper = map;
Rules = rule;
} }
private INotificationService NotificationService { get; } private INotificationService NotificationService { get; }
private ITvMazeApi TvApi { get; } private ITvMazeApi TvApi { get; }
private IMapper Mapper { get; } private IMapper Mapper { get; }
private IRuleEvaluator Rules { get; }
public async Task<RequestEngineResult> RequestTvShow(SearchTvShowViewModel tv) public async Task<RequestEngineResult> RequestTvShow(SearchTvShowViewModel tv)
{ {
@ -55,7 +55,7 @@ namespace Ombi.Core.Engine
Issues = IssueState.None, Issues = IssueState.None,
ProviderId = tv.Id, ProviderId = tv.Id,
RequestAll = tv.RequestAll, RequestAll = tv.RequestAll,
SeasonRequests = tv.SeasonRequests, SeasonRequests = tv.SeasonRequests
}; };
var model = new TvRequestModel var model = new TvRequestModel
@ -70,8 +70,7 @@ namespace Ombi.Core.Engine
Approved = false, Approved = false,
ImdbId = showInfo.externals?.imdb ?? string.Empty, ImdbId = showInfo.externals?.imdb ?? string.Empty,
TvDbId = tv.Id.ToString(), TvDbId = tv.Id.ToString(),
ProviderId = tv.Id, ProviderId = tv.Id
}; };
model.ChildRequests.Add(childRequest); model.ChildRequests.Add(childRequest);
@ -88,7 +87,7 @@ namespace Ombi.Core.Engine
Url = e.url, Url = e.url,
Title = e.name, Title = e.name,
AirDate = DateTime.Parse(e.airstamp), AirDate = DateTime.Parse(e.airstamp),
EpisodeNumber = e.number, EpisodeNumber = e.number
}); });
} }
} }
@ -97,46 +96,29 @@ namespace Ombi.Core.Engine
{ {
var latest = showInfo.Season.OrderBy(x => x.SeasonNumber).FirstOrDefault(); var latest = showInfo.Season.OrderBy(x => x.SeasonNumber).FirstOrDefault();
foreach (var modelSeasonRequest in childRequest.SeasonRequests) foreach (var modelSeasonRequest in childRequest.SeasonRequests)
{
if (modelSeasonRequest.SeasonNumber == latest.SeasonNumber) if (modelSeasonRequest.SeasonNumber == latest.SeasonNumber)
{
foreach (var episodesRequested in modelSeasonRequest.Episodes) foreach (var episodesRequested in modelSeasonRequest.Episodes)
{
episodesRequested.Requested = true; episodesRequested.Requested = true;
} }
}
}
}
if (tv.FirstSeason) if (tv.FirstSeason)
{ {
var first = showInfo.Season.OrderByDescending(x => x.SeasonNumber).FirstOrDefault(); var first = showInfo.Season.OrderByDescending(x => x.SeasonNumber).FirstOrDefault();
foreach (var modelSeasonRequest in childRequest.SeasonRequests) foreach (var modelSeasonRequest in childRequest.SeasonRequests)
{
if (modelSeasonRequest.SeasonNumber == first.SeasonNumber) if (modelSeasonRequest.SeasonNumber == first.SeasonNumber)
{
foreach (var episodesRequested in modelSeasonRequest.Episodes) foreach (var episodesRequested in modelSeasonRequest.Episodes)
{
episodesRequested.Requested = true; episodesRequested.Requested = true;
} }
}
}
}
var ruleResults = Rules.StartRequestRules(model); var ruleResults = RunRules(model).ToList();
if (ruleResults.Any(x => !x.Success)) if (ruleResults.Any(x => !x.Success))
return new RequestEngineResult
{ {
return new RequestEngineResult() ErrorMessage = ruleResults.FirstOrDefault(x => !string.IsNullOrEmpty(x.Message)).Message
{
ErrorMessage = ruleResults.FirstOrDefault(x => !string.IsNullOrEmpty(x.Message)).Message,
}; };
}
var existingRequest = await TvRequestService.CheckRequestAsync(model.Id); var existingRequest = await TvRequestService.CheckRequestAsync(model.Id);
if (existingRequest != null) if (existingRequest != null)
{
return await AddExistingRequest(model, existingRequest); return await AddExistingRequest(model, existingRequest);
}
// This is a new request // This is a new request
return await AddRequest(model); return await AddRequest(model);
@ -147,12 +129,14 @@ namespace Ombi.Core.Engine
var allRequests = await TvRequestService.GetAllAsync(count, position); var allRequests = await TvRequestService.GetAllAsync(count, position);
return allRequests; return allRequests;
} }
public async Task<IEnumerable<TvRequestModel>> SearchTvRequest(string search) public async Task<IEnumerable<TvRequestModel>> SearchTvRequest(string search)
{ {
var allRequests = await TvRequestService.GetAllAsync(); var allRequests = await TvRequestService.GetAllAsync();
var results = allRequests.Where(x => x.Title.Contains(search, CompareOptions.IgnoreCase)); var results = allRequests.Where(x => x.Title.Contains(search, CompareOptions.IgnoreCase));
return results; return results;
} }
public async Task<TvRequestModel> UpdateTvRequest(TvRequestModel request) public async Task<TvRequestModel> UpdateTvRequest(TvRequestModel request)
{ {
var allRequests = await TvRequestService.GetAllAsync(); var allRequests = await TvRequestService.GetAllAsync();
@ -168,25 +152,20 @@ namespace Ombi.Core.Engine
await TvRequestService.DeleteRequestAsync(requestId); await TvRequestService.DeleteRequestAsync(requestId);
} }
private async Task<RequestEngineResult> AddExistingRequest(TvRequestModel newRequest, TvRequestModel existingRequest) private async Task<RequestEngineResult> AddExistingRequest(TvRequestModel newRequest,
TvRequestModel existingRequest)
{ {
var child = newRequest.ChildRequests.FirstOrDefault(); // There will only be 1 var child = newRequest.ChildRequests.FirstOrDefault(); // There will only be 1
var episodeDiff = new List<SeasonRequestModel>(); var episodeDiff = new List<SeasonRequestModel>();
foreach (var existingChild in existingRequest.ChildRequests) foreach (var existingChild in existingRequest.ChildRequests)
{ {
var difference = GetListDifferences(existingChild.SeasonRequests, child.SeasonRequests).ToList(); var difference = GetListDifferences(existingChild.SeasonRequests, child.SeasonRequests).ToList();
if (difference.Any()) if (difference.Any())
{
episodeDiff = difference; episodeDiff = difference;
} }
}
if (episodeDiff.Any()) if (episodeDiff.Any())
{
// This is where there are some episodes that have been requested, but this list contains the 'new' requests
child.SeasonRequests = episodeDiff; child.SeasonRequests = episodeDiff;
}
existingRequest.ChildRequests.AddRange(newRequest.ChildRequests); existingRequest.ChildRequests.AddRange(newRequest.ChildRequests);
TvRequestService.UpdateRequest(existingRequest); TvRequestService.UpdateRequest(existingRequest);
@ -198,7 +177,8 @@ namespace Ombi.Core.Engine
return await AfterRequest(newRequest); return await AfterRequest(newRequest);
} }
private IEnumerable<SeasonRequestModel> GetListDifferences(IEnumerable<SeasonRequestModel> existing, IEnumerable<SeasonRequestModel> request) private IEnumerable<SeasonRequestModel> GetListDifferences(IEnumerable<SeasonRequestModel> existing,
IEnumerable<SeasonRequestModel> request)
{ {
var newRequest = request var newRequest = request
.Select(r => .Select(r =>
@ -206,7 +186,8 @@ namespace Ombi.Core.Engine
{ {
SeasonNumber = r.SeasonNumber, SeasonNumber = r.SeasonNumber,
Episodes = r.Episodes Episodes = r.Episodes
}).ToList(); })
.ToList();
return newRequest.Except(existing); return newRequest.Except(existing);
} }
@ -255,7 +236,5 @@ namespace Ombi.Core.Engine
return new RequestEngineResult {RequestAdded = true}; return new RequestEngineResult {RequestAdded = true};
} }
} }
} }

@ -1,29 +1,28 @@
using System; using AutoMapper;
using System.Collections.Generic;
using System.Linq;
using System.Security.Principal;
using System.Threading.Tasks;
using AutoMapper;
using Ombi.Api.Trakt; using Ombi.Api.Trakt;
using Ombi.Api.TvMaze; using Ombi.Api.TvMaze;
using Ombi.Api.TvMaze.Models;
using Ombi.Core.Engine.Interfaces; using Ombi.Core.Engine.Interfaces;
using Ombi.Core.Models.Requests; using Ombi.Core.Models.Requests;
using Ombi.Core.Models.Search; using Ombi.Core.Models.Search;
using Ombi.Core.Requests.Models; using Ombi.Core.Rules;
using Ombi.Core.Settings; using Ombi.Core.Settings;
using Ombi.Core.Settings.Models.External; using Ombi.Core.Settings.Models.External;
using Ombi.Store.Entities;
using Ombi.Store.Repository; using Ombi.Store.Repository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Principal;
using System.Threading.Tasks;
namespace Ombi.Core.Engine namespace Ombi.Core.Engine
{ {
public class TvSearchEngine : BaseMediaEngine, ITvSearchEngine public class TvSearchEngine : BaseMediaEngine, ITvSearchEngine
{ {
public TvSearchEngine(IPrincipal identity, IRequestServiceMain service, ITvMazeApi tvMaze, IMapper mapper, ISettingsService<PlexSettings> plexSettings, public TvSearchEngine(IPrincipal identity, IRequestServiceMain service, ITvMazeApi tvMaze, IMapper mapper, ISettingsService<PlexSettings> plexSettings,
ISettingsService<EmbySettings> embySettings, IPlexContentRepository repo, ITraktApi trakt) ISettingsService<EmbySettings> embySettings, IPlexContentRepository repo, ITraktApi trakt, IRuleEvaluator r)
: base(identity, service) : base(identity, service, r)
{ {
TvMazeApi = tvMaze; TvMazeApi = tvMaze;
Mapper = mapper; Mapper = mapper;
@ -40,7 +39,6 @@ namespace Ombi.Core.Engine
private IPlexContentRepository PlexContentRepo { get; } private IPlexContentRepository PlexContentRepo { get; }
private ITraktApi TraktApi { get; } private ITraktApi TraktApi { get; }
public async Task<IEnumerable<SearchTvShowViewModel>> Search(string searchTerm) public async Task<IEnumerable<SearchTvShowViewModel>> Search(string searchTerm)
{ {
var searchResult = await TvMazeApi.Search(searchTerm); var searchResult = await TvMazeApi.Search(searchTerm);
@ -76,7 +74,6 @@ namespace Ombi.Core.Engine
EpisodeNumber = e.number, EpisodeNumber = e.number,
}); });
mapped.SeasonRequests.Add(newSeason); mapped.SeasonRequests.Add(newSeason);
} }
else else
{ {
@ -86,7 +83,6 @@ namespace Ombi.Core.Engine
Title = e.name, Title = e.name,
AirDate = DateTime.Parse(e.airstamp), AirDate = DateTime.Parse(e.airstamp),
EpisodeNumber = e.number, EpisodeNumber = e.number,
}); });
} }
} }
@ -108,11 +104,13 @@ namespace Ombi.Core.Engine
var result = await TraktApi.GetAnticipatedShows(); var result = await TraktApi.GetAnticipatedShows();
return await ProcessResults(result); return await ProcessResults(result);
} }
public async Task<IEnumerable<SearchTvShowViewModel>> MostWatches() public async Task<IEnumerable<SearchTvShowViewModel>> MostWatches()
{ {
var result = await TraktApi.GetMostWatchesShows(); var result = await TraktApi.GetMostWatchesShows();
return await ProcessResults(result); return await ProcessResults(result);
} }
public async Task<IEnumerable<SearchTvShowViewModel>> Trending() public async Task<IEnumerable<SearchTvShowViewModel>> Trending()
{ {
var result = await TraktApi.GetTrendingShows(); var result = await TraktApi.GetTrendingShows();
@ -158,7 +156,6 @@ namespace Ombi.Core.Engine
if (item.Id > 0 && item.Available) if (item.Id > 0 && item.Available)
{ {
// TODO need to check if the episodes are available // TODO need to check if the episodes are available
var tvdbid = item.Id; var tvdbid = item.Id;
if (existingRequests.ContainsKey(tvdbid)) if (existingRequests.ContainsKey(tvdbid))
@ -173,7 +170,6 @@ namespace Ombi.Core.Engine
{ {
foreach (var existingRequestChildRequest in existingRequest.ChildRequests) foreach (var existingRequestChildRequest in existingRequest.ChildRequests)
{ {
// Find the existing request season // Find the existing request season
var existingSeason = var existingSeason =
existingRequestChildRequest.SeasonRequests.FirstOrDefault(x => x.SeasonNumber == season.SeasonNumber); existingRequestChildRequest.SeasonRequests.FirstOrDefault(x => x.SeasonNumber == season.SeasonNumber);
@ -187,7 +183,6 @@ namespace Ombi.Core.Engine
episodeSearching.Approved = ep.Approved; episodeSearching.Approved = ep.Approved;
} }
} }
} }
} }
//if (sonarrCached.Select(x => x.TvdbId).Contains(tvdbid) || sickRageCache.Contains(tvdbid)) //if (sonarrCached.Select(x => x.TvdbId).Contains(tvdbid) || sickRageCache.Contains(tvdbid))

@ -1,16 +1,21 @@
using System.Collections.Generic; using Ombi.Core.Models;
using System.Collections.Generic;
using System.Threading.Tasks; using System.Threading.Tasks;
using Ombi.Core.Models;
namespace Ombi.Core.IdentityResolver namespace Ombi.Core.IdentityResolver
{ {
public interface IUserIdentityManager public interface IUserIdentityManager
{ {
Task<UserDto> CreateUser(UserDto user); Task<UserDto> CreateUser(UserDto user);
Task<bool> CredentialsValid(string username, string password); Task<bool> CredentialsValid(string username, string password);
Task<UserDto> GetUser(string username); Task<UserDto> GetUser(string username);
Task<IEnumerable<UserDto>> GetUsers(); Task<IEnumerable<UserDto>> GetUsers();
Task DeleteUser(UserDto user); Task DeleteUser(UserDto user);
Task<UserDto> UpdateUser(UserDto userDto); Task<UserDto> UpdateUser(UserDto userDto);
} }
} }

@ -1,40 +1,13 @@
#region Copyright using AutoMapper;
// /************************************************************************ using Microsoft.AspNetCore.Cryptography.KeyDerivation;
// Copyright (c) 2017 Jamie Rees using Ombi.Core.Models;
// File: UserIdentityManager.cs using Ombi.Store.Entities;
// Created By: Jamie Rees using Ombi.Store.Repository;
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ************************************************************************/
#endregion
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Security.Claims; using System.Security.Claims;
using System.Security.Cryptography; using System.Security.Cryptography;
using System.Threading.Tasks; using System.Threading.Tasks;
using AutoMapper;
using Microsoft.AspNetCore.Cryptography.KeyDerivation;
using Ombi.Core.Models;
using Ombi.Store.Entities;
using Ombi.Store.Repository;
namespace Ombi.Core.IdentityResolver namespace Ombi.Core.IdentityResolver
{ {
@ -96,7 +69,7 @@ namespace Ombi.Core.IdentityResolver
private UserHash HashPassword(string password) private UserHash HashPassword(string password)
{ {
// generate a 128-bit salt using a secure PRNG // generate a 128-bit salt using a secure PRNG
byte[] salt = new byte[128 / 8]; var salt = new byte[128 / 8];
using (var rng = RandomNumberGenerator.Create()) using (var rng = RandomNumberGenerator.Create())
{ {
rng.GetBytes(salt); rng.GetBytes(salt);
@ -104,16 +77,15 @@ namespace Ombi.Core.IdentityResolver
return HashPassword(password, salt); return HashPassword(password, salt);
} }
private UserHash HashPassword(string password, byte[] salt) private UserHash HashPassword(string password, byte[] salt)
{ {
// derive a 256-bit subkey (use HMACSHA1 with 10,000 iterations) // derive a 256-bit subkey (use HMACSHA1 with 10,000 iterations)
var hashed = Convert.ToBase64String(KeyDerivation.Pbkdf2( var hashed = Convert.ToBase64String(KeyDerivation.Pbkdf2(
password: password, password,
salt: salt, salt,
prf: KeyDerivationPrf.HMACSHA1, KeyDerivationPrf.HMACSHA1,
iterationCount: 10000, 10000,
numBytesRequested: 256 / 8)); 256 / 8));
return new UserHash {HashedPass = hashed, Salt = salt}; return new UserHash {HashedPass = hashed, Salt = salt};
} }

@ -1,8 +1,8 @@
using System; using Newtonsoft.Json;
using Ombi.Store.Entities;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using Newtonsoft.Json;
using Ombi.Store.Entities;
namespace Ombi.Core.Models.Requests namespace Ombi.Core.Models.Requests
{ {
@ -37,9 +37,7 @@ namespace Ombi.Core.Models.Requests
{ {
var u = new List<string>(); var u = new List<string>();
if (RequestedUsers != null && RequestedUsers.Any()) if (RequestedUsers != null && RequestedUsers.Any())
{
u.AddRange(RequestedUsers); u.AddRange(RequestedUsers);
}
return u; return u;
} }
} }

@ -1,28 +1,42 @@
using System.Collections.Generic; using Ombi.Core.Models.Requests;
using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Threading.Tasks; using System.Threading.Tasks;
using Ombi.Core.Models.Requests;
using Ombi.Store.Entities;
namespace Ombi.Core.Requests.Models namespace Ombi.Core.Requests.Models
{ {
public interface IRequestService<T> where T : BaseRequestModel public interface IRequestService<T> where T : BaseRequestModel
{ {
int AddRequest(T model); int AddRequest(T model);
Task<int> AddRequestAsync(T model); Task<int> AddRequestAsync(T model);
void BatchDelete(IEnumerable<T> model); void BatchDelete(IEnumerable<T> model);
void BatchUpdate(IEnumerable<T> model); void BatchUpdate(IEnumerable<T> model);
T CheckRequest(int providerId); T CheckRequest(int providerId);
Task<T> CheckRequestAsync(int providerId); Task<T> CheckRequestAsync(int providerId);
void DeleteRequest(T request); void DeleteRequest(T request);
Task DeleteRequestAsync(int request); Task DeleteRequestAsync(int request);
Task DeleteRequestAsync(T request); Task DeleteRequestAsync(T request);
T Get(int id); T Get(int id);
IEnumerable<T> GetAll(); IEnumerable<T> GetAll();
Task<IEnumerable<T>> GetAllAsync(); Task<IEnumerable<T>> GetAllAsync();
Task<IEnumerable<T>> GetAllAsync(int count, int position); Task<IEnumerable<T>> GetAllAsync(int count, int position);
Task<T> GetAsync(int id); Task<T> GetAsync(int id);
T UpdateRequest(T model); T UpdateRequest(T model);
IQueryable<T> GetAllQueryable(); IQueryable<T> GetAllQueryable();
} }
} }

@ -1,11 +1,10 @@
using System.Collections.Generic; using Ombi.Core.Requests.Models;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using Ombi.Core.Requests.Models;
using Ombi.Helpers; using Ombi.Helpers;
using Ombi.Store.Entities; using Ombi.Store.Entities;
using Ombi.Store.Repository; using Ombi.Store.Repository;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Ombi.Core.Models.Requests namespace Ombi.Core.Models.Requests
{ {
@ -16,11 +15,18 @@ namespace Ombi.Core.Models.Requests
Repo = repo; Repo = repo;
RequestType = typeof(T) == typeof(TvRequestModel) ? RequestType.TvShow : RequestType.Movie; RequestType = typeof(T) == typeof(TvRequestModel) ? RequestType.TvShow : RequestType.Movie;
} }
private RequestType RequestType { get; } private RequestType RequestType { get; }
private IRequestRepository Repo { get; } private IRequestRepository Repo { get; }
public int AddRequest(T model) public int AddRequest(T model)
{ {
var entity = new RequestBlobs { Type = model.Type, Content = ByteConverterHelper.ReturnBytes(model), ProviderId = model.ProviderId }; var entity = new RequestBlobs
{
Type = model.Type,
Content = ByteConverterHelper.ReturnBytes(model),
ProviderId = model.ProviderId
};
var id = Repo.Insert(entity); var id = Repo.Insert(entity);
return id.Id; return id.Id;
@ -28,7 +34,12 @@ namespace Ombi.Core.Models.Requests
public async Task<int> AddRequestAsync(T model) public async Task<int> AddRequestAsync(T model)
{ {
var entity = new RequestBlobs { Type = model.Type, Content = ByteConverterHelper.ReturnBytes(model), ProviderId = model.ProviderId }; var entity = new RequestBlobs
{
Type = model.Type,
Content = ByteConverterHelper.ReturnBytes(model),
ProviderId = model.ProviderId
};
var id = await Repo.InsertAsync(entity).ConfigureAwait(false); var id = await Repo.InsertAsync(entity).ConfigureAwait(false);
return id.Id; return id.Id;
@ -40,9 +51,7 @@ namespace Ombi.Core.Models.Requests
var blob = blobs.FirstOrDefault(x => x.ProviderId == providerId && x.Type == RequestType); var blob = blobs.FirstOrDefault(x => x.ProviderId == providerId && x.Type == RequestType);
if (blob == null) if (blob == null)
{
return null; return null;
}
var model = ByteConverterHelper.ReturnObject<T>(blob.Content); var model = ByteConverterHelper.ReturnObject<T>(blob.Content);
model.Id = blob.Id; model.Id = blob.Id;
return model; return model;
@ -51,10 +60,9 @@ namespace Ombi.Core.Models.Requests
public async Task<T> CheckRequestAsync(int providerId) public async Task<T> CheckRequestAsync(int providerId)
{ {
var blobs = await Repo.GetAllAsync().ConfigureAwait(false); var blobs = await Repo.GetAllAsync().ConfigureAwait(false);
var blob = blobs.FirstOrDefault(x => x.ProviderId == providerId && x.Type == RequestType); if (blob == null) var blob = blobs.FirstOrDefault(x => x.ProviderId == providerId && x.Type == RequestType);
{ if (blob == null)
return null; return null;
}
var model = ByteConverterHelper.ReturnObject<T>(blob.Content); var model = ByteConverterHelper.ReturnObject<T>(blob.Content);
model.Id = blob.Id; model.Id = blob.Id;
return model; return model;
@ -71,6 +79,7 @@ namespace Ombi.Core.Models.Requests
var blob = await Repo.GetAsync(request.Id).ConfigureAwait(false); var blob = await Repo.GetAsync(request.Id).ConfigureAwait(false);
Repo.Delete(blob); Repo.Delete(blob);
} }
public async Task DeleteRequestAsync(int request) public async Task DeleteRequestAsync(int request)
{ {
var blob = await Repo.GetAsync(request).ConfigureAwait(false); var blob = await Repo.GetAsync(request).ConfigureAwait(false);
@ -83,18 +92,17 @@ namespace Ombi.Core.Models.Requests
b.Content = ByteConverterHelper.ReturnBytes(model); b.Content = ByteConverterHelper.ReturnBytes(model);
var blob = Repo.Update(b); var blob = Repo.Update(b);
return model; return model;
} }
public T Get(int id) public T Get(int id)
{ {
var blob = Repo.Get(id); var blob = Repo.Get(id);
if (blob == null) if (blob == null)
{
return default(T); return default(T);
}
var model = ByteConverterHelper.ReturnObject<T>(blob.Content); var model = ByteConverterHelper.ReturnObject<T>(blob.Content);
model.Id = blob.Id; // They should always be the same, but for somereason a user didn't have it in the db https://github.com/tidusjar/Ombi/issues/862#issuecomment-269743847 model.Id =
blob
.Id; // They should always be the same, but for somereason a user didn't have it in the db https://github.com/tidusjar/Ombi/issues/862#issuecomment-269743847
return model; return model;
} }
@ -102,9 +110,7 @@ namespace Ombi.Core.Models.Requests
{ {
var blob = await Repo.GetAsync(id).ConfigureAwait(false); var blob = await Repo.GetAsync(id).ConfigureAwait(false);
if (blob == null) if (blob == null)
{
return default(T); return default(T);
}
var model = ByteConverterHelper.ReturnObject<T>(blob.Content); var model = ByteConverterHelper.ReturnObject<T>(blob.Content);
model.Id = blob.Id; model.Id = blob.Id;
return model; return model;
@ -118,9 +124,7 @@ namespace Ombi.Core.Models.Requests
foreach (var b in blobs) foreach (var b in blobs)
{ {
if (b == null) if (b == null)
{
continue; continue;
}
var model = ByteConverterHelper.ReturnObject<T>(b.Content); var model = ByteConverterHelper.ReturnObject<T>(b.Content);
model.Id = b.Id; model.Id = b.Id;
retVal.Add(model); retVal.Add(model);
@ -135,9 +139,7 @@ namespace Ombi.Core.Models.Requests
foreach (var b in blobs) foreach (var b in blobs)
{ {
if (b == null) if (b == null)
{
continue; continue;
}
var model = ByteConverterHelper.ReturnObject<T>(b.Content); var model = ByteConverterHelper.ReturnObject<T>(b.Content);
model.Id = b.Id; model.Id = b.Id;
retVal.Add(model); retVal.Add(model);
@ -153,9 +155,7 @@ namespace Ombi.Core.Models.Requests
foreach (var b in blobs.Where(x => x.Type == RequestType)) foreach (var b in blobs.Where(x => x.Type == RequestType))
{ {
if (b == null) if (b == null)
{
continue; continue;
}
var model = ByteConverterHelper.ReturnObject<T>(b.Content); var model = ByteConverterHelper.ReturnObject<T>(b.Content);
model.Id = b.Id; model.Id = b.Id;
retVal.Add(model); retVal.Add(model);
@ -171,9 +171,7 @@ namespace Ombi.Core.Models.Requests
foreach (var b in blobs.Where(x => x.Type == RequestType)) foreach (var b in blobs.Where(x => x.Type == RequestType))
{ {
if (b == null) if (b == null)
{
continue; continue;
}
var model = ByteConverterHelper.ReturnObject<T>(b.Content); var model = ByteConverterHelper.ReturnObject<T>(b.Content);
model.Id = b.Id; model.Id = b.Id;
retVal.Add(model); retVal.Add(model);
@ -183,13 +181,29 @@ namespace Ombi.Core.Models.Requests
public void BatchUpdate(IEnumerable<T> model) public void BatchUpdate(IEnumerable<T> model)
{ {
var entities = model.Select(m => new RequestBlobs { Type = m.Type, Content = ByteConverterHelper.ReturnBytes(m), ProviderId = m.ProviderId, Id = m.Id }).ToList(); var entities = model
.Select(m => new RequestBlobs
{
Type = m.Type,
Content = ByteConverterHelper.ReturnBytes(m),
ProviderId = m.ProviderId,
Id = m.Id
})
.ToList();
Repo.UpdateAll(entities); Repo.UpdateAll(entities);
} }
public void BatchDelete(IEnumerable<T> model) public void BatchDelete(IEnumerable<T> model)
{ {
var entities = model.Select(m => new RequestBlobs { Type = m.Type, Content = ByteConverterHelper.ReturnBytes(m), ProviderId = m.ProviderId, Id = m.Id }).ToList(); var entities = model
.Select(m => new RequestBlobs
{
Type = m.Type,
Content = ByteConverterHelper.ReturnBytes(m),
ProviderId = m.ProviderId,
Id = m.Id
})
.ToList();
Repo.DeleteAll(entities); Repo.DeleteAll(entities);
} }
} }

@ -2,8 +2,6 @@
{ {
public class MovieRequestModel : BaseRequestModel public class MovieRequestModel : BaseRequestModel
{ {
public string ImdbId { get; set; } public string ImdbId { get; set; }
} }
} }

@ -1,6 +1,6 @@
using System; using Ombi.Store.Entities;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using Ombi.Store.Entities;
namespace Ombi.Core.Models.Requests namespace Ombi.Core.Models.Requests
{ {
@ -12,8 +12,10 @@ namespace Ombi.Core.Models.Requests
{ {
case RequestType.Movie: case RequestType.Movie:
return "Movie"; return "Movie";
case RequestType.TvShow: case RequestType.TvShow:
return "TV Show"; return "TV Show";
default: default:
return string.Empty; return string.Empty;
} }
@ -27,13 +29,14 @@ namespace Ombi.Core.Models.Requests
NoSubtitles = 1, NoSubtitles = 1,
WrongContent = 2, WrongContent = 2,
PlaybackIssues = 3, PlaybackIssues = 3,
Other = 4, // Provide a message Other = 4 // Provide a message
} }
public class EpisodesModel : IEquatable<EpisodesModel> public class EpisodesModel : IEquatable<EpisodesModel>
{ {
public int SeasonNumber { get; set; } public int SeasonNumber { get; set; }
public int EpisodeNumber { get; set; } public int EpisodeNumber { get; set; }
public bool Equals(EpisodesModel other) public bool Equals(EpisodesModel other)
{ {
// Check whether the compared object is null. // Check whether the compared object is null.
@ -73,5 +76,4 @@ namespace Ombi.Core.Models.Requests
public bool Available { get; set; } public bool Available { get; set; }
public bool Approved { get; set; } public bool Approved { get; set; }
} }
} }

@ -1,5 +1,5 @@
using System; using Ombi.Store.Entities;
using Ombi.Store.Entities; using System;
namespace Ombi.Core.Models.Requests namespace Ombi.Core.Models.Requests
{ {

@ -1,6 +1,4 @@
using System; using System.Collections.Generic;
using System.Collections.Generic;
using Ombi.Store.Entities;
namespace Ombi.Core.Models.Requests namespace Ombi.Core.Models.Requests
{ {
@ -10,6 +8,7 @@ namespace Ombi.Core.Models.Requests
{ {
ChildRequests = new List<ChildTvRequest>(); ChildRequests = new List<ChildTvRequest>();
} }
public string ImdbId { get; set; } public string ImdbId { get; set; }
public string TvDbId { get; set; } public string TvDbId { get; set; }
@ -28,6 +27,5 @@ namespace Ombi.Core.Models.Requests
{ {
public bool RequestAll { get; set; } public bool RequestAll { get; set; }
public List<SeasonRequestModel> SeasonRequests { get; set; } = new List<SeasonRequestModel>(); public List<SeasonRequestModel> SeasonRequests { get; set; } = new List<SeasonRequestModel>();
} }
} }

@ -1,31 +1,4 @@
#region Copyright using System;
// /************************************************************************
// Copyright (c) 2017 Jamie Rees
// File: SearchMovieViewModel.cs
// Created By: Jamie Rees
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ************************************************************************/
#endregion
using System;
using System.Collections.Generic; using System.Collections.Generic;
namespace Ombi.Core.Models.Search namespace Ombi.Core.Models.Search

@ -1,5 +1,5 @@
using System.Collections.Generic; using Ombi.Core.Models.Requests;
using Ombi.Core.Models.Requests; using System.Collections.Generic;
namespace Ombi.Core.Models.Search namespace Ombi.Core.Models.Search
{ {
@ -31,6 +31,7 @@ namespace Ombi.Core.Models.Search
/// The trailer. /// The trailer.
/// </value> /// </value>
public string Trailer { get; set; } public string Trailer { get; set; }
/// <summary> /// <summary>
/// This is used from the Trakt API /// This is used from the Trakt API
/// </summary> /// </summary>
@ -48,6 +49,5 @@ namespace Ombi.Core.Models.Search
public bool FirstSeason { get; set; } public bool FirstSeason { get; set; }
public bool LatestSeason { get; set; } public bool LatestSeason { get; set; }
} }
} }

@ -1,30 +1,4 @@
#region Copyright namespace Ombi.Core.Models.Search
// /************************************************************************
// Copyright (c) 2017 Jamie Rees
// File: SearchViewModel.cs
// Created By: Jamie Rees
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ************************************************************************/
#endregion
namespace Ombi.Core.Models.Search
{ {
public class SearchViewModel public class SearchViewModel
{ {

@ -1,6 +1,5 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.Security.Claims; using System.Security.Claims;
using System.Security.Principal;
namespace Ombi.Core.Models namespace Ombi.Core.Models
{ {
@ -14,16 +13,12 @@ namespace Ombi.Core.Models
public string Password { get; set; } public string Password { get; set; }
public byte[] Salt { get; set; } public byte[] Salt { get; set; }
public UserType UserType { get; set; } public UserType UserType { get; set; }
} }
public enum UserType public enum UserType
{ {
LocalUser = 1, LocalUser = 1,
PlexUser = 2, PlexUser = 2,
EmbyUser = 3, EmbyUser = 3
} }
} }

@ -1,14 +1,12 @@
using System.Threading.Tasks; using Ombi.Core.Models.Requests.Movie;
using Ombi.Core.Models.Requests;
using Ombi.Core.Models.Requests.Movie;
using Ombi.Core.Settings; using Ombi.Core.Settings;
using Ombi.Settings.Settings.Models.External; using Ombi.Settings.Settings.Models.External;
using System.Threading.Tasks;
namespace Ombi.Core namespace Ombi.Core
{ {
public class MovieSender public class MovieSender
{ {
public MovieSender(ISettingsService<RadarrSettings> radarrSettings) public MovieSender(ISettingsService<RadarrSettings> radarrSettings)
{ {
RadarrSettings = radarrSettings; RadarrSettings = radarrSettings;
@ -37,12 +35,17 @@ namespace Ombi.Core
//return SendToRadarr(model, radarrSettings, qualityId); //return SendToRadarr(model, radarrSettings, qualityId);
} }
return new MovieSenderResult { Success = false, MovieSent = false, Message = "There are no movie providers enabled!"}; return new MovieSenderResult
{
Success = false,
MovieSent = false,
Message = "There are no movie providers enabled!"
};
} }
//private MovieSenderResult SendToRadarr(MovieRequestModel model, RadarrSettings settings, string qualityId)
//{
// var qualityProfile = 0; // var qualityProfile = 0;
//{
//private MovieSenderResult SendToRadarr(MovieRequestModel model, RadarrSettings settings, string qualityId)
// if (!string.IsNullOrEmpty(qualityId)) // try to parse the passed in quality, otherwise use the settings default quality // if (!string.IsNullOrEmpty(qualityId)) // try to parse the passed in quality, otherwise use the settings default quality
// { // {
// int.TryParse(qualityId, out qualityProfile); // int.TryParse(qualityId, out qualityProfile);
@ -67,6 +70,5 @@ namespace Ombi.Core
// } // }
// return new MovieSenderResult { Result = false, MovieSendingEnabled = true }; // return new MovieSenderResult { Result = false, MovieSendingEnabled = true };
//} //}
} }
} }

@ -1,6 +1,4 @@
using Ombi.Core.Rules; namespace Ombi.Core.Rule
namespace Ombi.Core.Rule
{ {
public abstract class BaseRule public abstract class BaseRule
{ {

@ -1,4 +1,5 @@
using Ombi.Core.Models.Requests; using Ombi.Core.Models.Requests;
using Ombi.Core.Rule;
namespace Ombi.Core.Rules namespace Ombi.Core.Rules
{ {

@ -1,5 +1,6 @@
using System.Collections.Generic; using Ombi.Core.Models.Requests;
using Ombi.Core.Models.Requests; using Ombi.Core.Rule;
using System.Collections.Generic;
namespace Ombi.Core.Rules namespace Ombi.Core.Rules
{ {

@ -1,11 +1,11 @@
using Ombi.Core.Models.Requests; using Ombi.Core.Models.Requests;
using Ombi.Core.Rule; using Ombi.Core.Rules;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Reflection; using System.Reflection;
namespace Ombi.Core.Rules namespace Ombi.Core.Rule
{ {
public class RuleEvaluator : IRuleEvaluator public class RuleEvaluator : IRuleEvaluator
{ {
@ -14,27 +14,23 @@ namespace Ombi.Core.Rules
RequestRules = new List<IRequestRules<BaseRequestModel>>(); RequestRules = new List<IRequestRules<BaseRequestModel>>();
var baseType = typeof(BaseRule).FullName; var baseType = typeof(BaseRule).FullName;
System.Reflection.Assembly ass = typeof(RuleEvaluator).GetTypeInfo().Assembly; var ass = typeof(RuleEvaluator).GetTypeInfo().Assembly;
foreach (TypeInfo ti in ass.DefinedTypes) foreach (var ti in ass.DefinedTypes)
{
if (ti?.BaseType?.FullName == baseType) if (ti?.BaseType?.FullName == baseType)
{ {
var type = ti.AsType(); var type = ti?.AsType();
var ctors = type.GetConstructors(); var ctors = type.GetConstructors();
var ctor = ctors.FirstOrDefault(); var ctor = ctors.FirstOrDefault();
var services = new List<object>(); var services = new List<object>();
foreach (var param in ctor.GetParameters()) foreach (var param in ctor.GetParameters())
{
services.Add(provider.GetService(param.ParameterType)); services.Add(provider.GetService(param.ParameterType));
}
var item = Activator.CreateInstance(type, services.ToArray()); // ti.GetType is wrong var item = Activator.CreateInstance(type, services.ToArray()); // ti.GetType is wrong
RequestRules.Add((IRequestRules<BaseRequestModel>) item); RequestRules.Add((IRequestRules<BaseRequestModel>) item);
} }
} }
}
private List<IRequestRules<BaseRequestModel>> RequestRules { get; } private List<IRequestRules<BaseRequestModel>> RequestRules { get; }

@ -1,8 +1,4 @@
using System; namespace Ombi.Core.Rule
using System.Collections.Generic;
using System.Text;
namespace Ombi.Core.Rules
{ {
public class RuleResult public class RuleResult
{ {

@ -1,10 +1,8 @@
using Ombi.Core.Claims; using Ombi.Core.Claims;
using Ombi.Core.Models.Requests; using Ombi.Core.Models.Requests;
using Ombi.Core.Rules; using Ombi.Core.Rules;
using System; using Ombi.Store.Entities;
using System.Collections.Generic;
using System.Security.Principal; using System.Security.Principal;
using System.Text;
namespace Ombi.Core.Rule.Rules namespace Ombi.Core.Rule.Rules
{ {
@ -16,6 +14,7 @@ namespace Ombi.Core.Rule.Rules
} }
private IPrincipal User { get; } private IPrincipal User { get; }
public RuleResult Execute(BaseRequestModel obj) public RuleResult Execute(BaseRequestModel obj)
{ {
if (User.IsInRole(OmbiClaims.Admin)) if (User.IsInRole(OmbiClaims.Admin))
@ -24,14 +23,10 @@ namespace Ombi.Core.Rule.Rules
return Success(); return Success();
} }
if (obj.Type == Store.Entities.RequestType.Movie && User.IsInRole(OmbiClaims.AutoApproveMovie)) if (obj.Type == RequestType.Movie && User.IsInRole(OmbiClaims.AutoApproveMovie))
{
obj.Approved = true; obj.Approved = true;
} if (obj.Type == RequestType.TvShow && User.IsInRole(OmbiClaims.AutoApproveTv))
if (obj.Type == Store.Entities.RequestType.TvShow && User.IsInRole(OmbiClaims.AutoApproveTv))
{
obj.Approved = true; obj.Approved = true;
}
return Success(); // We don't really care, we just don't set the obj to approve return Success(); // We don't really care, we just don't set the obj to approve
} }
} }

@ -1,6 +1,7 @@
using Ombi.Core.Claims; using Ombi.Core.Claims;
using Ombi.Core.Models.Requests; using Ombi.Core.Models.Requests;
using Ombi.Core.Rules; using Ombi.Core.Rules;
using Ombi.Store.Entities;
using System.Security.Principal; using System.Security.Principal;
namespace Ombi.Core.Rule.Rules namespace Ombi.Core.Rule.Rules
@ -13,29 +14,22 @@ namespace Ombi.Core.Rule.Rules
} }
private IPrincipal User { get; } private IPrincipal User { get; }
public RuleResult Execute(BaseRequestModel obj) public RuleResult Execute(BaseRequestModel obj)
{ {
if (User.IsInRole(OmbiClaims.Admin)) if (User.IsInRole(OmbiClaims.Admin))
{
return Success(); return Success();
}
if (obj.Type == Store.Entities.RequestType.Movie) if (obj.Type == RequestType.Movie)
{ {
if (User.IsInRole(OmbiClaims.RequestMovie)) if (User.IsInRole(OmbiClaims.RequestMovie))
{
return Success(); return Success();
}
return Fail("You do not have permissions to Request a Movie"); return Fail("You do not have permissions to Request a Movie");
} }
else
{
if (User.IsInRole(OmbiClaims.RequestTv)) if (User.IsInRole(OmbiClaims.RequestTv))
{
return Success(); return Success();
}
return Fail("You do not have permissions to Request a Movie"); return Fail("You do not have permissions to Request a Movie");
} }
} }
} }
}

@ -1,10 +1,8 @@
using System; using Microsoft.Extensions.Logging;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Ombi.Api.Sonarr; using Ombi.Api.Sonarr;
using Ombi.Core.Models.Requests;
using Ombi.Core.Settings.Models.External; using Ombi.Core.Settings.Models.External;
using System.Linq;
using System.Threading.Tasks;
namespace Ombi.Core namespace Ombi.Core
{ {
@ -73,12 +71,8 @@ namespace Ombi.Core
var rootFoldersResult = await SonarrApi.GetRootFolders(sonarrSettings.ApiKey, sonarrSettings.FullUri); var rootFoldersResult = await SonarrApi.GetRootFolders(sonarrSettings.ApiKey, sonarrSettings.FullUri);
foreach (var r in rootFoldersResult.Where(r => r.id == pathId)) foreach (var r in rootFoldersResult.Where(r => r.id == pathId))
{
return r.path; return r.path;
}
return string.Empty; return string.Empty;
} }
} }
} }

@ -15,6 +15,7 @@ using Ombi.Core.Engine.Interfaces;
using Ombi.Core.IdentityResolver; using Ombi.Core.IdentityResolver;
using Ombi.Core.Models.Requests; using Ombi.Core.Models.Requests;
using Ombi.Core.Requests.Models; using Ombi.Core.Requests.Models;
using Ombi.Core.Rule;
using Ombi.Core.Settings; using Ombi.Core.Settings;
using Ombi.Notifications; using Ombi.Notifications;
using Ombi.Schedule; using Ombi.Schedule;

@ -1,31 +1,4 @@
#region Copyright using Microsoft.AspNetCore.Mvc;
// /************************************************************************
// Copyright (c) 2017 Jamie Rees
// File: BaseV1ApiController.cs
// Created By: Jamie Rees
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ************************************************************************/
#endregion
using Microsoft.AspNetCore.Mvc;
namespace Ombi.Controllers namespace Ombi.Controllers
{ {

@ -1,5 +1,4 @@
 <settings-menu></settings-menu>
<settings-menu></settings-menu>
<div *ngIf="settings"> <div *ngIf="settings">
<fieldset> <fieldset>
<legend>Plex Configuration</legend> <legend>Plex Configuration</legend>
@ -9,7 +8,6 @@
<label for="advanced">Advanced</label> <label for="advanced">Advanced</label>
</div> </div>
<div class="form-group col-md-3"> <div class="form-group col-md-3">
<div class="checkbox"> <div class="checkbox">
<input type="checkbox" id="enable" [(ngModel)]="settings.enable" ng-checked="settings.enable"> <input type="checkbox" id="enable" [(ngModel)]="settings.enable" ng-checked="settings.enable">
@ -47,7 +45,6 @@
<div class="form-group"> <div class="form-group">
<div> <div>
<button id="requestToken" (click)="requestServers(server)" class="btn btn-primary-outline">Load Servers <i class="fa fa-key"></i></button> <button id="requestToken" (click)="requestServers(server)" class="btn btn-primary-outline">Load Servers <i class="fa fa-key"></i></button>
</div> </div>
</div> </div>
<br /> <br />
@ -61,13 +58,13 @@
<span class="caret"></span> <span class="caret"></span>
</a> </a>
<ul *ngIf="loadedServers" class="dropdown-menu">
<ul *ngIf="loadedServers" class="dropdown-menu"><li *ngFor="let s of loadedServers.servers.server"><a (click)="selectServer(s,server)">{{s.name}}</a></li> <li *ngFor="let s of loadedServers.servers.server">
<a (click)="selectServer(s,server)">{{s.name}}</a>
</li>
</ul> </ul>
</div> </div>
</div> </div>
</div> </div>
<div *ngIf="advanced"> <div *ngIf="advanced">
@ -102,10 +99,8 @@
<div class="form-group"> <div class="form-group">
<div class="checkbox"> <div class="checkbox">
<input type="checkbox" id="EnableTvEpisodeSearching" [(ngModel)]="server.enableEpisodeSearching" ng-checked="server.enableEpisodeSearching"> <input type="checkbox" id="EnableTvEpisodeSearching" [(ngModel)]="server.enableEpisodeSearching" ng-checked="server.enableEpisodeSearching">
<label for="EnableTvEpisodeSearching">Enable Episode Searching</label> <label for="EnableTvEpisodeSearching">Enable Episode Searching</label>
</div> </div>
<small> <small>
If enabled then we will lookup all episodes on your Plex server and store them in the local database. This will stop episode requests that already exist on Plex (that might not be in Sonarr). If enabled then we will lookup all episodes on your Plex server and store them in the local database. This will stop episode requests that already exist on Plex (that might not be in Sonarr).
@ -113,7 +108,6 @@
</small> </small>
</div> </div>
<div class="form-group"> <div class="form-group">
<label for="authToken" class="control-label">Plex Authorization Token</label> <label for="authToken" class="control-label">Plex Authorization Token</label>
<div class=""> <div class="">
@ -127,10 +121,6 @@
<input type="text" class="form-control-custom form-control" id="MachineIdentifier" name="MachineIdentifier" [(ngModel)]="server.machineIdentifier" value="{{server.machineIdentifier}}"> <input type="text" class="form-control-custom form-control" id="MachineIdentifier" name="MachineIdentifier" [(ngModel)]="server.machineIdentifier" value="{{server.machineIdentifier}}">
</div> </div>
</div> </div>
</div> </div>
<label>Please select the libraries you want Ombi to look in for content</label> <label>Please select the libraries you want Ombi to look in for content</label>
<br /> <br />
@ -148,7 +138,6 @@
<label for="{{lib.title}}">{{lib.title}}</label> <label for="{{lib.title}}">{{lib.title}}</label>
</div> </div>
</div> </div>
</div> </div>
</div> </div>
@ -165,9 +154,6 @@
</div> </div>
</ngb-tabset> </ngb-tabset>
<div class="form-group"> <div class="form-group">
<div> <div>
<button (click)="save()" type="submit" id="save" class="btn btn-primary-outline">Submit</button> <button (click)="save()" type="submit" id="save" class="btn btn-primary-outline">Submit</button>

@ -5,7 +5,6 @@ import "rxjs/add/operator/takeUntil";
import { IPlexSettings, IPlexLibraries, IPlexServer } from '../../interfaces/ISettings'; import { IPlexSettings, IPlexLibraries, IPlexServer } from '../../interfaces/ISettings';
import { IPlexServerResponse, IPlexServerViewModel } from '../../interfaces/IPlex' import { IPlexServerResponse, IPlexServerViewModel } from '../../interfaces/IPlex'
import { SettingsService } from '../../services/settings.service'; import { SettingsService } from '../../services/settings.service';
import { PlexService } from '../../services/applications/plex.service'; import { PlexService } from '../../services/applications/plex.service';
import { NotificationService } from "../../services/notification.service"; import { NotificationService } from "../../services/notification.service";
@ -16,7 +15,6 @@ import { NotificationService } from "../../services/notification.service";
templateUrl: './plex.component.html', templateUrl: './plex.component.html',
}) })
export class PlexComponent implements OnInit, OnDestroy { export class PlexComponent implements OnInit, OnDestroy {
constructor(private settingsService: SettingsService, private notificationService: NotificationService, private plexService: PlexService) { } constructor(private settingsService: SettingsService, private notificationService: NotificationService, private plexService: PlexService) { }
settings: IPlexSettings; settings: IPlexSettings;
@ -27,7 +25,6 @@ export class PlexComponent implements OnInit, OnDestroy {
advanced = false; advanced = false;
serversButton = false; serversButton = false;
ngOnInit(): void { ngOnInit(): void {
this.settingsService.getPlex().subscribe(x => { this.settingsService.getPlex().subscribe(x => {
this.settings = x; this.settings = x;
@ -49,8 +46,7 @@ export class PlexComponent implements OnInit, OnDestroy {
}); });
} }
selectServer(selectedServer: IPlexServerResponse, server : IPlexServer) selectServer(selectedServer: IPlexServerResponse, server: IPlexServer) {
{
server.ip = selectedServer.localAddresses.split(',')[0]; server.ip = selectedServer.localAddresses.split(',')[0];
server.name = selectedServer.name; server.name = selectedServer.name;
server.machineIdentifier = selectedServer.machineIdentifier; server.machineIdentifier = selectedServer.machineIdentifier;
@ -75,7 +71,6 @@ export class PlexComponent implements OnInit, OnDestroy {
} }
removeServer(server: IPlexServer) { removeServer(server: IPlexServer) {
this.notificationService.warning("Disabled", "This feature is currently disabled"); this.notificationService.warning("Disabled", "This feature is currently disabled");
//var index = this.settings.servers.indexOf(server, 0); //var index = this.settings.servers.indexOf(server, 0);
//if (index > -1) { //if (index > -1) {
@ -84,13 +79,11 @@ export class PlexComponent implements OnInit, OnDestroy {
} }
loadLibraries(server: IPlexServer) { loadLibraries(server: IPlexServer) {
if (server.ip == null) if (server.ip == null) {
{
this.notificationService.error("Not Configured", "Plex is not yet configured correctly") this.notificationService.error("Not Configured", "Plex is not yet configured correctly")
return; return;
} }
this.plexService.getLibraries(server).subscribe(x => { this.plexService.getLibraries(server).subscribe(x => {
server.plexSelectedLibraries = []; server.plexSelectedLibraries = [];
x.mediaContainer.directory.forEach((item, index) => { x.mediaContainer.directory.forEach((item, index) => {
var lib: IPlexLibraries = { var lib: IPlexLibraries = {
@ -99,7 +92,6 @@ export class PlexComponent implements OnInit, OnDestroy {
enabled: false enabled: false
}; };
server.plexSelectedLibraries.push(lib); server.plexSelectedLibraries.push(lib);
}); });
}); });
} }

Loading…
Cancel
Save