You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
Ombi/src/Ombi.Core/Engine/TvRequestEngine.cs

265 lines
9.8 KiB

using AutoMapper;
8 years ago
using Hangfire;
using Ombi.Api.TvMaze;
using Ombi.Core.Models.Requests;
using Ombi.Core.Models.Search;
using Ombi.Core.Rules;
8 years ago
using Ombi.Helpers;
using Ombi.Notifications;
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;
using Ombi.Core.Engine.Interfaces;
8 years ago
namespace Ombi.Core.Engine
{
public class TvRequestEngine : BaseMediaEngine, ITvRequestEngine
{
public TvRequestEngine(ITvMazeApi tvApi, IRequestServiceMain requestService, IPrincipal user,
INotificationService notificationService, IMapper map,
IRuleEvaluator rule) : base(user, requestService, rule)
8 years ago
{
TvApi = tvApi;
NotificationService = notificationService;
8 years ago
Mapper = map;
8 years ago
}
8 years ago
private INotificationService NotificationService { get; }
private ITvMazeApi TvApi { get; }
8 years ago
private IMapper Mapper { get; }
8 years ago
public async Task<RequestEngineResult> RequestTvShow(SearchTvShowViewModel tv)
{
var showInfo = await TvApi.ShowLookupByTheTvDbId(tv.Id);
DateTime.TryParse(showInfo.premiered, out DateTime firstAir);
8 years ago
// For some reason the poster path is always http
var posterPath = showInfo.image?.medium.Replace("http:", "https:");
var childRequest = new ChildTvRequest
8 years ago
{
8 years ago
Id = tv.Id,
8 years ago
Type = RequestType.TvShow,
Overview = showInfo.summary.RemoveHtml(),
PosterPath = posterPath,
Title = showInfo.name,
ReleaseDate = firstAir,
Status = showInfo.status,
RequestedDate = DateTime.UtcNow,
Approved = false,
RequestedUsers = new List<string> { Username },
8 years ago
Issues = IssueState.None,
ProviderId = tv.Id,
RequestAll = tv.RequestAll,
SeasonRequests = tv.SeasonRequests
};
var model = new TvRequestModel
{
Id = tv.Id,
Type = RequestType.TvShow,
Overview = showInfo.summary.RemoveHtml(),
PosterPath = posterPath,
Title = showInfo.name,
ReleaseDate = firstAir,
Status = showInfo.status,
Approved = false,
8 years ago
ImdbId = showInfo.externals?.imdb ?? string.Empty,
TvDbId = tv.Id.ToString(),
ProviderId = tv.Id
8 years ago
};
model.ChildRequests.Add(childRequest);
if (childRequest.SeasonRequests.Any())
{
var episodes = await TvApi.EpisodeLookup(showInfo.id);
foreach (var e in episodes)
{
var season = childRequest.SeasonRequests.FirstOrDefault(x => x.SeasonNumber == e.season);
season?.Episodes.Add(new EpisodesRequested
{
Url = e.url,
Title = e.name,
AirDate = DateTime.Parse(e.airstamp),
EpisodeNumber = e.number
});
}
}
if (tv.LatestSeason)
{
8 years ago
var latest = showInfo.Season.OrderBy(x => x.SeasonNumber).FirstOrDefault();
foreach (var modelSeasonRequest in childRequest.SeasonRequests)
if (modelSeasonRequest.SeasonNumber == latest.SeasonNumber)
foreach (var episodesRequested in modelSeasonRequest.Episodes)
episodesRequested.Requested = true;
}
if (tv.FirstSeason)
{
8 years ago
var first = showInfo.Season.OrderByDescending(x => x.SeasonNumber).FirstOrDefault();
foreach (var modelSeasonRequest in childRequest.SeasonRequests)
if (modelSeasonRequest.SeasonNumber == first.SeasonNumber)
foreach (var episodesRequested in modelSeasonRequest.Episodes)
episodesRequested.Requested = true;
}
var ruleResults = RunRules(model).ToList();
8 years ago
if (ruleResults.Any(x => !x.Success))
return new RequestEngineResult
8 years ago
{
ErrorMessage = ruleResults.FirstOrDefault(x => !string.IsNullOrEmpty(x.Message)).Message
8 years ago
};
8 years ago
var existingRequest = await TvRequestService.CheckRequestAsync(model.Id);
if (existingRequest != null)
return await AddExistingRequest(model, existingRequest);
// This is a new request
return await AddRequest(model);
}
public async Task<IEnumerable<TvRequestModel>> GetRequests(int count, int position)
8 years ago
{
var allRequests = await TvRequestService.GetAllAsync(count, position);
return allRequests;
}
public async Task<IEnumerable<TvRequestModel>> GetRequests()
{
var allRequests = await TvRequestService.GetAllAsync();
return allRequests;
}
8 years ago
public async Task<IEnumerable<TvRequestModel>> SearchTvRequest(string search)
{
var allRequests = await TvRequestService.GetAllAsync();
var results = allRequests.Where(x => x.Title.Contains(search, CompareOptions.IgnoreCase));
return results;
}
8 years ago
public async Task<TvRequestModel> UpdateTvRequest(TvRequestModel request)
{
var allRequests = await TvRequestService.GetAllAsync();
var results = allRequests.FirstOrDefault(x => x.Id == request.Id);
results = Mapper.Map<TvRequestModel>(request);
8 years ago
8 years ago
var model = TvRequestService.UpdateRequest(results);
return model;
}
public async Task RemoveTvRequest(int requestId)
{
await TvRequestService.DeleteRequestAsync(requestId);
}
private async Task<RequestEngineResult> AddExistingRequest(TvRequestModel newRequest,
TvRequestModel existingRequest)
8 years ago
{
var child = newRequest.ChildRequests.FirstOrDefault(); // There will only be 1
var episodeDiff = new List<SeasonRequestModel>();
foreach (var existingChild in existingRequest.ChildRequests)
8 years ago
{
var difference = GetListDifferences(existingChild.SeasonRequests, child.SeasonRequests).ToList();
if (difference.Any())
episodeDiff = difference;
8 years ago
}
if (episodeDiff.Any())
child.SeasonRequests = episodeDiff;
8 years ago
existingRequest.ChildRequests.AddRange(newRequest.ChildRequests);
8 years ago
TvRequestService.UpdateRequest(existingRequest);
if (ShouldAutoApprove(RequestType.TvShow))
{
// TODO Auto Approval Code
}
return await AfterRequest(newRequest);
8 years ago
}
private IEnumerable<SeasonRequestModel> GetListDifferences(IEnumerable<SeasonRequestModel> existing,
IEnumerable<SeasonRequestModel> request)
8 years ago
{
var newRequest = request
.Select(r =>
new SeasonRequestModel
8 years ago
{
SeasonNumber = r.SeasonNumber,
Episodes = r.Episodes
})
.ToList();
8 years ago
return newRequest.Except(existing);
}
private async Task<RequestEngineResult> AddRequest(TvRequestModel model)
{
await TvRequestService.AddRequestAsync(model);
return await AfterRequest(model);
}
private async Task<RequestEngineResult> AfterRequest(TvRequestModel model)
{
8 years ago
if (ShouldSendNotification(model.Type))
{
var notificationModel = new NotificationModel
{
Title = model.Title,
User = Username,
DateTime = DateTime.Now,
NotificationType = NotificationType.NewRequest,
RequestType = model.Type,
ImgSrc = model.PosterPath
};
BackgroundJob.Enqueue(() => NotificationService.Publish(notificationModel).Wait());
}
//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 };
}
public async Task<IEnumerable<TvRequestModel>> GetApprovedRequests()
{
var allRequests = await TvRequestService.GetAllAsync();
return allRequests.Where(x => x.Approved && !x.Available);
}
public async Task<IEnumerable<TvRequestModel>> GetNewRequests()
{
var allRequests = await TvRequestService.GetAllAsync();
return allRequests.Where(x => !x.Approved && !x.Available);
}
public async Task<IEnumerable<TvRequestModel>> GetAvailableRequests()
{
var allRequests = await TvRequestService.GetAllAsync();
return allRequests.Where(x => x.Available);
8 years ago
}
}
}