using System; using System.Collections.Generic; using System.Linq; using Marr.Data.QGen; using NzbDrone.Core.Datastore; using NzbDrone.Core.Messaging.Events; using NzbDrone.Core.Qualities; using NzbDrone.Core.Tv; namespace NzbDrone.Core.History { public interface IHistoryRepository : IBasicRepository { void Trim(); List GetBestQualityInHistory(int episodeId); List BetweenDates(DateTime startDate, DateTime endDate, HistoryEventType eventType); List Failed(); List Grabbed(); List Imported(); History MostRecentForEpisode(int episodeId); List FindBySourceTitle(string sourceTitle); } public class HistoryRepository : BasicRepository, IHistoryRepository { private readonly IDatabase _database; public HistoryRepository(IDatabase database, IEventAggregator eventAggregator) : base(database, eventAggregator) { _database = database; } public void Trim() { var cutoff = DateTime.UtcNow.AddDays(-30).Date; Delete(c=> c.Date < cutoff); } public List GetBestQualityInHistory(int episodeId) { var history = Query.Where(c => c.EpisodeId == episodeId); return history.Select(h => h.Quality).ToList(); } public List BetweenDates(DateTime startDate, DateTime endDate, HistoryEventType eventType) { return Query.Join(JoinType.Inner, h => h.Series, (h, s) => h.SeriesId == s.Id) .Join(JoinType.Inner, h => h.Episode, (h, e) => h.EpisodeId == e.Id) .Where(h => h.Date >= startDate) .AndWhere(h => h.Date <= endDate) .AndWhere(h => h.EventType == eventType); } public List Failed() { return Query.Where(h => h.EventType == HistoryEventType.DownloadFailed); } public List Grabbed() { return Query.Where(h => h.EventType == HistoryEventType.Grabbed); } public List Imported() { return Query.Where(h => h.EventType == HistoryEventType.DownloadFolderImported); } public History MostRecentForEpisode(int episodeId) { return Query.Where(h => h.EpisodeId == episodeId) .OrderByDescending(h => h.Date) .FirstOrDefault(); } public List FindBySourceTitle(string sourceTitle) { return Query.Where(h => h.SourceTitle.Contains(sourceTitle)); } public List AllForEpisode(int episodeId) { return Query.Where(h => h.EpisodeId == episodeId); } protected override SortBuilder GetPagedQuery(QueryBuilder query, PagingSpec pagingSpec) { var baseQuery = query.Join(JoinType.Inner, h => h.Series, (h, s) => h.SeriesId == s.Id) .Join(JoinType.Inner, h => h.Episode, (h, e) => h.EpisodeId == e.Id); return base.GetPagedQuery(baseQuery, pagingSpec); } } }