using System; using System.Collections.Generic; using System.Linq; using Dapper; using NzbDrone.Core.Datastore; using NzbDrone.Core.Messaging.Events; using NzbDrone.Core.Movies; using NzbDrone.Core.Profiles; using NzbDrone.Core.Qualities; namespace NzbDrone.Core.History { public interface IHistoryRepository : IBasicRepository { List GetBestQualityInHistory(int movieId); History MostRecentForDownloadId(string downloadId); List FindByDownloadId(string downloadId); List FindDownloadHistory(int movieId, QualityModel quality); List GetByMovieId(int movieId, HistoryEventType? eventType); void DeleteForMovie(int movieId); History MostRecentForMovie(int movieId); List Since(DateTime date, HistoryEventType? eventType); } public class HistoryRepository : BasicRepository, IHistoryRepository { public HistoryRepository(IMainDatabase database, IEventAggregator eventAggregator) : base(database, eventAggregator) { } public List GetBestQualityInHistory(int movieId) { var history = Query(x => x.MovieId == movieId); return history.Select(h => h.Quality).ToList(); } public History MostRecentForDownloadId(string downloadId) { return FindByDownloadId(downloadId) .OrderByDescending(h => h.Date) .FirstOrDefault(); } public List FindByDownloadId(string downloadId) { return Query(x => x.DownloadId == downloadId); } public List FindDownloadHistory(int movieId, QualityModel quality) { var allowed = new [] { HistoryEventType.Grabbed, HistoryEventType.DownloadFailed, HistoryEventType.DownloadFolderImported }; return Query(h => h.MovieId == movieId && h.Quality == quality && allowed.Contains(h.EventType)); } public List GetByMovieId(int movieId, HistoryEventType? eventType) { var query = Query(x => x.MovieId == movieId); if (eventType.HasValue) { query = query.Where(h => h.EventType == eventType).ToList(); } query.OrderByDescending(h => h.Date); return query; } public void DeleteForMovie(int movieId) { Delete(c => c.MovieId == movieId); } private IEnumerable SelectJoined(SqlBuilder.Template sql) { using (var conn = _database.OpenConnection()) { return conn.Query( sql.RawSql, (hist, movie, profile) => { hist.Movie = movie; hist.Movie.Profile = profile; return hist; }, sql.Parameters) .ToList(); } } protected override SqlBuilder PagedBuilder() => new SqlBuilder() .Join("Movies ON Movies.Id = History.MovieId") .Join("Profiles ON Profiles.Id = Movies.ProfileId"); protected override IEnumerable PagedSelector(SqlBuilder.Template sql) => SelectJoined(sql); public History MostRecentForMovie(int movieId) { return Query(x => x.MovieId == movieId) .OrderByDescending(h => h.Date) .FirstOrDefault(); } public List Since(DateTime date, HistoryEventType? eventType) { var builder = Builder().Where(x => x.Date >= date); if (eventType.HasValue) { builder.Where(h => h.EventType == eventType); } return Query(builder).OrderBy(h => h.Date).ToList(); } } }