diff --git a/src/NzbDrone.Api/History/HistoryModule.cs b/src/NzbDrone.Api/History/HistoryModule.cs index 85b3f6135..405caae93 100644 --- a/src/NzbDrone.Api/History/HistoryModule.cs +++ b/src/NzbDrone.Api/History/HistoryModule.cs @@ -1,7 +1,10 @@ using System; -using System.Collections.Generic; -using NzbDrone.Api.Mapping; +using Nancy; +using Nancy.ModelBinding; +using NzbDrone.Api.Extensions; +using NzbDrone.Common.Serializer; using NzbDrone.Core.Datastore; +using NzbDrone.Core.Download; using NzbDrone.Core.History; namespace NzbDrone.Api.History @@ -9,11 +12,15 @@ namespace NzbDrone.Api.History public class HistoryModule : NzbDroneRestModule { private readonly IHistoryService _historyService; + private readonly IFailedDownloadService _failedDownloadService; - public HistoryModule(IHistoryService historyService) + public HistoryModule(IHistoryService historyService, IFailedDownloadService failedDownloadService) { _historyService = historyService; + _failedDownloadService = failedDownloadService; GetResourcePaged = GetHistory; + + Post["/failed"] = x => MarkAsFailed(); } private PagingResource GetHistory(PagingResource pagingResource) @@ -36,5 +43,12 @@ namespace NzbDrone.Api.History return ApplyToPage(_historyService.Paged, pagingSpec); } + + private Response MarkAsFailed() + { + var id = (int)Request.Form.Id; + _failedDownloadService.MarkAsFailed(id); + return new Object().AsResponse(); + } } } \ No newline at end of file diff --git a/src/NzbDrone.Api/History/HistoryResource.cs b/src/NzbDrone.Api/History/HistoryResource.cs index 0251e9354..fe572a25c 100644 --- a/src/NzbDrone.Api/History/HistoryResource.cs +++ b/src/NzbDrone.Api/History/HistoryResource.cs @@ -1,6 +1,8 @@ using System; using System.Collections.Generic; +using NzbDrone.Api.Episodes; using NzbDrone.Api.REST; +using NzbDrone.Api.Series; using NzbDrone.Core.History; using NzbDrone.Core.Tv; @@ -21,7 +23,7 @@ namespace NzbDrone.Api.History public Dictionary Data { get; set; } - public Episode Episode { get; set; } - public Core.Tv.Series Series { get; set; } + public EpisodeResource Episode { get; set; } + public SeriesResource Series { get; set; } } } diff --git a/src/NzbDrone.Api/Indexers/ReleaseResource.cs b/src/NzbDrone.Api/Indexers/ReleaseResource.cs index a745f3869..fda9ef67a 100644 --- a/src/NzbDrone.Api/Indexers/ReleaseResource.cs +++ b/src/NzbDrone.Api/Indexers/ReleaseResource.cs @@ -18,7 +18,7 @@ namespace NzbDrone.Api.Indexers public Boolean SceneSource { get; set; } public Int32 SeasonNumber { get; set; } public Language Language { get; set; } - public DateTime? AirDate { get; set; } + public String AirDate { get; set; } public String SeriesTitle { get; set; } public int[] EpisodeNumbers { get; set; } public Boolean Approved { get; set; } diff --git a/src/NzbDrone.Api/Update/UpdateModule.cs b/src/NzbDrone.Api/Update/UpdateModule.cs index 2ade0b76d..c35f3f50f 100644 --- a/src/NzbDrone.Api/Update/UpdateModule.cs +++ b/src/NzbDrone.Api/Update/UpdateModule.cs @@ -22,7 +22,6 @@ namespace NzbDrone.Api.Update _recentUpdateProvider = recentUpdateProvider; _installUpdateService = installUpdateService; GetResourceAll = GetRecentUpdates; - Post["/"] = x=> InstallUpdate(); } private List GetRecentUpdates() @@ -46,16 +45,6 @@ namespace NzbDrone.Api.Update return resources; } - - private Response InstallUpdate() - { - var updateResource = Request.Body.FromJson(); - - var updatePackage = updateResource.InjectTo(); - _installUpdateService.InstallUpdate(updatePackage); - - return updateResource.AsResponse(); - } } public class UpdateResource : RestResource diff --git a/src/NzbDrone.Core.Test/Blacklisting/BlacklistRepositoryFixture.cs b/src/NzbDrone.Core.Test/Blacklisting/BlacklistRepositoryFixture.cs new file mode 100644 index 000000000..39ff23c96 --- /dev/null +++ b/src/NzbDrone.Core.Test/Blacklisting/BlacklistRepositoryFixture.cs @@ -0,0 +1,57 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using FluentAssertions; +using Moq; +using NUnit.Framework; +using NzbDrone.Core.Blacklisting; +using NzbDrone.Core.Download; +using NzbDrone.Core.Qualities; +using NzbDrone.Core.Test.Framework; +using NzbDrone.Core.Tv; + +namespace NzbDrone.Core.Test.Blacklisting +{ + [TestFixture] + public class BlacklistRepositoryFixture : DbTest + { + private Blacklist _blacklist; + + [SetUp] + public void Setup() + { + _blacklist = new Blacklist + { + SeriesId = 12345, + EpisodeIds = new List {1}, + Quality = new QualityModel(Quality.Bluray720p), + SourceTitle = "series.title.s01e01", + Date = DateTime.UtcNow + }; + } + + [Test] + public void should_be_able_to_write_to_database() + { + Subject.Insert(_blacklist); + Subject.All().Should().HaveCount(1); + } + + [Test] + public void should_should_have_episode_ids() + { + Subject.Insert(_blacklist); + + Subject.All().First().EpisodeIds.Should().Contain(_blacklist.EpisodeIds); + } + + [Test] + public void should_check_for_blacklisted_title_case_insensative() + { + Subject.Insert(_blacklist); + + Subject.Blacklisted(_blacklist.SourceTitle.ToUpperInvariant()).Should().BeTrue(); + } + } +} diff --git a/src/NzbDrone.Core.Test/Blacklisting/BlacklistServiceFixture.cs b/src/NzbDrone.Core.Test/Blacklisting/BlacklistServiceFixture.cs new file mode 100644 index 000000000..85d19db97 --- /dev/null +++ b/src/NzbDrone.Core.Test/Blacklisting/BlacklistServiceFixture.cs @@ -0,0 +1,52 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using Moq; +using NUnit.Framework; +using NzbDrone.Core.Blacklisting; +using NzbDrone.Core.Download; +using NzbDrone.Core.Qualities; +using NzbDrone.Core.Test.Framework; +using NzbDrone.Core.Tv; + +namespace NzbDrone.Core.Test.Blacklisting +{ + [TestFixture] + public class BlacklistServiceFixture : CoreTest + { + private DownloadFailedEvent _event; + + [SetUp] + public void Setup() + { + _event = new DownloadFailedEvent + { + SeriesId = 12345, + EpisodeIds = new List {1}, + Quality = new QualityModel(Quality.Bluray720p), + SourceTitle = "series.title.s01e01", + DownloadClient = "SabnzbdClient", + DownloadClientId = "Sabnzbd_nzo_2dfh73k" + }; + } + + [Test] + public void should_trigger_redownload() + { + Subject.Handle(_event); + + Mocker.GetMock() + .Verify(v => v.Redownload(_event.SeriesId, _event.EpisodeIds), Times.Once()); + } + + [Test] + public void should_add_to_repository() + { + Subject.Handle(_event); + + Mocker.GetMock() + .Verify(v => v.Insert(It.Is(b => b.EpisodeIds == _event.EpisodeIds)), Times.Once()); + } + } +} diff --git a/src/NzbDrone.Core.Test/DecisionEngineTests/UpgradeHistorySpecificationFixture.cs b/src/NzbDrone.Core.Test/DecisionEngineTests/HistorySpecificationFixture.cs similarity index 70% rename from src/NzbDrone.Core.Test/DecisionEngineTests/UpgradeHistorySpecificationFixture.cs rename to src/NzbDrone.Core.Test/DecisionEngineTests/HistorySpecificationFixture.cs index 70e81dc8a..0fe7b7ba0 100644 --- a/src/NzbDrone.Core.Test/DecisionEngineTests/UpgradeHistorySpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/DecisionEngineTests/HistorySpecificationFixture.cs @@ -1,8 +1,11 @@ using System.Collections.Generic; using FizzWare.NBuilder; using FluentAssertions; +using Moq; using NUnit.Framework; using NzbDrone.Core.DecisionEngine.Specifications.RssSync; +using NzbDrone.Core.Download; +using NzbDrone.Core.Download.Clients.Sabnzbd; using NzbDrone.Core.History; using NzbDrone.Core.IndexerSearch.Definitions; using NzbDrone.Core.Parser.Model; @@ -15,9 +18,9 @@ using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.DecisionEngineTests { [TestFixture] - public class UpgradeHistorySpecificationFixture : CoreTest + public class HistorySpecificationFixture : CoreTest { - private UpgradeHistorySpecification _upgradeHistory; + private HistorySpecification _upgradeHistory; private RemoteEpisode _parseResultMulti; private RemoteEpisode _parseResultSingle; @@ -29,7 +32,7 @@ namespace NzbDrone.Core.Test.DecisionEngineTests public void Setup() { Mocker.Resolve(); - _upgradeHistory = Mocker.Resolve(); + _upgradeHistory = Mocker.Resolve(); var singleEpisodeList = new List { new Episode { Id = 1, SeasonNumber = 12, EpisodeNumber = 3 } }; var doubleEpisodeList = new List { @@ -64,6 +67,9 @@ namespace NzbDrone.Core.Test.DecisionEngineTests Mocker.GetMock().Setup(c => c.GetBestQualityInHistory(1)).Returns(_notupgradableQuality); Mocker.GetMock().Setup(c => c.GetBestQualityInHistory(2)).Returns(_notupgradableQuality); Mocker.GetMock().Setup(c => c.GetBestQualityInHistory(3)).Returns(null); + + Mocker.GetMock() + .Setup(c => c.GetDownloadClient()).Returns(Mocker.GetMock().Object); } private void WithFirstReportUpgradable() @@ -76,6 +82,17 @@ namespace NzbDrone.Core.Test.DecisionEngineTests Mocker.GetMock().Setup(c => c.GetBestQualityInHistory(2)).Returns(_upgradableQuality); } + private void GivenSabnzbdDownloadClient() + { + Mocker.GetMock() + .Setup(c => c.GetDownloadClient()).Returns(Mocker.Resolve()); + } + + private void GivenMostRecentForEpisode(HistoryEventType eventType) + { + Mocker.GetMock().Setup(s => s.MostRecentForEpisode(It.IsAny())) + .Returns(new History.History { EventType = eventType }); + } [Test] public void should_be_upgradable_if_only_episode_is_upgradable() @@ -129,5 +146,40 @@ namespace NzbDrone.Core.Test.DecisionEngineTests { _upgradeHistory.IsSatisfiedBy(_parseResultMulti, new SeasonSearchCriteria()).Should().BeTrue(); } + + [Test] + public void should_return_true_if_using_sabnzbd_and_nothing_in_history() + { + GivenSabnzbdDownloadClient(); + + _upgradeHistory.IsSatisfiedBy(_parseResultMulti, null).Should().BeTrue(); + } + + [Test] + public void should_return_false_if_most_recent_in_history_is_grabbed() + { + GivenSabnzbdDownloadClient(); + GivenMostRecentForEpisode(HistoryEventType.Grabbed); + + _upgradeHistory.IsSatisfiedBy(_parseResultMulti, null).Should().BeFalse(); + } + + [Test] + public void should_return_true_if_most_recent_in_history_is_failed() + { + GivenSabnzbdDownloadClient(); + GivenMostRecentForEpisode(HistoryEventType.DownloadFailed); + + _upgradeHistory.IsSatisfiedBy(_parseResultMulti, null).Should().BeTrue(); + } + + [Test] + public void should_return_true_if_most_recent_in_history_is_imported() + { + GivenSabnzbdDownloadClient(); + GivenMostRecentForEpisode(HistoryEventType.DownloadFolderImported); + + _upgradeHistory.IsSatisfiedBy(_parseResultMulti, null).Should().BeTrue(); + } } } \ No newline at end of file diff --git a/src/NzbDrone.Core.Test/Download/DownloadClientTests/SabProviderTests/QueueFixture.cs b/src/NzbDrone.Core.Test/Download/DownloadClientTests/SabProviderTests/QueueFixture.cs deleted file mode 100644 index 1b5c75c22..000000000 --- a/src/NzbDrone.Core.Test/Download/DownloadClientTests/SabProviderTests/QueueFixture.cs +++ /dev/null @@ -1,324 +0,0 @@ -/*using System; -using System.Collections.Generic; -using System.Linq; -using FluentAssertions; -using Moq; -using NUnit.Framework; -using NzbDrone.Common; -using NzbDrone.Core.Configuration; -using NzbDrone.Core.Download.Clients.Sabnzbd; -using NzbDrone.Core.Model; -using NzbDrone.Core.Qualities; -using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Tv; -using NzbDrone.Test.Common; - -namespace NzbDrone.Core.Test.Download.DownloadClientTests.SabProviderTests -{ - [TestFixture] - - public class QueueFixture : CoreTest - { - [SetUp] - public void Setup() - { - string sabHost = "192.168.5.55"; - int sabPort = 2222; - string apikey = "5c770e3197e4fe763423ee7c392c25d1"; - string username = "admin"; - string password = "pass"; - string cat = "tv"; - - var fakeConfig = Mocker.GetMock(); - fakeConfig.SetupGet(c => c.SabHost).Returns(sabHost); - fakeConfig.SetupGet(c => c.SabPort).Returns(sabPort); - fakeConfig.SetupGet(c => c.SabApiKey).Returns(apikey); - fakeConfig.SetupGet(c => c.SabUsername).Returns(username); - fakeConfig.SetupGet(c => c.SabPassword).Returns(password); - fakeConfig.SetupGet(c => c.SabTvCategory).Returns(cat); - } - - private void WithFullQueue() - { - Mocker.GetMock() - .Setup( - s => - s.DownloadString( - "http://192.168.5.55:2222/api?mode=queue&output=json&start=0&limit=0&apikey=5c770e3197e4fe763423ee7c392c25d1&ma_username=admin&ma_password=pass")) - .Returns(ReadAllText("Files","Queue.txt")); - } - - private void WithEmptyQueue() - { - Mocker.GetMock() - .Setup(s => s.DownloadString("http://192.168.5.55:2222/api?mode=queue&output=json&start=0&limit=0&apikey=5c770e3197e4fe763423ee7c392c25d1&ma_username=admin&ma_password=pass")) - .Returns(ReadAllText("Files","QueueEmpty.txt")); - } - - private void WithFailResponse() - { - Mocker.GetMock() - .Setup(s => s.DownloadString(It.IsAny())).Returns(ReadAllText("Files","JsonError.txt")); - } - - private void WithUnknownPriorityQueue() - { - Mocker.GetMock() - .Setup( - s => - s.DownloadString( - "http://192.168.5.55:2222/api?mode=queue&output=json&start=0&limit=0&apikey=5c770e3197e4fe763423ee7c392c25d1&ma_username=admin&ma_password=pass")) - .Returns(ReadAllText("Files", "QueueUnknownPriority.txt")); - } - - [Test] - public void GetQueue_should_return_an_empty_list_when_the_queue_is_empty() - { - WithEmptyQueue(); - - var result = Mocker.Resolve().GetQueue(); - - result.Should().BeEmpty(); - } - - [Test] - public void GetQueue_should_throw_when_there_is_an_error_getting_the_queue() - { - WithFailResponse(); - - Assert.Throws(() => Mocker.Resolve().GetQueue(), "API Key Incorrect"); - } - - [Test] - public void GetQueue_should_return_a_list_with_items_when_the_queue_has_items() - { - WithFullQueue(); - - var result = Mocker.Resolve().GetQueue(); - - result.Should().HaveCount(7); - } - - [Test] - public void GetQueue_should_return_a_list_with_items_even_when_priority_is_non_standard() - { - WithUnknownPriorityQueue(); - - var result = Mocker.Resolve().GetQueue(); - - result.Should().HaveCount(7); - } - - [Test] - public void is_in_queue_should_find_if_exact_episode_is_in_queue() - { - WithFullQueue(); - - var parseResult = new RemoteEpisode - { - EpisodeTitle = "Title", - EpisodeNumbers = new List { 5 }, - SeasonNumber = 1, - Quality = new QualityModel { Quality = Quality.SDTV, Proper = false }, - Series = new Series { Title = "30 Rock", CleanTitle = Parser.NormalizeTitle("30 Rock") }, - }; - - - var result = Mocker.Resolve().IsInQueue(parseResult); - - result.Should().BeTrue(); - } - - [Test] - public void is_in_queue_should_find_if_exact_daily_episode_is_in_queue() - { - WithFullQueue(); - - var parseResult = new RemoteEpisode - { - Quality = new QualityModel { Quality = Quality.Bluray720p, Proper = false }, - AirDate = new DateTime(2011, 12, 01), - Series = new Series { Title = "The Dailyshow", CleanTitle = Parser.NormalizeTitle("The Dailyshow"), SeriesType = SeriesTypes.Daily }, - }; - - - var result = Mocker.Resolve().IsInQueue(parseResult); - - result.Should().BeTrue(); - } - - [Test] - public void is_in_queue_should_find_if_exact_full_season_release_is_in_queue() - { - WithFullQueue(); - - - var parseResult = new RemoteEpisode - { - Quality = new QualityModel { Quality = Quality.Bluray720p, Proper = false }, - FullSeason = true, - SeasonNumber = 5, - Series = new Series { Title = "My Name is earl", CleanTitle = Parser.NormalizeTitle("My Name is earl") }, - }; - - var result = Mocker.Resolve().IsInQueue(parseResult); - - result.Should().BeTrue(); - } - - public static object[] DifferentEpisodeCases = - { - new object[] { 2, new[] { 5 }, "30 Rock", Quality.Bluray1080p, true }, //Same Series, Different Season, Episode - new object[] { 1, new[] { 6 }, "30 Rock", Quality.Bluray1080p, true }, //Same series, different episodes - new object[] { 1, new[] { 6, 7, 8 }, "30 Rock", Quality.Bluray1080p, true }, //Same series, different episodes - new object[] { 1, new[] { 6 }, "Some other show", Quality.Bluray1080p, true }, //Different series, same season, episode - new object[] { 1, new[] { 5 }, "Rock", Quality.Bluray1080p, true }, //Similar series, same season, episodes - new object[] { 1, new[] { 5 }, "30 Rock", Quality.Bluray720p, false }, //Same series, higher quality - new object[] { 1, new[] { 5 }, "30 Rock", Quality.HDTV720p, true } //Same series, higher quality - }; - - [Test, TestCaseSource("DifferentEpisodeCases")] - public void IsInQueue_should_not_find_diffrent_episode_queue(int season, int[] episodes, string title, Quality qualityType, bool proper) - { - WithFullQueue(); - - var parseResult = new RemoteEpisode - { - EpisodeTitle = "Title", - EpisodeNumbers = new List(episodes), - SeasonNumber = season, - Quality = new QualityModel { Quality = qualityType, Proper = proper }, - Series = new Series { Title = title, CleanTitle = Parser.NormalizeTitle(title) }, - }; - - var result = Mocker.Resolve().IsInQueue(parseResult); - - result.Should().BeFalse(); - } - - public static object[] LowerQualityCases = - { - new object[] { 1, new[] { 5 }, "30 Rock", Quality.SDTV, false }, //Same Series, lower quality - new object[] { 1, new[] { 5 }, "30 rocK", Quality.SDTV, false }, //Same Series, different casing - new object[] { 1, new[] { 5 }, "30 RocK", Quality.HDTV720p, false }, //Same Series, same quality - new object[] { 1, new[] { 5, 6 }, "30 RocK", Quality.HDTV720p, false }, //Same Series, same quality, one different episode - new object[] { 1, new[] { 5, 6 }, "30 RocK", Quality.HDTV720p, false }, //Same Series, same quality, one different episode - new object[] { 4, new[] { 8 }, "Parks and Recreation", Quality.WEBDL720p, false }, //Same Series, same quality - }; - - [Test, TestCaseSource("LowerQualityCases")] - public void IsInQueue_should_find_same_or_lower_quality_episode_queue(int season, int[] episodes, string title, Quality qualityType, bool proper) - { - WithFullQueue(); - - var parseResult = new RemoteEpisode - { - EpisodeTitle = "Title", - EpisodeNumbers = new List(episodes), - SeasonNumber = season, - Quality = new QualityModel { Quality = qualityType, Proper = proper }, - Series = new Series { Title = title, CleanTitle = Parser.NormalizeTitle(title) }, - }; - - var result = Mocker.Resolve().IsInQueue(parseResult); - - result.Should().BeTrue(); - } - - public static object[] DuplicateItemsCases = - { - new object[] { 5, new[] { 13 }, "The Big Bang Theory", Quality.SDTV, false }, //Same Series, lower quality - new object[] { 5, new[] { 13 }, "The Big Bang Theory", Quality.HDTV720p, false }, //Same Series, same quality - new object[] { 5, new[] { 13 }, "The Big Bang Theory", Quality.HDTV720p, true }, //Same Series, same quality - new object[] { 5, new[] { 13, 14 }, "The Big Bang Theory", Quality.HDTV720p, false } //Same Series, same quality, one diffrent episode - }; - - [Test, TestCaseSource("DuplicateItemsCases")] - public void IsInQueue_should_find_items_marked_as_duplicate(int season, int[] episodes, string title, Quality qualityType, bool proper) - { - WithFullQueue(); - - var parseResult = new RemoteEpisode - { - EpisodeTitle = "Title", - EpisodeNumbers = new List(episodes), - SeasonNumber = season, - Quality = new QualityModel { Quality = qualityType, Proper = proper }, - Series = new Series { Title = title, CleanTitle = Parser.NormalizeTitle(title) }, - }; - - var result = Mocker.Resolve().IsInQueue(parseResult); - - result.Should().BeTrue(); - } - - public static object[] DoubleEpisodeCases = - { - new object[] { 3, new[] { 14, 15 }, "My Name Is Earl", Quality.Bluray720p, false }, - new object[] { 3, new[] { 15 }, "My Name Is Earl", Quality.DVD, false }, - new object[] { 3, new[] { 14 }, "My Name Is Earl", Quality.HDTV720p, false }, - new object[] { 3, new[] { 15, 16 }, "My Name Is Earl", Quality.SDTV, false } - }; - - [Test, TestCaseSource("DoubleEpisodeCases")] - public void IsInQueue_should_find_double_episodes_(int season, int[] episodes, string title, Quality qualityType, bool proper) - { - WithFullQueue(); - - var parseResult = new RemoteEpisode - { - EpisodeTitle = "Title", - EpisodeNumbers = new List(episodes), - SeasonNumber = season, - Quality = new QualityModel { Quality = qualityType, Proper = proper }, - Series = new Series { Title = title, CleanTitle = Parser.NormalizeTitle(title) }, - }; - - var result = Mocker.Resolve().IsInQueue(parseResult); - - result.Should().BeTrue(); - } - - [Test] - public void IsInQueue_should_return_false_if_queue_is_empty() - { - WithEmptyQueue(); - - var parseResult = new RemoteEpisode - { - EpisodeTitle = "Title", - EpisodeNumbers = new List { 1 }, - SeasonNumber = 2, - Quality = new QualityModel { Quality = Quality.Bluray1080p, Proper = true }, - Series = new Series { Title = "Test", CleanTitle = Parser.NormalizeTitle("Test") }, - }; - - var result = Mocker.Resolve().IsInQueue(parseResult); - - result.Should().BeFalse(); - } - - [Test] - public void GetQueue_should_parse_timeleft_with_hours_greater_than_24_hours() - { - WithFullQueue(); - - var result = Mocker.Resolve().GetQueue(); - - result.Should().NotBeEmpty(); - var timeleft = result.First(q => q.Id == "SABnzbd_nzo_qv6ilb").Timeleft; - timeleft.Days.Should().Be(2); - timeleft.Hours.Should().Be(9); - timeleft.Minutes.Should().Be(27); - timeleft.Seconds.Should().Be(45); - } - - [TearDown] - public void TearDown() - { - ExceptionVerification.IgnoreWarns(); - } - - - } -}*/ \ No newline at end of file diff --git a/src/NzbDrone.Core.Test/Download/DownloadClientTests/SabProviderTests/SabProviderFixture.cs b/src/NzbDrone.Core.Test/Download/DownloadClientTests/SabProviderTests/SabProviderFixture.cs index f23a2b762..615c7a7e4 100644 --- a/src/NzbDrone.Core.Test/Download/DownloadClientTests/SabProviderTests/SabProviderFixture.cs +++ b/src/NzbDrone.Core.Test/Download/DownloadClientTests/SabProviderTests/SabProviderFixture.cs @@ -1,4 +1,5 @@ using System; +using System.IO; using System.Linq; using System.Net; using FizzWare.NBuilder; @@ -46,30 +47,6 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.SabProviderTests .ToList(); } - private void WithFailResponse() - { - Mocker.GetMock() - .Setup(s => s.DownloadString(It.IsAny())).Returns("{ \"status\": false, \"error\": \"API Key Required\" }"); - } - - [Test] - public void add_url_should_format_request_properly() - { - Mocker.GetMock(MockBehavior.Strict) - .Setup(s => s.DownloadString("http://192.168.5.55:2222/api?mode=addurl&name=http://www.nzbclub.com/nzb_download.aspx?mid=1950232&priority=0&pp=3&cat=tv&nzbname=My+Series+Name+-+5x2-5x3+-+My+title+%5bBluray720p%5d+%5bProper%5d&output=json&apikey=5c770e3197e4fe763423ee7c392c25d1&ma_username=admin&ma_password=pass")) - .Returns("{ \"status\": true }"); - - - Subject.DownloadNzb(_remoteEpisode); - } - - [Test] - public void add_by_url_should_detect_and_handle_sab_errors() - { - WithFailResponse(); - Assert.Throws(() => Subject.DownloadNzb(_remoteEpisode)); - } - [Test] public void should_be_able_to_get_categories_when_config_is_passed_in() { @@ -195,15 +172,6 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.SabProviderTests result.Should().Be("0.6.9"); } - [Test] - public void should_throw_when_WebException_is_thrown() - { - Mocker.GetMock() - .Setup(s => s.DownloadString(It.IsAny())).Throws(new WebException()); - - Assert.Throws(() => Subject.DownloadNzb(_remoteEpisode)); - } - [Test] public void downloadNzb_should_use_sabRecentTvPriority_when_recentEpisode_is_true() { @@ -211,16 +179,14 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.SabProviderTests .SetupGet(s => s.SabRecentTvPriority) .Returns(SabPriorityType.High); - - Mocker.GetMock() - .Setup(s => s.DownloadString("http://192.168.5.55:2222/api?mode=addurl&name=http://www.nzbclub.com/nzb_download.aspx?mid=1950232&priority=1&pp=3&cat=tv&nzbname=My+Series+Name+-+5x2-5x3+-+My+title+%5bBluray720p%5d+%5bProper%5d&output=json&apikey=5c770e3197e4fe763423ee7c392c25d1&ma_username=admin&ma_password=pass")) - .Returns("{ \"status\": true }"); - + Mocker.GetMock() + .Setup(s => s.DownloadNzb(It.IsAny(), It.IsAny(), It.IsAny(), (int)SabPriorityType.High)) + .Returns("{ \"status\": \"true\", \"nzo_ids\": [ \"sab_id_goes_here\" ] }"); Subject.DownloadNzb(_remoteEpisode); - Mocker.GetMock() - .Verify(v => v.DownloadString("http://192.168.5.55:2222/api?mode=addurl&name=http://www.nzbclub.com/nzb_download.aspx?mid=1950232&priority=1&pp=3&cat=tv&nzbname=My+Series+Name+-+5x2-5x3+-+My+title+%5bBluray720p%5d+%5bProper%5d&output=json&apikey=5c770e3197e4fe763423ee7c392c25d1&ma_username=admin&ma_password=pass"), Times.Once()); + Mocker.GetMock() + .Verify(v => v.DownloadNzb(It.IsAny(), It.IsAny(), It.IsAny(), (int)SabPriorityType.High), Times.Once()); } } } diff --git a/src/NzbDrone.Core.Test/Download/DownloadServiceFixture.cs b/src/NzbDrone.Core.Test/Download/DownloadServiceFixture.cs index 86413bcc4..cb3a0313c 100644 --- a/src/NzbDrone.Core.Test/Download/DownloadServiceFixture.cs +++ b/src/NzbDrone.Core.Test/Download/DownloadServiceFixture.cs @@ -82,7 +82,6 @@ namespace NzbDrone.Core.Test.Download VerifyEventNotPublished(); } - [Test] public void should_not_attempt_download_if_client_isnt_configure() { diff --git a/src/NzbDrone.Core.Test/Download/FailedDownloadServiceFixture.cs b/src/NzbDrone.Core.Test/Download/FailedDownloadServiceFixture.cs new file mode 100644 index 000000000..170e0a0b9 --- /dev/null +++ b/src/NzbDrone.Core.Test/Download/FailedDownloadServiceFixture.cs @@ -0,0 +1,209 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using FizzWare.NBuilder; +using Moq; +using NUnit.Framework; +using NzbDrone.Core.Configuration; +using NzbDrone.Core.Download; +using NzbDrone.Core.History; +using NzbDrone.Core.Messaging.Events; +using NzbDrone.Core.Test.Framework; + +namespace NzbDrone.Core.Test.Download +{ + [TestFixture] + public class FailedDownloadServiceFixture : CoreTest + { + private List _completed; + private List _failed; + + [SetUp] + public void Setup() + { + _completed = Builder.CreateListOfSize(5) + .All() + .With(h => h.Status = HistoryStatus.Completed) + .Build() + .ToList(); + + _failed = Builder.CreateListOfSize(1) + .All() + .With(h => h.Status = HistoryStatus.Failed) + .Build() + .ToList(); + + Mocker.GetMock() + .Setup(c => c.GetDownloadClient()).Returns(Mocker.GetMock().Object); + + Mocker.GetMock() + .SetupGet(s => s.EnableFailedDownloadHandling) + .Returns(true); + } + + private void GivenNoGrabbedHistory() + { + Mocker.GetMock() + .Setup(s => s.Grabbed()) + .Returns(new List()); + } + + private void GivenGrabbedHistory(List history) + { + Mocker.GetMock() + .Setup(s => s.Grabbed()) + .Returns(history); + } + + private void GivenNoFailedHistory() + { + Mocker.GetMock() + .Setup(s => s.Failed()) + .Returns(new List()); + } + + private void GivenFailedHistory(List failedHistory) + { + Mocker.GetMock() + .Setup(s => s.Failed()) + .Returns(failedHistory); + } + + private void GivenFailedDownloadClientHistory() + { + Mocker.GetMock() + .Setup(s => s.GetHistory(0, 20)) + .Returns(_failed); + } + + private void VerifyNoFailedDownloads() + { + Mocker.GetMock() + .Verify(v => v.PublishEvent(It.IsAny()), Times.Never()); + } + + private void VerifyFailedDownloads(int count = 1) + { + Mocker.GetMock() + .Verify(v => v.PublishEvent(It.Is(d => d.EpisodeIds.Count == count)), Times.Once()); + } + + [Test] + public void should_not_process_if_no_download_client_history() + { + Mocker.GetMock() + .Setup(s => s.GetHistory(0, 20)) + .Returns(new List()); + + Subject.Execute(new FailedDownloadCommand()); + + Mocker.GetMock() + .Verify(s => s.BetweenDates(It.IsAny(), It.IsAny(), HistoryEventType.Grabbed), + Times.Never()); + + VerifyNoFailedDownloads(); + } + + [Test] + public void should_not_process_if_no_failed_items_in_download_client_history() + { + Mocker.GetMock() + .Setup(s => s.GetHistory(0, 20)) + .Returns(_completed); + + Subject.Execute(new FailedDownloadCommand()); + + Mocker.GetMock() + .Verify(s => s.BetweenDates(It.IsAny(), It.IsAny(), HistoryEventType.Grabbed), + Times.Never()); + + VerifyNoFailedDownloads(); + } + + [Test] + public void should_not_process_if_matching_history_is_not_found() + { + GivenNoGrabbedHistory(); + GivenFailedDownloadClientHistory(); + + Subject.Execute(new FailedDownloadCommand()); + + VerifyNoFailedDownloads(); + } + + [Test] + public void should_not_process_if_already_added_to_history_as_failed() + { + GivenFailedDownloadClientHistory(); + + var history = Builder.CreateListOfSize(1) + .Build() + .ToList(); + + GivenGrabbedHistory(history); + GivenFailedHistory(history); + + history.First().Data.Add("downloadClient", "SabnzbdClient"); + history.First().Data.Add("downloadClientId", _failed.First().Id); + + Subject.Execute(new FailedDownloadCommand()); + + VerifyNoFailedDownloads(); + } + + [Test] + public void should_process_if_not_already_in_failed_history() + { + GivenFailedDownloadClientHistory(); + + var history = Builder.CreateListOfSize(1) + .Build() + .ToList(); + + GivenGrabbedHistory(history); + GivenNoFailedHistory(); + + history.First().Data.Add("downloadClient", "SabnzbdClient"); + history.First().Data.Add("downloadClientId", _failed.First().Id); + + Subject.Execute(new FailedDownloadCommand()); + + VerifyFailedDownloads(); + } + + [Test] + public void should_have_multiple_episode_ids_when_multi_episode_release_fails() + { + GivenFailedDownloadClientHistory(); + + var history = Builder.CreateListOfSize(2) + .Build() + .ToList(); + + GivenGrabbedHistory(history); + GivenNoFailedHistory(); + + history.ForEach(h => + { + h.Data.Add("downloadClient", "SabnzbdClient"); + h.Data.Add("downloadClientId", _failed.First().Id); + }); + + Subject.Execute(new FailedDownloadCommand()); + + VerifyFailedDownloads(2); + } + + [Test] + public void should_skip_if_enable_failed_download_handling_is_off() + { + Mocker.GetMock() + .SetupGet(s => s.EnableFailedDownloadHandling) + .Returns(false); + + Subject.Execute(new FailedDownloadCommand()); + + VerifyNoFailedDownloads(); + } + } +} diff --git a/src/NzbDrone.Core.Test/MediaFiles/EpisodeImport/Specifications/NotSampleSpecificationFixture.cs b/src/NzbDrone.Core.Test/MediaFiles/EpisodeImport/Specifications/NotSampleSpecificationFixture.cs index 3699ffeb6..62c610bbf 100644 --- a/src/NzbDrone.Core.Test/MediaFiles/EpisodeImport/Specifications/NotSampleSpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/MediaFiles/EpisodeImport/Specifications/NotSampleSpecificationFixture.cs @@ -7,6 +7,7 @@ using NUnit.Framework; using NzbDrone.Core.MediaFiles.EpisodeImport.Specifications; using NzbDrone.Core.MediaFiles.MediaInfo; using NzbDrone.Core.Parser.Model; +using NzbDrone.Core.Qualities; using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Tv; using NzbDrone.Test.Common; @@ -36,112 +37,117 @@ namespace NzbDrone.Core.Test.MediaFiles.EpisodeImport.Specifications { Path = @"C:\Test\30 Rock\30.rock.s01e01.avi", Episodes = episodes, - Series = _series + Series = _series, + Quality = new QualityModel(Quality.HDTV720p) }; } - private void WithDailySeries() - { - _series.SeriesType = SeriesTypes.Daily; - } - - private void WithSeasonZero() - { - _localEpisode.Episodes[0].SeasonNumber = 0; - } - - private void WithFileSize(long size) + private void GivenFileSize(long size) { _localEpisode.Size = size; } - private void WithLength(int minutes) + private void GivenRuntime(int seconds) { Mocker.GetMock() .Setup(s => s.GetRunTime(It.IsAny())) - .Returns(new TimeSpan(0, 0, minutes, 0)); + .Returns(new TimeSpan(0, 0, seconds)); } [Test] public void should_return_true_if_series_is_daily() { - WithDailySeries(); - + _series.SeriesType = SeriesTypes.Daily; Subject.IsSatisfiedBy(_localEpisode).Should().BeTrue(); } [Test] public void should_return_true_if_season_zero() { - WithSeasonZero(); + _localEpisode.Episodes[0].SeasonNumber = 0; + Subject.IsSatisfiedBy(_localEpisode).Should().BeTrue(); + } + [Test] + public void should_return_true_for_existing_file() + { + _localEpisode.ExistingFile = true; Subject.IsSatisfiedBy(_localEpisode).Should().BeTrue(); } [Test] - public void should_return_false_if_undersize_and_under_length() + public void should_return_true_for_flv() { - WithFileSize(10.Megabytes()); - WithLength(1); + _localEpisode.Path = @"C:\Test\some.show.s01e01.flv"; - Subject.IsSatisfiedBy(_localEpisode).Should().BeFalse(); + Subject.IsSatisfiedBy(_localEpisode).Should().BeTrue(); + + Mocker.GetMock().Verify(c => c.GetRunTime(It.IsAny()), Times.Never()); } [Test] - public void should_return_true_if_undersize() + public void should_not_run_runtime_check_on_linux() { - WithFileSize(10.Megabytes()); - WithLength(10); + LinuxOnly(); + GivenFileSize(1000.Megabytes()); - Subject.IsSatisfiedBy(_localEpisode).Should().BeTrue(); + Subject.IsSatisfiedBy(_localEpisode); + + Mocker.GetMock().Verify(v => v.GetRunTime(It.IsAny()), Times.Never()); } [Test] - public void should_return_true_if_under_length() + public void should_run_runtime_check_on_windows() { - WithFileSize(100.Megabytes()); - WithLength(1); + WindowsOnly(); - Subject.IsSatisfiedBy(_localEpisode).Should().BeTrue(); + GivenRuntime(120); + GivenFileSize(1000.Megabytes()); + + Subject.IsSatisfiedBy(_localEpisode); + + Mocker.GetMock().Verify(v => v.GetRunTime(It.IsAny()), Times.Once()); } [Test] - public void should_return_true_if_over_size_and_length() + public void should_return_false_if_runtime_is_less_than_minimum() { - WithFileSize(100.Megabytes()); - WithLength(10); + WindowsOnly(); + GivenRuntime(60); - Subject.IsSatisfiedBy(_localEpisode).Should().BeTrue(); + Subject.IsSatisfiedBy(_localEpisode).Should().BeFalse(); } [Test] - public void should_not_check_lenght_if_file_is_large_enough() + public void should_return_true_if_runtime_greater_than_than_minimum() { - WithFileSize(100.Megabytes()); + WindowsOnly(); + GivenRuntime(120); Subject.IsSatisfiedBy(_localEpisode).Should().BeTrue(); - - Mocker.GetMock().Verify(c => c.GetRunTime(It.IsAny()), Times.Never()); } [Test] - public void should_log_error_if_run_time_is_0_and_under_sample_size() + public void should_return_false_if_file_size_is_under_minimum() { - WithFileSize(40.Megabytes()); - WithLength(0); + LinuxOnly(); + + GivenRuntime(120); + GivenFileSize(20.Megabytes()); Subject.IsSatisfiedBy(_localEpisode).Should().BeFalse(); - ExceptionVerification.ExpectedErrors(1); } [Test] - public void should_skip_check_for_flv_file() + public void should_return_false_if_file_size_is_under_minimum_for_larger_limits() { - _localEpisode.Path = @"C:\Test\some.show.s01e01.flv"; + LinuxOnly(); - Subject.IsSatisfiedBy(_localEpisode).Should().BeTrue(); + GivenRuntime(120); + GivenFileSize(120.Megabytes()); + _localEpisode.Quality = new QualityModel(Quality.Bluray1080p); - Mocker.GetMock().Verify(c => c.GetRunTime(It.IsAny()), Times.Never()); + Subject.IsSatisfiedBy(_localEpisode).Should().BeFalse(); } } } diff --git a/src/NzbDrone.Core.Test/MediaFiles/EpisodeImport/Specifications/NotUnpackingSpecificationFixture.cs b/src/NzbDrone.Core.Test/MediaFiles/EpisodeImport/Specifications/NotUnpackingSpecificationFixture.cs index 05a45a1f6..db8afed53 100644 --- a/src/NzbDrone.Core.Test/MediaFiles/EpisodeImport/Specifications/NotUnpackingSpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/MediaFiles/EpisodeImport/Specifications/NotUnpackingSpecificationFixture.cs @@ -54,6 +54,8 @@ namespace NzbDrone.Core.Test.MediaFiles.EpisodeImport.Specifications [Test] public void should_return_true_when_in_old_working_folder() { + WindowsOnly(); + GivenInWorkingFolder(); GivenLastWriteTimeUtc(DateTime.UtcNow.AddHours(-1)); @@ -68,5 +70,16 @@ namespace NzbDrone.Core.Test.MediaFiles.EpisodeImport.Specifications Subject.IsSatisfiedBy(_localEpisode).Should().BeFalse(); } + + [Test] + public void should_return_false_if_unopacking_on_linux() + { + LinuxOnly(); + + GivenInWorkingFolder(); + GivenLastWriteTimeUtc(DateTime.UtcNow.AddDays(-5)); + + Subject.IsSatisfiedBy(_localEpisode).Should().BeFalse(); + } } } diff --git a/src/NzbDrone.Core.Test/NzbDrone.Core.Test.csproj b/src/NzbDrone.Core.Test/NzbDrone.Core.Test.csproj index e75b4d0ac..66bd95291 100644 --- a/src/NzbDrone.Core.Test/NzbDrone.Core.Test.csproj +++ b/src/NzbDrone.Core.Test/NzbDrone.Core.Test.csproj @@ -99,6 +99,8 @@ + + @@ -121,9 +123,9 @@ - + @@ -167,7 +169,9 @@ + + @@ -193,7 +197,7 @@ - + diff --git a/src/NzbDrone.Core.Test/ParserTests/ParserFixture.cs b/src/NzbDrone.Core.Test/ParserTests/ParserFixture.cs index d74c5aedf..5652f3b6c 100644 --- a/src/NzbDrone.Core.Test/ParserTests/ParserFixture.cs +++ b/src/NzbDrone.Core.Test/ParserTests/ParserFixture.cs @@ -6,6 +6,7 @@ using NUnit.Framework; using NzbDrone.Common.Expansive; using NzbDrone.Core.Parser; using NzbDrone.Core.Test.Framework; +using NzbDrone.Core.Tv; using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.ParserTests @@ -21,6 +22,9 @@ namespace NzbDrone.Core.Test.ParserTests * [TestCase("Desparate Housewives - S07E22 - 7x23 - And Lots of Security.. [HDTV-720p].mkv", "Desparate Housewives", 7, new[] { 22, 23 }, 2)] * [TestCase("S07E22 - 7x23 - And Lots of Security.. [HDTV-720p].mkv", "", 7, new[] { 22, 23 }, 2)] * (Game of Thrones s03 e - "Game of Thrones Season 3 Episode 10" + * The.Man.of.Steel.1994-05.33.hybrid.DreamGirl-Novus-HD + * Superman.-.The.Man.of.Steel.1994-06.34.hybrid.DreamGirl-Novus-HD + * Superman.-.The.Man.of.Steel.1994-05.33.hybrid.DreamGirl-Novus-HD */ [TestCase("Sonny.With.a.Chance.S02E15", "Sonny.With.a.Chance", 2, 15)] @@ -80,6 +84,7 @@ namespace NzbDrone.Core.Test.ParserTests [TestCase("(Game of Thrones s03 e - \"Game of Thrones Season 3 Episode 10\"", "Game of Thrones", 3, 10)] [TestCase("House.Hunters.International.S05E607.720p.hdtv.x264", "House.Hunters.International", 5, 607)] [TestCase("Adventure.Time.With.Finn.And.Jake.S01E20.720p.BluRay.x264-DEiMOS", "Adventure.Time.With.Finn.And.Jake", 1, 20)] + [TestCase("Hostages.S01E04.2-45.PM.[HDTV-720p].mkv", "Hostages", 1, 4)] public void ParseTitle_single(string postTitle, string title, int seasonNumber, int episodeNumber) { var result = Parser.Parser.ParseTitle(postTitle); @@ -168,7 +173,7 @@ namespace NzbDrone.Core.Test.ParserTests var airDate = new DateTime(year, month, day); result.Should().NotBeNull(); result.SeriesTitle.Should().Be(title.CleanSeriesTitle()); - result.AirDate.Should().Be(airDate); + result.AirDate.Should().Be(airDate.ToString(Episode.AIR_DATE_FORMAT)); result.EpisodeNumbers.Should().BeNull(); } @@ -230,6 +235,7 @@ namespace NzbDrone.Core.Test.ParserTests [TestCase("The.Daily.Show", "dailyshow")] [TestCase("Castle (2009)", "castle2009")] [TestCase("Parenthood.2010", "parenthood2010")] + [TestCase("Law_and_Order_SVU", "lawordersvu")] public void series_name_normalize(string parsedSeriesName, string seriesName) { var result = parsedSeriesName.CleanSeriesTitle(); diff --git a/src/NzbDrone.Core.Test/ParserTests/ParsingServiceTests/GetEpisodesFixture.cs b/src/NzbDrone.Core.Test/ParserTests/ParsingServiceTests/GetEpisodesFixture.cs index 35dc82373..b1d235dee 100644 --- a/src/NzbDrone.Core.Test/ParserTests/ParsingServiceTests/GetEpisodesFixture.cs +++ b/src/NzbDrone.Core.Test/ParserTests/ParsingServiceTests/GetEpisodesFixture.cs @@ -61,7 +61,7 @@ namespace NzbDrone.Core.Test.ParserTests.ParsingServiceTests private void GivenDailyParseResult() { - _parsedEpisodeInfo.AirDate = DateTime.Today; + _parsedEpisodeInfo.AirDate = DateTime.Today.ToString(Episode.AIR_DATE_FORMAT); } private void GivenSceneNumberingSeries() @@ -78,7 +78,7 @@ namespace NzbDrone.Core.Test.ParserTests.ParsingServiceTests Subject.Map(_parsedEpisodeInfo, _series.TvRageId); Mocker.GetMock() - .Verify(v => v.FindEpisode(It.IsAny(), It.IsAny()), Times.Once()); + .Verify(v => v.FindEpisode(It.IsAny(), It.IsAny()), Times.Once()); } [Test] @@ -90,19 +90,19 @@ namespace NzbDrone.Core.Test.ParserTests.ParsingServiceTests Subject.Map(_parsedEpisodeInfo, _series.TvRageId, _singleEpisodeSearchCriteria); Mocker.GetMock() - .Verify(v => v.FindEpisode(It.IsAny(), It.IsAny()), Times.Never()); + .Verify(v => v.FindEpisode(It.IsAny(), It.IsAny()), Times.Never()); } [Test] public void should_fallback_to_daily_episode_lookup_when_search_criteria_episode_doesnt_match() { GivenDailySeries(); - _parsedEpisodeInfo.AirDate = DateTime.Today.AddDays(-5); + _parsedEpisodeInfo.AirDate = DateTime.Today.AddDays(-5).ToString(Episode.AIR_DATE_FORMAT); ; Subject.Map(_parsedEpisodeInfo, _series.TvRageId, _singleEpisodeSearchCriteria); Mocker.GetMock() - .Verify(v => v.FindEpisode(It.IsAny(), It.IsAny()), Times.Once()); + .Verify(v => v.FindEpisode(It.IsAny(), It.IsAny()), Times.Once()); } [Test] diff --git a/src/NzbDrone.Core.Test/ParserTests/ParsingServiceTests/GetSeriesFixture.cs b/src/NzbDrone.Core.Test/ParserTests/ParsingServiceTests/GetSeriesFixture.cs new file mode 100644 index 000000000..bad109bf9 --- /dev/null +++ b/src/NzbDrone.Core.Test/ParserTests/ParsingServiceTests/GetSeriesFixture.cs @@ -0,0 +1,51 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using Moq; +using NUnit.Framework; +using NzbDrone.Core.Parser; +using NzbDrone.Core.Test.Framework; +using NzbDrone.Core.Tv; + +namespace NzbDrone.Core.Test.ParserTests.ParsingServiceTests +{ + [TestFixture] + public class GetSeriesFixture : CoreTest + { + [Test] + public void should_use_passed_in_title_when_it_cannot_be_parsed() + { + const string title = "30 Rock"; + + Subject.GetSeries(title); + + Mocker.GetMock() + .Verify(s => s.FindByTitle(title), Times.Once()); + } + + [Test] + public void should_use_parsed_series_title() + { + const string title = "30.Rock.S01E01.720p.hdtv"; + + Subject.GetSeries(title); + + Mocker.GetMock() + .Verify(s => s.FindByTitle(Parser.Parser.ParseTitle(title).SeriesTitle), Times.Once()); + } + + [Test] + public void should_fallback_to_title_without_year_and_year_when_title_lookup_fails() + { + const string title = "House.2004.S01E01.720p.hdtv"; + var parsedEpisodeInfo = Parser.Parser.ParseTitle(title); + + Subject.GetSeries(title); + + Mocker.GetMock() + .Verify(s => s.FindByTitle(parsedEpisodeInfo.SeriesTitleInfo.TitleWithoutYear, + parsedEpisodeInfo.SeriesTitleInfo.Year), Times.Once()); + } + } +} diff --git a/src/NzbDrone.Core.Test/ParserTests/SeriesTitleInfoFixture.cs b/src/NzbDrone.Core.Test/ParserTests/SeriesTitleInfoFixture.cs new file mode 100644 index 000000000..5f2e00b9c --- /dev/null +++ b/src/NzbDrone.Core.Test/ParserTests/SeriesTitleInfoFixture.cs @@ -0,0 +1,64 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using FluentAssertions; +using NUnit.Framework; +using NzbDrone.Core.Test.Framework; + +namespace NzbDrone.Core.Test.ParserTests +{ + [TestFixture] + public class SeriesTitleInfoFixture : CoreTest + { + [Test] + public void should_have_year_zero_when_title_doesnt_have_a_year() + { + const string title = "House.S01E01.pilot.720p.hdtv"; + + var result = Parser.Parser.ParseTitle(title).SeriesTitleInfo; + + result.Year.Should().Be(0); + } + + [Test] + public void should_have_same_title_for_title_and_title_without_year_when_title_doesnt_have_a_year() + { + const string title = "House.S01E01.pilot.720p.hdtv"; + + var result = Parser.Parser.ParseTitle(title).SeriesTitleInfo; + + result.Title.Should().Be(result.TitleWithoutYear); + } + + [Test] + public void should_have_year_when_title_has_a_year() + { + const string title = "House.2004.S01E01.pilot.720p.hdtv"; + + var result = Parser.Parser.ParseTitle(title).SeriesTitleInfo; + + result.Year.Should().Be(2004); + } + + [Test] + public void should_have_year_in_title_when_title_has_a_year() + { + const string title = "House.2004.S01E01.pilot.720p.hdtv"; + + var result = Parser.Parser.ParseTitle(title).SeriesTitleInfo; + + result.Title.Should().Be("house2004"); + } + + [Test] + public void should_title_without_year_should_not_contain_year() + { + const string title = "House.2004.S01E01.pilot.720p.hdtv"; + + var result = Parser.Parser.ParseTitle(title).SeriesTitleInfo; + + result.TitleWithoutYear.Should().Be("house"); + } + } +} diff --git a/src/NzbDrone.Core/Blacklisting/Blacklist.cs b/src/NzbDrone.Core/Blacklisting/Blacklist.cs new file mode 100644 index 000000000..94cc5ffed --- /dev/null +++ b/src/NzbDrone.Core/Blacklisting/Blacklist.cs @@ -0,0 +1,16 @@ +using System; +using System.Collections.Generic; +using NzbDrone.Core.Datastore; +using NzbDrone.Core.Tv; + +namespace NzbDrone.Core.Blacklisting +{ + public class Blacklist : ModelBase + { + public int SeriesId { get; set; } + public List EpisodeIds { get; set; } + public string SourceTitle { get; set; } + public QualityModel Quality { get; set; } + public DateTime Date { get; set; } + } +} diff --git a/src/NzbDrone.Core/Blacklisting/BlacklistRepository.cs b/src/NzbDrone.Core/Blacklisting/BlacklistRepository.cs new file mode 100644 index 000000000..c0b7e5fbf --- /dev/null +++ b/src/NzbDrone.Core/Blacklisting/BlacklistRepository.cs @@ -0,0 +1,24 @@ +using System; +using NzbDrone.Core.Datastore; +using NzbDrone.Core.Messaging.Events; + +namespace NzbDrone.Core.Blacklisting +{ + public interface IBlacklistRepository : IBasicRepository + { + bool Blacklisted(string sourceTitle); + } + + public class BlacklistRepository : BasicRepository, IBlacklistRepository + { + public BlacklistRepository(IDatabase database, IEventAggregator eventAggregator) : + base(database, eventAggregator) + { + } + + public bool Blacklisted(string sourceTitle) + { + return Query.Any(e => e.SourceTitle.Contains(sourceTitle)); + } + } +} diff --git a/src/NzbDrone.Core/Blacklisting/BlacklistService.cs b/src/NzbDrone.Core/Blacklisting/BlacklistService.cs new file mode 100644 index 000000000..4f15c59f9 --- /dev/null +++ b/src/NzbDrone.Core/Blacklisting/BlacklistService.cs @@ -0,0 +1,47 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using NzbDrone.Core.Download; +using NzbDrone.Core.Messaging.Events; + +namespace NzbDrone.Core.Blacklisting +{ + public interface IBlacklistService + { + bool Blacklisted(string sourceTitle); + } + + public class BlacklistService : IBlacklistService, IHandle + { + private readonly IBlacklistRepository _blacklistRepository; + private readonly IRedownloadFailedDownloads _redownloadFailedDownloadService; + + public BlacklistService(IBlacklistRepository blacklistRepository, IRedownloadFailedDownloads redownloadFailedDownloadService) + { + _blacklistRepository = blacklistRepository; + _redownloadFailedDownloadService = redownloadFailedDownloadService; + } + + public bool Blacklisted(string sourceTitle) + { + return _blacklistRepository.Blacklisted(sourceTitle); + } + + public void Handle(DownloadFailedEvent message) + { + var blacklist = new Blacklist + { + SeriesId = message.SeriesId, + EpisodeIds = message.EpisodeIds, + SourceTitle = message.SourceTitle, + Quality = message.Quality, + Date = DateTime.UtcNow + }; + + _blacklistRepository.Insert(blacklist); + + _redownloadFailedDownloadService.Redownload(message.SeriesId, message.EpisodeIds); + } + } +} diff --git a/src/NzbDrone.Core/Configuration/ConfigService.cs b/src/NzbDrone.Core/Configuration/ConfigService.cs index a7bebdb6d..c480dd7cf 100644 --- a/src/NzbDrone.Core/Configuration/ConfigService.cs +++ b/src/NzbDrone.Core/Configuration/ConfigService.cs @@ -261,6 +261,27 @@ namespace NzbDrone.Core.Configuration set { SetValue("AutoDownloadPropers", value); } } + public Boolean AutoRedownloadFailed + { + get { return GetValueBoolean("AutoRedownloadFailed", true); } + + set { SetValue("AutoRedownloadFailed", value); } + } + + public Boolean RemoveFailedDownloads + { + get { return GetValueBoolean("RemoveFailedDownloads", true); } + + set { SetValue("RemoveFailedDownloads", value); } + } + + public Boolean EnableFailedDownloadHandling + { + get { return GetValueBoolean("EnableFailedDownloadHandling", true); } + + set { SetValue("EnableFailedDownloadHandling", value); } + } + public string DownloadClientWorkingFolders { get { return GetValue("DownloadClientWorkingFolders", "_UNPACK_|_FAILED_"); } diff --git a/src/NzbDrone.Core/Configuration/IConfigService.cs b/src/NzbDrone.Core/Configuration/IConfigService.cs index e226740b0..8df4fbaa2 100644 --- a/src/NzbDrone.Core/Configuration/IConfigService.cs +++ b/src/NzbDrone.Core/Configuration/IConfigService.cs @@ -39,6 +39,9 @@ namespace NzbDrone.Core.Configuration Int32 RssSyncInterval { get; set; } Boolean AutoDownloadPropers { get; set; } String DownloadClientWorkingFolders { get; set; } + Boolean AutoRedownloadFailed { get; set; } + Boolean RemoveFailedDownloads { get; set; } + Boolean EnableFailedDownloadHandling { get; set; } void SaveValues(Dictionary configValues); } } diff --git a/src/NzbDrone.Core/Datastore/Migration/028_add_blacklist_table.cs b/src/NzbDrone.Core/Datastore/Migration/028_add_blacklist_table.cs new file mode 100644 index 000000000..0514c9689 --- /dev/null +++ b/src/NzbDrone.Core/Datastore/Migration/028_add_blacklist_table.cs @@ -0,0 +1,19 @@ +using FluentMigrator; +using NzbDrone.Core.Datastore.Migration.Framework; + +namespace NzbDrone.Core.Datastore.Migration +{ + [Migration(28)] + public class add_blacklist_table : NzbDroneMigrationBase + { + protected override void MainDbUpgrade() + { + Create.TableForModel("Blacklist") + .WithColumn("SeriesId").AsInt32() + .WithColumn("EpisodeIds").AsString() + .WithColumn("SourceTitle").AsString() + .WithColumn("Quality").AsString() + .WithColumn("Date").AsDateTime(); + } + } +} diff --git a/src/NzbDrone.Core/Datastore/TableMapping.cs b/src/NzbDrone.Core/Datastore/TableMapping.cs index ec341d6dc..5b5fe331f 100644 --- a/src/NzbDrone.Core/Datastore/TableMapping.cs +++ b/src/NzbDrone.Core/Datastore/TableMapping.cs @@ -4,6 +4,7 @@ using System.Linq; using Marr.Data; using Marr.Data.Mapping; using NzbDrone.Common.Reflection; +using NzbDrone.Core.Blacklisting; using NzbDrone.Core.Configuration; using NzbDrone.Core.DataAugmentation.Scene; using NzbDrone.Core.Datastore.Converters; @@ -67,6 +68,8 @@ namespace NzbDrone.Core.Datastore Mapper.Entity().RegisterModel("NamingConfig"); Mapper.Entity().MapResultSet(); + + Mapper.Entity().RegisterModel("Blacklist"); } private static void RegisterMappers() @@ -80,6 +83,7 @@ namespace NzbDrone.Core.Datastore MapRepository.Instance.RegisterTypeConverter(typeof(Enum), new EnumIntConverter()); MapRepository.Instance.RegisterTypeConverter(typeof(Quality), new QualityIntConverter()); MapRepository.Instance.RegisterTypeConverter(typeof(Dictionary), new EmbeddedDocumentConverter()); + MapRepository.Instance.RegisterTypeConverter(typeof(List), new EmbeddedDocumentConverter()); } private static void RegisterProviderSettingConverter() diff --git a/src/NzbDrone.Core/DecisionEngine/Specifications/BlacklistSpecification.cs b/src/NzbDrone.Core/DecisionEngine/Specifications/BlacklistSpecification.cs new file mode 100644 index 000000000..7aa5c6b32 --- /dev/null +++ b/src/NzbDrone.Core/DecisionEngine/Specifications/BlacklistSpecification.cs @@ -0,0 +1,48 @@ +using System.Linq; +using NLog; +using NzbDrone.Core.Blacklisting; +using NzbDrone.Core.Configuration; +using NzbDrone.Core.IndexerSearch.Definitions; +using NzbDrone.Core.Parser.Model; + +namespace NzbDrone.Core.DecisionEngine.Specifications +{ + public class BlacklistSpecification : IDecisionEngineSpecification + { + private readonly IBlacklistService _blacklistService; + private readonly IConfigService _configService; + private readonly Logger _logger; + + public BlacklistSpecification(IBlacklistService blacklistService, IConfigService configService, Logger logger) + { + _blacklistService = blacklistService; + _configService = configService; + _logger = logger; + } + + public string RejectionReason + { + get + { + return "Release is blacklisted"; + } + } + + public virtual bool IsSatisfiedBy(RemoteEpisode subject, SearchCriteriaBase searchCriteria) + { + if (!_configService.EnableFailedDownloadHandling) + { + _logger.Trace("Failed Download Handling is not enabled"); + return true; + } + + if (_blacklistService.Blacklisted(subject.Release.Title)) + { + _logger.Trace("{0} is blacklisted", subject.Release.Title); + return false; + } + + return true; + } + } +} diff --git a/src/NzbDrone.Core/DecisionEngine/Specifications/RssSync/UpgradeHistorySpecification.cs b/src/NzbDrone.Core/DecisionEngine/Specifications/RssSync/HistorySpecification.cs similarity index 54% rename from src/NzbDrone.Core/DecisionEngine/Specifications/RssSync/UpgradeHistorySpecification.cs rename to src/NzbDrone.Core/DecisionEngine/Specifications/RssSync/HistorySpecification.cs index e844cb91d..319b76ce5 100644 --- a/src/NzbDrone.Core/DecisionEngine/Specifications/RssSync/UpgradeHistorySpecification.cs +++ b/src/NzbDrone.Core/DecisionEngine/Specifications/RssSync/HistorySpecification.cs @@ -1,20 +1,28 @@ using NLog; +using NzbDrone.Core.Download; +using NzbDrone.Core.Download.Clients.Sabnzbd; using NzbDrone.Core.History; using NzbDrone.Core.IndexerSearch.Definitions; +using NzbDrone.Core.MetadataSource.Trakt; using NzbDrone.Core.Parser.Model; namespace NzbDrone.Core.DecisionEngine.Specifications.RssSync { - public class UpgradeHistorySpecification : IDecisionEngineSpecification + public class HistorySpecification : IDecisionEngineSpecification { private readonly IHistoryService _historyService; private readonly QualityUpgradableSpecification _qualityUpgradableSpecification; + private readonly IProvideDownloadClient _downloadClientProvider; private readonly Logger _logger; - public UpgradeHistorySpecification(IHistoryService historyService, QualityUpgradableSpecification qualityUpgradableSpecification, Logger logger) + public HistorySpecification(IHistoryService historyService, + QualityUpgradableSpecification qualityUpgradableSpecification, + IProvideDownloadClient downloadClientProvider, + Logger logger) { _historyService = historyService; _qualityUpgradableSpecification = qualityUpgradableSpecification; + _downloadClientProvider = downloadClientProvider; _logger = logger; } @@ -34,6 +42,22 @@ namespace NzbDrone.Core.DecisionEngine.Specifications.RssSync return true; } + if (_downloadClientProvider.GetDownloadClient().GetType() == typeof (SabnzbdClient)) + { + _logger.Trace("Performing history status check on report"); + foreach (var episode in subject.Episodes) + { + _logger.Trace("Checking current status of episode [{0}] in history", episode.Id); + var mostRecent = _historyService.MostRecentForEpisode(episode.Id); + + if (mostRecent != null && mostRecent.EventType == HistoryEventType.Grabbed) + { + return false; + } + } + return true; + } + foreach (var episode in subject.Episodes) { var bestQualityInHistory = _historyService.GetBestQualityInHistory(episode.Id); diff --git a/src/NzbDrone.Core/DecisionEngine/Specifications/Search/DailyEpisodeMatchSpecification.cs b/src/NzbDrone.Core/DecisionEngine/Specifications/Search/DailyEpisodeMatchSpecification.cs index daaf3146c..cee1ae288 100644 --- a/src/NzbDrone.Core/DecisionEngine/Specifications/Search/DailyEpisodeMatchSpecification.cs +++ b/src/NzbDrone.Core/DecisionEngine/Specifications/Search/DailyEpisodeMatchSpecification.cs @@ -34,9 +34,9 @@ namespace NzbDrone.Core.DecisionEngine.Specifications.Search if (dailySearchSpec == null) return true; - var episode = _episodeService.GetEpisode(dailySearchSpec.Series.Id, dailySearchSpec.Airtime); + var episode = _episodeService.GetEpisode(dailySearchSpec.Series.Id, dailySearchSpec.AirDate.ToString(Episode.AIR_DATE_FORMAT)); - if (!remoteEpisode.ParsedEpisodeInfo.AirDate.HasValue || remoteEpisode.ParsedEpisodeInfo.AirDate.Value.ToString(Episode.AIR_DATE_FORMAT) != episode.AirDate) + if (!remoteEpisode.ParsedEpisodeInfo.IsDaily() || remoteEpisode.ParsedEpisodeInfo.AirDate != episode.AirDate) { _logger.Trace("Episode AirDate does not match searched episode number, skipping."); return false; diff --git a/src/NzbDrone.Core/Download/Clients/BlackholeProvider.cs b/src/NzbDrone.Core/Download/Clients/BlackholeProvider.cs index 1598ee647..5f43ca351 100644 --- a/src/NzbDrone.Core/Download/Clients/BlackholeProvider.cs +++ b/src/NzbDrone.Core/Download/Clients/BlackholeProvider.cs @@ -1,4 +1,5 @@ -using System.Collections.Generic; +using System; +using System.Collections.Generic; using System.IO; using NLog; using NzbDrone.Common; @@ -22,7 +23,7 @@ namespace NzbDrone.Core.Download.Clients _logger = logger; } - public void DownloadNzb(RemoteEpisode remoteEpisode) + public string DownloadNzb(RemoteEpisode remoteEpisode) { var url = remoteEpisode.Release.DownloadUrl; var title = remoteEpisode.Release.Title; @@ -34,8 +35,9 @@ namespace NzbDrone.Core.Download.Clients _logger.Trace("Downloading NZB from: {0} to: {1}", url, filename); _httpProvider.DownloadFile(url, filename); - _logger.Trace("NZB Download succeeded, saved to: {0}", filename); + + return null; } public bool IsConfigured @@ -50,5 +52,18 @@ namespace NzbDrone.Core.Download.Clients { return new QueueItem[0]; } + + public IEnumerable GetHistory(int start = 0, int limit = 0) + { + return new HistoryItem[0]; + } + + public void RemoveFromQueue(string id) + { + } + + public void RemoveFromHistory(string id) + { + } } } diff --git a/src/NzbDrone.Core/Download/Clients/Nzbget/NzbgetClient.cs b/src/NzbDrone.Core/Download/Clients/Nzbget/NzbgetClient.cs index f3d692d32..66acf0f92 100644 --- a/src/NzbDrone.Core/Download/Clients/Nzbget/NzbgetClient.cs +++ b/src/NzbDrone.Core/Download/Clients/Nzbget/NzbgetClient.cs @@ -24,7 +24,7 @@ namespace NzbDrone.Core.Download.Clients.Nzbget _logger = logger; } - public void DownloadNzb(RemoteEpisode remoteEpisode) + public string DownloadNzb(RemoteEpisode remoteEpisode) { var url = remoteEpisode.Release.DownloadUrl; var title = remoteEpisode.Release.Title + ".nzb"; @@ -46,6 +46,7 @@ namespace NzbDrone.Core.Download.Clients.Nzbget var success = Json.Deserialize(response).Result; _logger.Debug("Queue Response: [{0}]", success); + return null; } public bool IsConfigured @@ -90,6 +91,21 @@ namespace NzbDrone.Core.Download.Clients.Nzbget } } + public IEnumerable GetHistory(int start = 0, int limit = 0) + { + return new HistoryItem[0]; + } + + public void RemoveFromQueue(string id) + { + throw new NotImplementedException(); + } + + public void RemoveFromHistory(string id) + { + throw new NotImplementedException(); + } + public virtual VersionModel GetVersion(string host = null, int port = 0, string username = null, string password = null) { //Get saved values if any of these are defaults diff --git a/src/NzbDrone.Core/Download/Clients/PneumaticClient.cs b/src/NzbDrone.Core/Download/Clients/PneumaticClient.cs index 537683243..f536965b2 100644 --- a/src/NzbDrone.Core/Download/Clients/PneumaticClient.cs +++ b/src/NzbDrone.Core/Download/Clients/PneumaticClient.cs @@ -26,7 +26,7 @@ namespace NzbDrone.Core.Download.Clients _diskProvider = diskProvider; } - public void DownloadNzb(RemoteEpisode remoteEpisode) + public string DownloadNzb(RemoteEpisode remoteEpisode) { var url = remoteEpisode.Release.DownloadUrl; var title = remoteEpisode.Release.Title; @@ -41,8 +41,6 @@ namespace NzbDrone.Core.Download.Clients //Save to the Pneumatic directory (The user will need to ensure its accessible by XBMC) var filename = Path.Combine(_configService.PneumaticFolder, title + ".nzb"); - - logger.Trace("Downloading NZB from: {0} to: {1}", url, filename); _httpProvider.DownloadFile(url, filename); @@ -50,6 +48,8 @@ namespace NzbDrone.Core.Download.Clients var contents = String.Format("plugin://plugin.program.pneumatic/?mode=strm&type=add_file&nzb={0}&nzbname={1}", filename, title); _diskProvider.WriteAllText(Path.Combine(_configService.DownloadedEpisodesFolder, title + ".strm"), contents); + + return null; } public bool IsConfigured @@ -65,6 +65,19 @@ namespace NzbDrone.Core.Download.Clients return new QueueItem[0]; } + public IEnumerable GetHistory(int start = 0, int limit = 0) + { + return new HistoryItem[0]; + } + + public void RemoveFromQueue(string id) + { + } + + public void RemoveFromHistory(string id) + { + } + public virtual bool IsInQueue(RemoteEpisode newEpisode) { return false; diff --git a/src/NzbDrone.Core/Download/Clients/Sabnzbd/SabCommunicationProxy.cs b/src/NzbDrone.Core/Download/Clients/Sabnzbd/SabCommunicationProxy.cs new file mode 100644 index 000000000..f1d348b17 --- /dev/null +++ b/src/NzbDrone.Core/Download/Clients/Sabnzbd/SabCommunicationProxy.cs @@ -0,0 +1,97 @@ +using System; +using System.IO; +using NzbDrone.Common.Serializer; +using NzbDrone.Core.Configuration; +using RestSharp; + +namespace NzbDrone.Core.Download.Clients.Sabnzbd +{ + public interface ISabCommunicationProxy + { + string DownloadNzb(Stream nzb, string name, string category, int priority); + void RemoveFrom(string source, string id); + string ProcessRequest(IRestRequest restRequest, string action); + } + + public class SabCommunicationProxy : ISabCommunicationProxy + { + private readonly IConfigService _configService; + + public SabCommunicationProxy(IConfigService configService) + { + _configService = configService; + } + + public string DownloadNzb(Stream nzb, string title, string category, int priority) + { + var request = new RestRequest(Method.POST); + var action = String.Format("mode=addfile&cat={0}&priority={1}", category, priority); + + request.AddFile("name", ReadFully(nzb), title, "application/x-nzb"); + + return ProcessRequest(request, action); + } + + public void RemoveFrom(string source, string id) + { + var request = new RestRequest(); + var action = String.Format("mode={0}&name=delete&del_files=1&value={1}", source, id); + + ProcessRequest(request, action); + } + + public string ProcessRequest(IRestRequest restRequest, string action) + { + var client = BuildClient(action); + var response = client.Execute(restRequest); + + CheckForError(response); + + return response.Content; + } + + private IRestClient BuildClient(string action) + { + var protocol = _configService.SabUseSsl ? "https" : "http"; + + var url = string.Format(@"{0}://{1}:{2}/api?{3}&apikey={4}&ma_username={5}&ma_password={6}&output=json", + protocol, + _configService.SabHost, + _configService.SabPort, + action, + _configService.SabApiKey, + _configService.SabUsername, + _configService.SabPassword); + + return new RestClient(url); + } + + private void CheckForError(IRestResponse response) + { + if (response.ResponseStatus != ResponseStatus.Completed) + { + throw new ApplicationException("Unable to connect to SABnzbd, please check your settings"); + } + + var result = Json.Deserialize(response.Content); + + if (result.Status != null && result.Status.Equals("false", StringComparison.InvariantCultureIgnoreCase)) + throw new ApplicationException(result.Error); + } + + //TODO: Find a better home for this + private byte[] ReadFully(Stream input) + { + byte[] buffer = new byte[16 * 1024]; + using (MemoryStream ms = new MemoryStream()) + { + int read; + while ((read = input.Read(buffer, 0, buffer.Length)) > 0) + { + ms.Write(buffer, 0, read); + } + return ms.ToArray(); + } + } + } +} diff --git a/src/NzbDrone.Core/Download/Clients/Sabnzbd/SabnzbdClient.cs b/src/NzbDrone.Core/Download/Clients/Sabnzbd/SabnzbdClient.cs index 4e1fabcfc..c5799f5ce 100644 --- a/src/NzbDrone.Core/Download/Clients/Sabnzbd/SabnzbdClient.cs +++ b/src/NzbDrone.Core/Download/Clients/Sabnzbd/SabnzbdClient.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Linq; using System.Web; using Newtonsoft.Json.Linq; using NLog; @@ -13,48 +14,12 @@ using RestSharp; namespace NzbDrone.Core.Download.Clients.Sabnzbd { - public class SabRequestBuilder - { - private readonly IConfigService _configService; - - public SabRequestBuilder(IConfigService configService) - { - _configService = configService; - } - - public IRestRequest AddToQueueRequest(RemoteEpisode remoteEpisode) - { - string cat = _configService.SabTvCategory; - int priority = (int)_configService.SabRecentTvPriority; - - string name = remoteEpisode.Release.DownloadUrl.Replace("&", "%26"); - string nzbName = HttpUtility.UrlEncode(remoteEpisode.Release.Title); - - string action = string.Format("mode=addurl&name={0}&priority={1}&pp=3&cat={2}&nzbname={3}&output=json", - name, priority, cat, nzbName); - - string request = GetSabRequest(action); - - return new RestRequest(request); - } - - private string GetSabRequest(string action) - { - return string.Format(@"http://{0}:{1}/api?{2}&apikey={3}&ma_username={4}&ma_password={5}", - _configService.SabHost, - _configService.SabPort, - action, - _configService.SabApiKey, - _configService.SabUsername, - _configService.SabPassword); - } - } - public class SabnzbdClient : IDownloadClient { private readonly IConfigService _configService; private readonly IHttpProvider _httpProvider; private readonly IParsingService _parsingService; + private readonly ISabCommunicationProxy _sabCommunicationProxy; private readonly ICached> _queueCache; private readonly Logger _logger; @@ -62,39 +27,17 @@ namespace NzbDrone.Core.Download.Clients.Sabnzbd IHttpProvider httpProvider, ICacheManger cacheManger, IParsingService parsingService, + ISabCommunicationProxy sabCommunicationProxy, Logger logger) { _configService = configService; _httpProvider = httpProvider; _parsingService = parsingService; + _sabCommunicationProxy = sabCommunicationProxy; _queueCache = cacheManger.GetCache>(GetType(), "queue"); _logger = logger; } - public void DownloadNzb(RemoteEpisode remoteEpisode) - { - var url = remoteEpisode.Release.DownloadUrl; - var title = remoteEpisode.Release.Title; - - string cat = _configService.SabTvCategory; - int priority = remoteEpisode.IsRecentEpisode() ? (int)_configService.SabRecentTvPriority : (int)_configService.SabOlderTvPriority; - - string name = url.Replace("&", "%26"); - string nzbName = HttpUtility.UrlEncode(title); - - string action = string.Format("mode=addurl&name={0}&priority={1}&pp=3&cat={2}&nzbname={3}&output=json", - name, priority, cat, nzbName); - - string request = GetSabRequest(action); - _logger.Info("Adding report [{0}] to the queue.", title); - - var response = _httpProvider.DownloadString(request); - - _logger.Debug("Queue Response: [{0}]", response); - - CheckForError(response); - } - public bool IsConfigured { get @@ -104,6 +47,24 @@ namespace NzbDrone.Core.Download.Clients.Sabnzbd } } + public string DownloadNzb(RemoteEpisode remoteEpisode) + { + var url = remoteEpisode.Release.DownloadUrl; + var title = remoteEpisode.Release.Title; + var category = _configService.SabTvCategory; + var priority = remoteEpisode.IsRecentEpisode() ? (int)_configService.SabRecentTvPriority : (int)_configService.SabOlderTvPriority; + + using (var nzb = _httpProvider.DownloadStream(url)) + { + _logger.Info("Adding report [{0}] to the queue.", title); + var response = Json.Deserialize(_sabCommunicationProxy.DownloadNzb(nzb, title, category, priority)); + + _logger.Debug("Queue Response: [{0}]", response.Status); + + return response.Ids.First(); + } + } + public IEnumerable GetQueue() { return _queueCache.Get("queue", () => @@ -128,7 +89,7 @@ namespace NzbDrone.Core.Download.Clients.Sabnzbd queueItem.Timeleft = sabQueueItem.Timeleft; queueItem.Status = sabQueueItem.Status; - var parsedEpisodeInfo = Parser.Parser.ParseTitle(queueItem.Title); + var parsedEpisodeInfo = Parser.Parser.ParseTitle(queueItem.Title.Replace("ENCRYPTED / ", "")); if (parsedEpisodeInfo == null) continue; var remoteEpisode = _parsingService.Map(parsedEpisodeInfo, 0); @@ -143,7 +104,7 @@ namespace NzbDrone.Core.Download.Clients.Sabnzbd }, TimeSpan.FromSeconds(10)); } - public virtual List GetHistory(int start = 0, int limit = 0) + public IEnumerable GetHistory(int start = 0, int limit = 0) { string action = String.Format("mode=history&output=json&start={0}&limit={1}", start, limit); string request = GetSabRequest(action); @@ -152,7 +113,34 @@ namespace NzbDrone.Core.Download.Clients.Sabnzbd CheckForError(response); var items = Json.Deserialize(JObject.Parse(response).SelectToken("history").ToString()).Items; - return items ?? new List(); + var historyItems = new List(); + + foreach (var sabHistoryItem in items) + { + var historyItem = new HistoryItem(); + historyItem.Id = sabHistoryItem.Id; + historyItem.Title = sabHistoryItem.Title; + historyItem.Size = sabHistoryItem.Size; + historyItem.DownloadTime = sabHistoryItem.DownloadTime; + historyItem.Storage = sabHistoryItem.Storage; + historyItem.Category = sabHistoryItem.Category; + historyItem.Message = sabHistoryItem.FailMessage; + historyItem.Status = sabHistoryItem.Status == "Failed" ? HistoryStatus.Failed : HistoryStatus.Completed; + + historyItems.Add(historyItem); + } + + return historyItems; + } + + public void RemoveFromQueue(string id) + { + _sabCommunicationProxy.RemoveFrom("queue", id); + } + + public void RemoveFromHistory(string id) + { + _sabCommunicationProxy.RemoveFrom("history", id); } public virtual SabCategoryModel GetCategories(string host = null, int port = 0, string apiKey = null, string username = null, string password = null) diff --git a/src/NzbDrone.Core/Download/DownloadFailedEvent.cs b/src/NzbDrone.Core/Download/DownloadFailedEvent.cs new file mode 100644 index 000000000..188ab24f9 --- /dev/null +++ b/src/NzbDrone.Core/Download/DownloadFailedEvent.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using NzbDrone.Common.Messaging; +using NzbDrone.Core.Tv; + +namespace NzbDrone.Core.Download +{ + public class DownloadFailedEvent : IEvent + { + public Int32 SeriesId { get; set; } + public List EpisodeIds { get; set; } + public QualityModel Quality { get; set; } + public String SourceTitle { get; set; } + public String DownloadClient { get; set; } + public String DownloadClientId { get; set; } + public String Message { get; set; } + } +} \ No newline at end of file diff --git a/src/NzbDrone.Core/Download/DownloadService.cs b/src/NzbDrone.Core/Download/DownloadService.cs index f41acdafa..05dfd4737 100644 --- a/src/NzbDrone.Core/Download/DownloadService.cs +++ b/src/NzbDrone.Core/Download/DownloadService.cs @@ -1,4 +1,5 @@ -using NLog; +using System; +using NLog; using NzbDrone.Common.EnsureThat; using NzbDrone.Core.Instrumentation; using NzbDrone.Core.Messaging.Events; @@ -40,10 +41,17 @@ namespace NzbDrone.Core.Download return; } - downloadClient.DownloadNzb(remoteEpisode); + var downloadClientId = downloadClient.DownloadNzb(remoteEpisode); + var episodeGrabbedEvent = new EpisodeGrabbedEvent(remoteEpisode); + + if (!String.IsNullOrWhiteSpace(downloadClientId)) + { + episodeGrabbedEvent.DownloadClient = downloadClient.GetType().Name; + episodeGrabbedEvent.DownloadClientId = downloadClientId; + } _logger.ProgressInfo("Report sent to download client. {0}", downloadTitle); - _eventAggregator.PublishEvent(new EpisodeGrabbedEvent(remoteEpisode)); + _eventAggregator.PublishEvent(episodeGrabbedEvent); } } } \ No newline at end of file diff --git a/src/NzbDrone.Core/Download/EpisodeGrabbedEvent.cs b/src/NzbDrone.Core/Download/EpisodeGrabbedEvent.cs index cd6fc46cc..a6a9f0b52 100644 --- a/src/NzbDrone.Core/Download/EpisodeGrabbedEvent.cs +++ b/src/NzbDrone.Core/Download/EpisodeGrabbedEvent.cs @@ -1,4 +1,5 @@ -using NzbDrone.Common.Messaging; +using System; +using NzbDrone.Common.Messaging; using NzbDrone.Core.Parser.Model; namespace NzbDrone.Core.Download @@ -6,6 +7,8 @@ namespace NzbDrone.Core.Download public class EpisodeGrabbedEvent : IEvent { public RemoteEpisode Episode { get; private set; } + public String DownloadClient { get; set; } + public String DownloadClientId { get; set; } public EpisodeGrabbedEvent(RemoteEpisode episode) { diff --git a/src/NzbDrone.Core/Download/FailedDownloadCommand.cs b/src/NzbDrone.Core/Download/FailedDownloadCommand.cs new file mode 100644 index 000000000..864921ba1 --- /dev/null +++ b/src/NzbDrone.Core/Download/FailedDownloadCommand.cs @@ -0,0 +1,9 @@ +using NzbDrone.Core.Messaging.Commands; + +namespace NzbDrone.Core.Download +{ + public class FailedDownloadCommand : Command + { + + } +} diff --git a/src/NzbDrone.Core/Download/FailedDownloadService.cs b/src/NzbDrone.Core/Download/FailedDownloadService.cs new file mode 100644 index 000000000..40048652a --- /dev/null +++ b/src/NzbDrone.Core/Download/FailedDownloadService.cs @@ -0,0 +1,171 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using NLog; +using NzbDrone.Core.Configuration; +using NzbDrone.Core.History; +using NzbDrone.Core.Messaging.Commands; +using NzbDrone.Core.Messaging.Events; + +namespace NzbDrone.Core.Download +{ + public interface IFailedDownloadService + { + void MarkAsFailed(int historyId); + } + + public class FailedDownloadService : IFailedDownloadService, IExecute + { + private readonly IProvideDownloadClient _downloadClientProvider; + private readonly IHistoryService _historyService; + private readonly IEventAggregator _eventAggregator; + private readonly IConfigService _configService; + private readonly Logger _logger; + + private readonly IDownloadClient _downloadClient; + + private static string DOWNLOAD_CLIENT = "downloadClient"; + private static string DOWNLOAD_CLIENT_ID = "downloadClientId"; + + public FailedDownloadService(IProvideDownloadClient downloadClientProvider, + IHistoryService historyService, + IEventAggregator eventAggregator, + IConfigService configService, + Logger logger) + { + _downloadClientProvider = downloadClientProvider; + _historyService = historyService; + _eventAggregator = eventAggregator; + _configService = configService; + _logger = logger; + + _downloadClient = _downloadClientProvider.GetDownloadClient(); + } + + public void MarkAsFailed(int historyId) + { + var item = _historyService.Get(historyId); + PublishDownloadFailedEvent(new List {item}, "Manually marked as failed"); + } + + private void CheckForFailedDownloads() + { + if (!_configService.EnableFailedDownloadHandling) + { + _logger.Trace("Failed Download Handling is not enabled"); + return; + } + + var grabbedHistory = _historyService.Grabbed(); + var failedHistory = _historyService.Failed(); + + CheckQueue(grabbedHistory, failedHistory); + CheckHistory(grabbedHistory, failedHistory); + } + + private void CheckQueue(List grabbedHistory, List failedHistory) + { + var downloadClientQueue = _downloadClient.GetQueue().ToList(); + var failedItems = downloadClientQueue.Where(q => q.Title.StartsWith("ENCRYPTED / ")).ToList(); + + if (!failedItems.Any()) + { + _logger.Trace("Yay! No encrypted downloads"); + return; + } + + foreach (var failedItem in failedItems) + { + var failedLocal = failedItem; + var historyItems = GetHistoryItems(grabbedHistory, failedLocal.Id); + + if (!historyItems.Any()) + { + _logger.Trace("Unable to find matching history item"); + continue; + } + + if (failedHistory.Any(h => h.Data.ContainsKey(DOWNLOAD_CLIENT_ID) && + h.Data[DOWNLOAD_CLIENT_ID].Equals(failedLocal.Id))) + { + _logger.Trace("Already added to history as failed"); + continue; + } + + PublishDownloadFailedEvent(historyItems, "Encypted download detected"); + + if (_configService.RemoveFailedDownloads) + { + _logger.Info("Removing encrypted download from queue: {0}", failedItem.Title.Replace("ENCRYPTED / ", "")); + _downloadClient.RemoveFromQueue(failedItem.Id); + } + } + } + + private void CheckHistory(List grabbedHistory, List failedHistory) + { + var downloadClientHistory = _downloadClient.GetHistory(0, 20).ToList(); + var failedItems = downloadClientHistory.Where(h => h.Status == HistoryStatus.Failed).ToList(); + + if (!failedItems.Any()) + { + _logger.Trace("Yay! No failed downloads"); + return; + } + + foreach (var failedItem in failedItems) + { + var failedLocal = failedItem; + var historyItems = GetHistoryItems(grabbedHistory, failedLocal.Id); + + if (!historyItems.Any()) + { + _logger.Trace("Unable to find matching history item"); + continue; + } + + if (failedHistory.Any(h => h.Data.ContainsKey(DOWNLOAD_CLIENT_ID) && + h.Data[DOWNLOAD_CLIENT_ID].Equals(failedLocal.Id))) + { + _logger.Trace("Already added to history as failed"); + continue; + } + + PublishDownloadFailedEvent(historyItems, failedItem.Message); + + if (_configService.RemoveFailedDownloads) + { + _logger.Info("Removing failed download from history: {0}", failedItem.Title); + _downloadClient.RemoveFromHistory(failedItem.Id); + } + } + } + + private List GetHistoryItems(List grabbedHistory, string downloadClientId) + { + return grabbedHistory.Where(h => h.Data.ContainsKey(DOWNLOAD_CLIENT) && + h.Data[DOWNLOAD_CLIENT_ID].Equals(downloadClientId)) + .ToList(); + } + + private void PublishDownloadFailedEvent(List historyItems, string message) + { + var historyItem = historyItems.First(); + _eventAggregator.PublishEvent(new DownloadFailedEvent + { + SeriesId = historyItem.SeriesId, + EpisodeIds = historyItems.Select(h => h.EpisodeId).ToList(), + Quality = historyItem.Quality, + SourceTitle = historyItem.SourceTitle, + DownloadClient = historyItem.Data[DOWNLOAD_CLIENT], + DownloadClientId = historyItem.Data[DOWNLOAD_CLIENT_ID], + Message = message + }); + } + + public void Execute(FailedDownloadCommand message) + { + CheckForFailedDownloads(); + } + } +} diff --git a/src/NzbDrone.Core/Download/HistoryItem.cs b/src/NzbDrone.Core/Download/HistoryItem.cs new file mode 100644 index 000000000..1dd969f29 --- /dev/null +++ b/src/NzbDrone.Core/Download/HistoryItem.cs @@ -0,0 +1,23 @@ +using System; +using NzbDrone.Core.Parser.Model; + +namespace NzbDrone.Core.Download +{ + public class HistoryItem + { + public String Id { get; set; } + public String Title { get; set; } + public String Size { get; set; } + public String Category { get; set; } + public Int32 DownloadTime { get; set; } + public String Storage { get; set; } + public String Message { get; set; } + public HistoryStatus Status { get; set; } + } + + public enum HistoryStatus + { + Completed = 0, + Failed = 1 + } +} diff --git a/src/NzbDrone.Core/Download/IDownloadClient.cs b/src/NzbDrone.Core/Download/IDownloadClient.cs index ce32b62b2..42107372b 100644 --- a/src/NzbDrone.Core/Download/IDownloadClient.cs +++ b/src/NzbDrone.Core/Download/IDownloadClient.cs @@ -5,8 +5,11 @@ namespace NzbDrone.Core.Download { public interface IDownloadClient { - void DownloadNzb(RemoteEpisode remoteEpisode); + string DownloadNzb(RemoteEpisode remoteEpisode); bool IsConfigured { get; } IEnumerable GetQueue(); + IEnumerable GetHistory(int start = 0, int limit = 0); + void RemoveFromQueue(string id); + void RemoveFromHistory(string id); } } diff --git a/src/NzbDrone.Core/Download/RedownloadFailedDownloadService.cs b/src/NzbDrone.Core/Download/RedownloadFailedDownloadService.cs new file mode 100644 index 000000000..dd40220c9 --- /dev/null +++ b/src/NzbDrone.Core/Download/RedownloadFailedDownloadService.cs @@ -0,0 +1,76 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using NLog; +using NzbDrone.Core.Configuration; +using NzbDrone.Core.IndexerSearch; +using NzbDrone.Core.Messaging.Commands; +using NzbDrone.Core.Tv; + +namespace NzbDrone.Core.Download +{ + public interface IRedownloadFailedDownloads + { + void Redownload(int seriesId, List episodeIds); + } + + public class RedownloadFailedDownloadService : IRedownloadFailedDownloads + { + private readonly IConfigService _configService; + private readonly IEpisodeService _episodeService; + private readonly ICommandExecutor _commandExecutor; + private readonly Logger _logger; + + public RedownloadFailedDownloadService(IConfigService configService, IEpisodeService episodeService, ICommandExecutor commandExecutor, Logger logger) + { + _configService = configService; + _episodeService = episodeService; + _commandExecutor = commandExecutor; + _logger = logger; + } + + public void Redownload(int seriesId, List episodeIds) + { + if (!_configService.AutoRedownloadFailed) + { + _logger.Trace("Auto redownloading failed episodes is disabled"); + return; + } + + if (episodeIds.Count == 1) + { + _logger.Trace("Failed download only contains one episode, searching again"); + + _commandExecutor.PublishCommandAsync(new EpisodeSearchCommand + { + EpisodeIds = episodeIds.ToList() + }); + + return; + } + + var seasonNumber = _episodeService.GetEpisode(episodeIds.First()).SeasonNumber; + var episodesInSeason = _episodeService.GetEpisodesBySeason(seriesId, seasonNumber); + + if (episodeIds.Count == episodesInSeason.Count) + { + _logger.Trace("Failed download was entire season, searching again"); + + _commandExecutor.PublishCommandAsync(new SeasonSearchCommand + { + SeriesId = seriesId, + SeasonNumber = seasonNumber + }); + + return; + } + + _logger.Trace("Failed download contains multiple episodes, probably a double episode, searching again"); + + _commandExecutor.PublishCommandAsync(new EpisodeSearchCommand + { + EpisodeIds = episodeIds.ToList() + }); + } + } +} diff --git a/src/NzbDrone.Core/History/History.cs b/src/NzbDrone.Core/History/History.cs index 886ae9c4e..94b345e59 100644 --- a/src/NzbDrone.Core/History/History.cs +++ b/src/NzbDrone.Core/History/History.cs @@ -17,22 +17,18 @@ namespace NzbDrone.Core.History public string SourceTitle { get; set; } public QualityModel Quality { get; set; } public DateTime Date { get; set; } - public Episode Episode { get; set; } public Series Series { get; set; } - public HistoryEventType EventType { get; set; } - public Dictionary Data { get; set; } } - public enum HistoryEventType { Unknown = 0, Grabbed = 1, SeriesFolderImported = 2, - DownloadFolderImported = 3 + DownloadFolderImported = 3, + DownloadFailed = 4 } - } \ No newline at end of file diff --git a/src/NzbDrone.Core/History/HistoryRepository.cs b/src/NzbDrone.Core/History/HistoryRepository.cs index 5a6cf5244..59d54c745 100644 --- a/src/NzbDrone.Core/History/HistoryRepository.cs +++ b/src/NzbDrone.Core/History/HistoryRepository.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Linq; -using System.Linq.Expressions; using Marr.Data.QGen; using NzbDrone.Core.Datastore; using NzbDrone.Core.Messaging.Events; @@ -13,6 +12,10 @@ namespace NzbDrone.Core.History { void Trim(); List GetBestQualityInHistory(int episodeId); + List BetweenDates(DateTime startDate, DateTime endDate, HistoryEventType eventType); + List Failed(); + List Grabbed(); + History MostRecentForEpisode(int episodeId); } public class HistoryRepository : BasicRepository, IHistoryRepository @@ -38,6 +41,32 @@ namespace NzbDrone.Core.History 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 History MostRecentForEpisode(int episodeId) + { + return Query.Where(h => h.EpisodeId == episodeId) + .OrderByDescending(h => h.Date) + .FirstOrDefault(); + } + public override PagingSpec GetPaged(PagingSpec pagingSpec) { pagingSpec.Records = GetPagedQuery(pagingSpec).ToList(); diff --git a/src/NzbDrone.Core/History/HistoryService.cs b/src/NzbDrone.Core/History/HistoryService.cs index ed09ae94e..7fbb737af 100644 --- a/src/NzbDrone.Core/History/HistoryService.cs +++ b/src/NzbDrone.Core/History/HistoryService.cs @@ -18,9 +18,14 @@ namespace NzbDrone.Core.History void Trim(); QualityModel GetBestQualityInHistory(int episodeId); PagingSpec Paged(PagingSpec pagingSpec); + List BetweenDates(DateTime startDate, DateTime endDate, HistoryEventType eventType); + List Failed(); + List Grabbed(); + History MostRecentForEpisode(int episodeId); + History Get(int id); } - public class HistoryService : IHistoryService, IHandle, IHandle + public class HistoryService : IHistoryService, IHandle, IHandle, IHandle { private readonly IHistoryRepository _historyRepository; private readonly Logger _logger; @@ -41,6 +46,31 @@ namespace NzbDrone.Core.History return _historyRepository.GetPaged(pagingSpec); } + public List BetweenDates(DateTime startDate, DateTime endDate, HistoryEventType eventType) + { + return _historyRepository.BetweenDates(startDate, endDate, eventType); + } + + public List Failed() + { + return _historyRepository.Failed(); + } + + public List Grabbed() + { + return _historyRepository.Grabbed(); + } + + public History MostRecentForEpisode(int episodeId) + { + return _historyRepository.MostRecentForEpisode(episodeId); + } + + public History Get(int id) + { + return _historyRepository.Get(id); + } + public void Purge() { _historyRepository.Purge(); @@ -51,7 +81,7 @@ namespace NzbDrone.Core.History _historyRepository.Trim(); } - public virtual QualityModel GetBestQualityInHistory(int episodeId) + public QualityModel GetBestQualityInHistory(int episodeId) { return _historyRepository.GetBestQualityInHistory(episodeId).OrderByDescending(q => q).FirstOrDefault(); } @@ -75,19 +105,25 @@ namespace NzbDrone.Core.History history.Data.Add("ReleaseGroup", message.Episode.Release.ReleaseGroup); history.Data.Add("Age", message.Episode.Release.Age.ToString()); + if (!String.IsNullOrWhiteSpace(message.DownloadClientId)) + { + history.Data.Add("DownloadClient", message.DownloadClient); + history.Data.Add("DownloadClientId", message.DownloadClientId); + } + _historyRepository.Insert(history); } } public void Handle(EpisodeImportedEvent message) { - foreach (var episode in message.DroppedEpisode.Episodes) + foreach (var episode in message.EpisodeInfo.Episodes) { var history = new History { EventType = HistoryEventType.DownloadFolderImported, Date = DateTime.UtcNow, - Quality = message.DroppedEpisode.Quality, + Quality = message.EpisodeInfo.Quality, SourceTitle = message.ImportedEpisode.SceneName, SeriesId = message.ImportedEpisode.SeriesId, EpisodeId = episode.Id @@ -95,11 +131,33 @@ namespace NzbDrone.Core.History //Won't have a value since we publish this event before saving to DB. //history.Data.Add("FileId", message.ImportedEpisode.Id.ToString()); - history.Data.Add("DroppedPath", message.DroppedEpisode.Path); + history.Data.Add("DroppedPath", message.EpisodeInfo.Path); history.Data.Add("ImportedPath", message.ImportedEpisode.Path); _historyRepository.Insert(history); } } + + public void Handle(DownloadFailedEvent message) + { + foreach (var episodeId in message.EpisodeIds) + { + var history = new History + { + EventType = HistoryEventType.DownloadFailed, + Date = DateTime.UtcNow, + Quality = message.Quality, + SourceTitle = message.SourceTitle, + SeriesId = message.SeriesId, + EpisodeId = episodeId, + }; + + history.Data.Add("DownloadClient", message.DownloadClient); + history.Data.Add("DownloadClientId", message.DownloadClientId); + history.Data.Add("Message", message.Message); + + _historyRepository.Insert(history); + } + } } } \ No newline at end of file diff --git a/src/NzbDrone.Core/IndexerSearch/Definitions/DailyEpisodeSearchCriteria.cs b/src/NzbDrone.Core/IndexerSearch/Definitions/DailyEpisodeSearchCriteria.cs index 72d7fb195..3ffba7578 100644 --- a/src/NzbDrone.Core/IndexerSearch/Definitions/DailyEpisodeSearchCriteria.cs +++ b/src/NzbDrone.Core/IndexerSearch/Definitions/DailyEpisodeSearchCriteria.cs @@ -4,11 +4,11 @@ namespace NzbDrone.Core.IndexerSearch.Definitions { public class DailyEpisodeSearchCriteria : SearchCriteriaBase { - public DateTime Airtime { get; set; } + public DateTime AirDate { get; set; } public override string ToString() { - return string.Format("[{0} : {1}", SceneTitle, Airtime); + return string.Format("[{0} : {1}", SceneTitle, AirDate); } } } \ No newline at end of file diff --git a/src/NzbDrone.Core/IndexerSearch/NzbSearchService.cs b/src/NzbDrone.Core/IndexerSearch/NzbSearchService.cs index 96b52e8cf..0981c5eb9 100644 --- a/src/NzbDrone.Core/IndexerSearch/NzbSearchService.cs +++ b/src/NzbDrone.Core/IndexerSearch/NzbSearchService.cs @@ -98,7 +98,7 @@ namespace NzbDrone.Core.IndexerSearch { var airDate = DateTime.ParseExact(episode.AirDate, Episode.AIR_DATE_FORMAT, CultureInfo.InvariantCulture); var searchSpec = Get(series, new List{ episode }); - searchSpec.Airtime = airDate; + searchSpec.AirDate = airDate; return Dispatch(indexer => _feedFetcher.Fetch(indexer, searchSpec), searchSpec); } diff --git a/src/NzbDrone.Core/IndexerSearch/SearchAndDownloadService.cs b/src/NzbDrone.Core/IndexerSearch/SearchAndDownloadService.cs deleted file mode 100644 index d15c9c63c..000000000 --- a/src/NzbDrone.Core/IndexerSearch/SearchAndDownloadService.cs +++ /dev/null @@ -1,39 +0,0 @@ -using System; - -namespace NzbDrone.Core.IndexerSearch -{ - - interface ISearchAndDownload - { - void SearchSingle(int seriesId, int seasonNumber, int episodeNumber); - void SearchDaily(int seriesId, DateTime airDate); - void SearchSeason(int seriesId, int seasonNumber); - } - - /* public class SearchAndDownloadService : ISearchAndDownload - { - private readonly ISearchForNzb _searchService; - private readonly IMakeDownloadDecision _downloadDecisionMaker; - - public SearchAndDownloadService(ISearchForNzb searchService, IMakeDownloadDecision downloadDecisionMaker) - { - _searchService = searchService; - _downloadDecisionMaker = downloadDecisionMaker; - } - - public void FetchSearchSingle(int seriesId, int seasonNumber, int episodeNumber) - { - var result = _searchService.SearchSingle(seriesId, seasonNumber, episodeNumber); - } - - public void SearchDaily(int seriesId, DateTime airDate) - { - throw new NotImplementedException(); - } - - public void SearchSeason(int seriesId, int seasonNumber) - { - throw new NotImplementedException(); - } - }*/ -} \ No newline at end of file diff --git a/src/NzbDrone.Core/Indexers/IndexerFetchService.cs b/src/NzbDrone.Core/Indexers/IndexerFetchService.cs index b571f6466..2de0c51b0 100644 --- a/src/NzbDrone.Core/Indexers/IndexerFetchService.cs +++ b/src/NzbDrone.Core/Indexers/IndexerFetchService.cs @@ -87,7 +87,7 @@ namespace NzbDrone.Core.Indexers { _logger.Debug("Searching for {0}", searchCriteria); - var searchUrls = indexer.GetDailyEpisodeSearchUrls(searchCriteria.QueryTitle, searchCriteria.Series.TvRageId, searchCriteria.Airtime); + var searchUrls = indexer.GetDailyEpisodeSearchUrls(searchCriteria.QueryTitle, searchCriteria.Series.TvRageId, searchCriteria.AirDate); var result = Fetch(indexer, searchUrls); _logger.Info("Finished searching {0} for {1}. Found {2}", indexer, searchCriteria, result.Count); diff --git a/src/NzbDrone.Core/Jobs/TaskManager.cs b/src/NzbDrone.Core/Jobs/TaskManager.cs index e2bc22da2..c7d28b727 100644 --- a/src/NzbDrone.Core/Jobs/TaskManager.cs +++ b/src/NzbDrone.Core/Jobs/TaskManager.cs @@ -7,6 +7,7 @@ using NzbDrone.Core.Configuration.Events; using NzbDrone.Core.DataAugmentation; using NzbDrone.Core.DataAugmentation.Scene; using NzbDrone.Core.DataAugmentation.Xem; +using NzbDrone.Core.Download; using NzbDrone.Core.Housekeeping; using NzbDrone.Core.Indexers; using NzbDrone.Core.Instrumentation.Commands; @@ -54,7 +55,8 @@ namespace NzbDrone.Core.Jobs new ScheduledTask{ Interval = 1*60, TypeName = typeof(TrimLogCommand).FullName}, new ScheduledTask{ Interval = 3*60, TypeName = typeof(UpdateSceneMappingCommand).FullName}, new ScheduledTask{ Interval = 1, TypeName = typeof(TrackedCommandCleanupCommand).FullName}, - new ScheduledTask{ Interval = 24*60, TypeName = typeof(HousekeepingCommand).FullName} + new ScheduledTask{ Interval = 24*60, TypeName = typeof(HousekeepingCommand).FullName}, + new ScheduledTask{ Interval = 1, TypeName = typeof(FailedDownloadCommand).FullName} }; var currentTasks = _scheduledTaskRepository.All(); diff --git a/src/NzbDrone.Core/MediaFiles/DownloadedEpisodesImportService.cs b/src/NzbDrone.Core/MediaFiles/DownloadedEpisodesImportService.cs index 5f36b5910..4cb226005 100644 --- a/src/NzbDrone.Core/MediaFiles/DownloadedEpisodesImportService.cs +++ b/src/NzbDrone.Core/MediaFiles/DownloadedEpisodesImportService.cs @@ -7,7 +7,6 @@ using NzbDrone.Common; using NzbDrone.Core.Configuration; using NzbDrone.Core.MediaFiles.Commands; using NzbDrone.Core.MediaFiles.EpisodeImport; -using NzbDrone.Core.MediaFiles.EpisodeImport.Specifications; using NzbDrone.Core.Messaging.Commands; using NzbDrone.Core.Parser; using NzbDrone.Core.Tv; @@ -74,10 +73,7 @@ namespace NzbDrone.Core.MediaFiles if (importedFiles.Any()) { - if (_diskProvider.GetFolderSize(subFolder) < NotSampleSpecification.SampleSizeLimit) - { - _diskProvider.DeleteFolder(subFolder, true); - } + _diskProvider.DeleteFolder(subFolder, true); } } catch (Exception e) diff --git a/src/NzbDrone.Core/MediaFiles/EpisodeFileMovingService.cs b/src/NzbDrone.Core/MediaFiles/EpisodeFileMovingService.cs index e4e58c6ed..43c018656 100644 --- a/src/NzbDrone.Core/MediaFiles/EpisodeFileMovingService.cs +++ b/src/NzbDrone.Core/MediaFiles/EpisodeFileMovingService.cs @@ -1,8 +1,10 @@ using System; using System.IO; using System.Linq; +using Growl.Connector; using NLog; using NzbDrone.Common; +using NzbDrone.Common.EnvironmentInfo; using NzbDrone.Core.Messaging.Events; using NzbDrone.Core.Organizer; using NzbDrone.Core.Parser.Model; @@ -73,26 +75,38 @@ namespace NzbDrone.Core.MediaFiles _logger.Debug("Moving [{0}] > [{1}]", episodeFile.Path, destinationFilename); _diskProvider.MoveFile(episodeFile.Path, destinationFilename); - _logger.Trace("Setting last write time on series folder: {0}", series.Path); - _diskProvider.SetFolderWriteTime(series.Path, episodeFile.DateAdded); - - if (series.SeasonFolder) + try { - var seasonFolder = Path.GetDirectoryName(destinationFilename); + _logger.Trace("Setting last write time on series folder: {0}", series.Path); + _diskProvider.SetFolderWriteTime(series.Path, episodeFile.DateAdded); + + if (series.SeasonFolder) + { + var seasonFolder = Path.GetDirectoryName(destinationFilename); - _logger.Trace("Setting last write time on season folder: {0}", seasonFolder); - _diskProvider.SetFolderWriteTime(seasonFolder, episodeFile.DateAdded); + _logger.Trace("Setting last write time on season folder: {0}", seasonFolder); + _diskProvider.SetFolderWriteTime(seasonFolder, episodeFile.DateAdded); + } } - //Wrapped in Try/Catch to prevent this from causing issues with remote NAS boxes, the move worked, which is more important. - try + catch (Exception ex) { - _diskProvider.InheritFolderPermissions(destinationFilename); + _logger.WarnException("Unable to set last write time", ex); } - catch (UnauthorizedAccessException ex) + + //We should only run this on Windows + if (OsInfo.IsWindows) { - _logger.Debug("Unable to apply folder permissions to: ", destinationFilename); - _logger.TraceException(ex.Message, ex); + //Wrapped in Try/Catch to prevent this from causing issues with remote NAS boxes, the move worked, which is more important. + try + { + _diskProvider.InheritFolderPermissions(destinationFilename); + } + catch (UnauthorizedAccessException ex) + { + _logger.Debug("Unable to apply folder permissions to: ", destinationFilename); + _logger.TraceException(ex.Message, ex); + } } } } diff --git a/src/NzbDrone.Core/MediaFiles/EpisodeImport/ImportApprovedEpisodes.cs b/src/NzbDrone.Core/MediaFiles/EpisodeImport/ImportApprovedEpisodes.cs index 86d10675e..ce14d7054 100644 --- a/src/NzbDrone.Core/MediaFiles/EpisodeImport/ImportApprovedEpisodes.cs +++ b/src/NzbDrone.Core/MediaFiles/EpisodeImport/ImportApprovedEpisodes.cs @@ -41,7 +41,7 @@ namespace NzbDrone.Core.MediaFiles.EpisodeImport var qualifiedImports = GetQualifiedImports(decisions); var imported = new List(); - foreach (var importDecision in qualifiedImports) + foreach (var importDecision in qualifiedImports.OrderByDescending(e => e.LocalEpisode.Size)) { var localEpisode = importDecision.LocalEpisode; diff --git a/src/NzbDrone.Core/MediaFiles/EpisodeImport/Specifications/NotSampleSpecification.cs b/src/NzbDrone.Core/MediaFiles/EpisodeImport/Specifications/NotSampleSpecification.cs index dba6cf400..ccf833ce7 100644 --- a/src/NzbDrone.Core/MediaFiles/EpisodeImport/Specifications/NotSampleSpecification.cs +++ b/src/NzbDrone.Core/MediaFiles/EpisodeImport/Specifications/NotSampleSpecification.cs @@ -1,8 +1,11 @@ using System; +using System.Collections.Generic; using System.IO; using NLog; +using NzbDrone.Common.EnvironmentInfo; using NzbDrone.Core.MediaFiles.MediaInfo; using NzbDrone.Core.Parser.Model; +using NzbDrone.Core.Qualities; using NzbDrone.Core.Tv; namespace NzbDrone.Core.MediaFiles.EpisodeImport.Specifications @@ -11,6 +14,7 @@ namespace NzbDrone.Core.MediaFiles.EpisodeImport.Specifications { private readonly IVideoFileInfoReader _videoFileInfoReader; private readonly Logger _logger; + private static List _largeSampleSizeQualities = new List { Quality.HDTV1080p, Quality.WEBDL1080p, Quality.Bluray1080p }; public NotSampleSpecification(IVideoFileInfoReader videoFileInfoReader, Logger logger) @@ -31,6 +35,12 @@ namespace NzbDrone.Core.MediaFiles.EpisodeImport.Specifications public bool IsSatisfiedBy(LocalEpisode localEpisode) { + if (localEpisode.ExistingFile) + { + _logger.Trace("Existing file, skipping sample check"); + return true; + } + if (localEpisode.Series.SeriesType == SeriesTypes.Daily) { _logger.Trace("Daily Series, skipping sample check"); @@ -43,28 +53,49 @@ namespace NzbDrone.Core.MediaFiles.EpisodeImport.Specifications return true; } - if (Path.GetExtension(localEpisode.Path).Equals(".flv", StringComparison.InvariantCultureIgnoreCase)) + var extension = Path.GetExtension(localEpisode.Path); + + if (extension != null && extension.Equals(".flv", StringComparison.InvariantCultureIgnoreCase)) { - _logger.Trace("Skipping smaple check for .flv file"); + _logger.Trace("Skipping sample check for .flv file"); return true; } - if (localEpisode.Size > SampleSizeLimit) + if (OsInfo.IsWindows) { + var runTime = _videoFileInfoReader.GetRunTime(localEpisode.Path); + + if (runTime.TotalMinutes.Equals(0)) + { + _logger.Error("[{0}] has a runtime of 0, is it a valid video file?", localEpisode); + return false; + } + + if (runTime.TotalSeconds < 90) + { + _logger.Trace("[{0}] appears to be a sample. Size: {1} Runtime: {2}", localEpisode.Path, localEpisode.Size, runTime); + return false; + } + + _logger.Trace("Runtime is over 2 minutes, skipping file size check"); return true; } - var runTime = _videoFileInfoReader.GetRunTime(localEpisode.Path); + return CheckSize(localEpisode); + } - if (runTime.TotalMinutes.Equals(0)) + private bool CheckSize(LocalEpisode localEpisode) + { + if (_largeSampleSizeQualities.Contains(localEpisode.Quality.Quality)) { - _logger.Error("[{0}] has a runtime of 0, is it a valid video file?", localEpisode); - return false; + if (localEpisode.Size < SampleSizeLimit * 2) + { + return false; + } } - if (runTime.TotalMinutes < 3) + if (localEpisode.Size < SampleSizeLimit) { - _logger.Trace("[{0}] appears to be a sample. Size: {1} Runtime: {2}", localEpisode.Path, localEpisode.Size, runTime); return false; } diff --git a/src/NzbDrone.Core/MediaFiles/EpisodeImport/Specifications/NotUnpackingSpecification.cs b/src/NzbDrone.Core/MediaFiles/EpisodeImport/Specifications/NotUnpackingSpecification.cs index b8212e12c..2445e0701 100644 --- a/src/NzbDrone.Core/MediaFiles/EpisodeImport/Specifications/NotUnpackingSpecification.cs +++ b/src/NzbDrone.Core/MediaFiles/EpisodeImport/Specifications/NotUnpackingSpecification.cs @@ -2,6 +2,7 @@ using System.IO; using NLog; using NzbDrone.Common; +using NzbDrone.Common.EnvironmentInfo; using NzbDrone.Core.Configuration; using NzbDrone.Core.Parser.Model; @@ -34,6 +35,12 @@ namespace NzbDrone.Core.MediaFiles.EpisodeImport.Specifications { if (Directory.GetParent(localEpisode.Path).Name.StartsWith(workingFolder)) { + if (OsInfo.IsLinux) + { + _logger.Trace("{0} is still being unpacked", localEpisode.Path); + return false; + } + if (_diskProvider.GetLastFileWrite(localEpisode.Path) > DateTime.UtcNow.AddMinutes(-5)) { _logger.Trace("{0} appears to be unpacking still", localEpisode.Path); diff --git a/src/NzbDrone.Core/MediaFiles/Events/EpisodeImportedEvent.cs b/src/NzbDrone.Core/MediaFiles/Events/EpisodeImportedEvent.cs index 2f166b069..38db811a6 100644 --- a/src/NzbDrone.Core/MediaFiles/Events/EpisodeImportedEvent.cs +++ b/src/NzbDrone.Core/MediaFiles/Events/EpisodeImportedEvent.cs @@ -5,12 +5,12 @@ namespace NzbDrone.Core.MediaFiles.Events { public class EpisodeImportedEvent : IEvent { - public LocalEpisode DroppedEpisode { get; private set; } + public LocalEpisode EpisodeInfo { get; private set; } public EpisodeFile ImportedEpisode { get; private set; } - public EpisodeImportedEvent(LocalEpisode droppedEpisode, EpisodeFile importedEpisode) + public EpisodeImportedEvent(LocalEpisode episodeInfo, EpisodeFile importedEpisode) { - DroppedEpisode = droppedEpisode; + EpisodeInfo = episodeInfo; ImportedEpisode = importedEpisode; } } diff --git a/src/NzbDrone.Core/NzbDrone.Core.csproj b/src/NzbDrone.Core/NzbDrone.Core.csproj index 5c25f088e..9007ad74e 100644 --- a/src/NzbDrone.Core/NzbDrone.Core.csproj +++ b/src/NzbDrone.Core/NzbDrone.Core.csproj @@ -119,6 +119,9 @@ Properties\SharedAssemblyInfo.cs + + + @@ -181,6 +184,7 @@ Code + @@ -200,6 +204,7 @@ + @@ -218,17 +223,23 @@ - + + + + + + + @@ -307,6 +318,8 @@ + + @@ -347,7 +360,6 @@ - @@ -570,6 +582,7 @@ + @@ -625,7 +638,6 @@ - diff --git a/src/NzbDrone.Core/Parser/InvalidDateException.cs b/src/NzbDrone.Core/Parser/InvalidDateException.cs new file mode 100644 index 000000000..dfc509295 --- /dev/null +++ b/src/NzbDrone.Core/Parser/InvalidDateException.cs @@ -0,0 +1,19 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using NzbDrone.Common.Exceptions; + +namespace NzbDrone.Core.Parser +{ + public class InvalidDateException : NzbDroneException + { + public InvalidDateException(string message, params object[] args) : base(message, args) + { + } + + public InvalidDateException(string message) : base(message) + { + } + } +} diff --git a/src/NzbDrone.Core/Parser/Model/ParsedEpisodeInfo.cs b/src/NzbDrone.Core/Parser/Model/ParsedEpisodeInfo.cs index 492248882..14fd53a80 100644 --- a/src/NzbDrone.Core/Parser/Model/ParsedEpisodeInfo.cs +++ b/src/NzbDrone.Core/Parser/Model/ParsedEpisodeInfo.cs @@ -7,10 +7,11 @@ namespace NzbDrone.Core.Parser.Model public class ParsedEpisodeInfo { public string SeriesTitle { get; set; } + public SeriesTitleInfo SeriesTitleInfo { get; set; } public QualityModel Quality { get; set; } public int SeasonNumber { get; set; } public int[] EpisodeNumbers { get; set; } - public DateTime? AirDate { get; set; } + public String AirDate { get; set; } public Language Language { get; set; } public bool FullSeason { get; set; } @@ -19,9 +20,9 @@ namespace NzbDrone.Core.Parser.Model { string episodeString = "[Unknown Episode]"; - if (AirDate != null && EpisodeNumbers == null) + if (IsDaily() && EpisodeNumbers == null) { - episodeString = string.Format("{0}", AirDate.Value.ToString("yyyy-MM-dd")); + episodeString = string.Format("{0}", AirDate); } else if (FullSeason) { @@ -34,5 +35,10 @@ namespace NzbDrone.Core.Parser.Model return string.Format("{0} - {1} {2}", SeriesTitle, episodeString, Quality); } + + public bool IsDaily() + { + return !String.IsNullOrWhiteSpace(AirDate); + } } } \ No newline at end of file diff --git a/src/NzbDrone.Core/Parser/Model/SeriesTitleInfo.cs b/src/NzbDrone.Core/Parser/Model/SeriesTitleInfo.cs new file mode 100644 index 000000000..5ced83c40 --- /dev/null +++ b/src/NzbDrone.Core/Parser/Model/SeriesTitleInfo.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace NzbDrone.Core.Parser.Model +{ + public class SeriesTitleInfo + { + public string Title { get; set; } + public string TitleWithoutYear { get; set; } + public int Year { get; set; } + } +} diff --git a/src/NzbDrone.Core/Parser/Parser.cs b/src/NzbDrone.Core/Parser/Parser.cs index 85ef1be7c..9122245ab 100644 --- a/src/NzbDrone.Core/Parser/Parser.cs +++ b/src/NzbDrone.Core/Parser/Parser.cs @@ -6,6 +6,7 @@ using System.Text.RegularExpressions; using NLog; using NzbDrone.Common.Instrumentation; using NzbDrone.Core.Parser.Model; +using NzbDrone.Core.Tv; namespace NzbDrone.Core.Parser { @@ -64,7 +65,7 @@ namespace NzbDrone.Core.Parser RegexOptions.IgnoreCase | RegexOptions.Compiled) }; - private static readonly Regex NormalizeRegex = new Regex(@"((^|\W)(a|an|the|and|or|of)($|\W|_))|\W|_|(?:(?<=[^0-9]+)|\b)(?!(?:19\d{2}|20\d{2}))\d+(?=[^0-9ip]+|\b)", + private static readonly Regex NormalizeRegex = new Regex(@"((^|\W|_)(a|an|the|and|or|of)($|\W|_))|\W|_|(?:(?<=[^0-9]+)|\b)(?!(?:19\d{2}|20\d{2}))\d+(?=[^0-9ip]+|\b)", RegexOptions.IgnoreCase | RegexOptions.Compiled); private static readonly Regex SimpleTitleRegex = new Regex(@"480[i|p]|720[i|p]|1080[i|p]|[x|h|x\s|h\s]264|DD\W?5\W1|\<|\>|\?|\*|\:|\|", @@ -75,6 +76,9 @@ namespace NzbDrone.Core.Parser private static readonly Regex LanguageRegex = new Regex(@"(?:\W|_)(?ita|italian)|(?german\b)|(?flemish)|(?greek)|(?(?:\W|_)FR)(?:\W|_)", RegexOptions.IgnoreCase | RegexOptions.Compiled); + private static readonly Regex YearInTitleRegex = new Regex(@"^(?.+?)(?:\W|_)?(?<year>\d{4})", + RegexOptions.IgnoreCase | RegexOptions.Compiled); + public static ParsedEpisodeInfo ParsePath(string path) { var fileInfo = new FileInfo(path); @@ -110,16 +114,20 @@ namespace NzbDrone.Core.Parser if (match.Count != 0) { - var result = ParseMatchCollection(match); - if (result != null) + try { - //Check if episode is in the future (most likely a parse error) - if (result.AirDate > DateTime.Now.AddDays(1).Date || result.AirDate < new DateTime(1970, 1, 1)) - break; - - result.Language = ParseLanguage(title); - result.Quality = QualityParser.ParseQuality(title); - return result; + var result = ParseMatchCollection(match); + if (result != null) + { + result.Language = ParseLanguage(title); + result.Quality = QualityParser.ParseQuality(title); + return result; + } + } + catch (InvalidDateException ex) + { + Logger.TraceException(ex.Message, ex); + break; } } } @@ -134,6 +142,58 @@ namespace NzbDrone.Core.Parser return null; } + public static string ParseSeriesName(string title) + { + Logger.Trace("Parsing string '{0}'", title); + + var parseResult = ParseTitle(title); + + if (parseResult == null) + { + return CleanSeriesTitle(title); + } + + return parseResult.SeriesTitle; + } + + public static string CleanSeriesTitle(this string title) + { + long number = 0; + + //If Title only contains numbers return it as is. + if (Int64.TryParse(title, out number)) + return title; + + return NormalizeRegex.Replace(title, String.Empty).ToLower(); + } + + public static string CleanupEpisodeTitle(string title) + { + //this will remove (1),(2) from the end of multi part episodes. + return MultiPartCleanupRegex.Replace(title, string.Empty).Trim(); + } + + private static SeriesTitleInfo GetSeriesTitleInfo(string title) + { + var seriesTitleInfo = new SeriesTitleInfo(); + seriesTitleInfo.Title = title; + + var match = YearInTitleRegex.Match(title); + + if (!match.Success) + { + seriesTitleInfo.TitleWithoutYear = title; + } + + else + { + seriesTitleInfo.TitleWithoutYear = match.Groups["title"].Value; + seriesTitleInfo.Year = Convert.ToInt32(match.Groups["year"].Value); + } + + return seriesTitleInfo; + } + private static ParsedEpisodeInfo ParseMatchCollection(MatchCollection matchCollection) { var seriesName = matchCollection[0].Groups["title"].Value.Replace('.', ' '); @@ -163,10 +223,10 @@ namespace NzbDrone.Core.Parser return null; result = new ParsedEpisodeInfo - { - SeasonNumber = seasons.First(), - EpisodeNumbers = new int[0], - }; + { + SeasonNumber = seasons.First(), + EpisodeNumbers = new int[0], + }; foreach (Match matchGroup in matchCollection) { @@ -212,33 +272,28 @@ namespace NzbDrone.Core.Parser airmonth = tempDay; } + var airDate = new DateTime(airYear, airmonth, airday); + + //Check if episode is in the future (most likely a parse error) + if (airDate > DateTime.Now.AddDays(1).Date || airDate < new DateTime(1970, 1, 1)) + { + throw new InvalidDateException("Invalid date found: {0}", airDate); + } + result = new ParsedEpisodeInfo - { - AirDate = new DateTime(airYear, airmonth, airday).Date, - }; + { + AirDate = airDate.ToString(Episode.AIR_DATE_FORMAT), + }; } result.SeriesTitle = CleanSeriesTitle(seriesName); + result.SeriesTitleInfo = GetSeriesTitleInfo(result.SeriesTitle); Logger.Trace("Episode Parsed. {0}", result); return result; } - public static string ParseSeriesName(string title) - { - Logger.Trace("Parsing string '{0}'", title); - - var parseResult = ParseTitle(title); - - if (parseResult == null) - { - return CleanSeriesTitle(title); - } - - return parseResult.SeriesTitle; - } - private static Language ParseLanguage(string title) { var lowerTitle = title.ToLower(); @@ -332,22 +387,5 @@ namespace NzbDrone.Core.Parser return true; } - - public static string CleanSeriesTitle(this string title) - { - long number = 0; - - //If Title only contains numbers return it as is. - if (Int64.TryParse(title, out number)) - return title; - - return NormalizeRegex.Replace(title, String.Empty).ToLower(); - } - - public static string CleanupEpisodeTitle(string title) - { - //this will remove (1),(2) from the end of multi part episodes. - return MultiPartCleanupRegex.Replace(title, string.Empty).Trim(); - } } } \ No newline at end of file diff --git a/src/NzbDrone.Core/Parser/ParsingService.cs b/src/NzbDrone.Core/Parser/ParsingService.cs index b678c5eeb..3cd3aa407 100644 --- a/src/NzbDrone.Core/Parser/ParsingService.cs +++ b/src/NzbDrone.Core/Parser/ParsingService.cs @@ -68,15 +68,22 @@ namespace NzbDrone.Core.Parser public Series GetSeries(string title) { - var searchTitle = title; var parsedEpisodeInfo = Parser.ParseTitle(title); - if (parsedEpisodeInfo != null) + if (parsedEpisodeInfo == null) + { + return _seriesService.FindByTitle(title); + } + + var series = _seriesService.FindByTitle(parsedEpisodeInfo.SeriesTitle); + + if (series == null) { - searchTitle = parsedEpisodeInfo.SeriesTitle; + series = _seriesService.FindByTitle(parsedEpisodeInfo.SeriesTitleInfo.TitleWithoutYear, + parsedEpisodeInfo.SeriesTitleInfo.Year); } - return _seriesService.FindByTitle(searchTitle); + return series; } public RemoteEpisode Map(ParsedEpisodeInfo parsedEpisodeInfo, int tvRageId, SearchCriteriaBase searchCriteria = null) @@ -104,7 +111,7 @@ namespace NzbDrone.Core.Parser { var result = new List<Episode>(); - if (parsedEpisodeInfo.AirDate.HasValue) + if (parsedEpisodeInfo.IsDaily()) { if (series.SeriesType == SeriesTypes.Standard) { @@ -112,7 +119,7 @@ namespace NzbDrone.Core.Parser return null; } - var episodeInfo = GetDailyEpisode(series, parsedEpisodeInfo.AirDate.Value, searchCriteria); + var episodeInfo = GetDailyEpisode(series, parsedEpisodeInfo.AirDate, searchCriteria); if (episodeInfo != null) { @@ -223,14 +230,14 @@ namespace NzbDrone.Core.Parser return series; } - private Episode GetDailyEpisode(Series series, DateTime airDate, SearchCriteriaBase searchCriteria) + private Episode GetDailyEpisode(Series series, String airDate, SearchCriteriaBase searchCriteria) { Episode episodeInfo = null; if (searchCriteria != null) { episodeInfo = searchCriteria.Episodes.SingleOrDefault( - e => e.AirDate == airDate.ToString(Episode.AIR_DATE_FORMAT)); + e => e.AirDate == airDate); } if (episodeInfo == null) diff --git a/src/NzbDrone.Core/Tv/EpisodeRepository.cs b/src/NzbDrone.Core/Tv/EpisodeRepository.cs index 57d8acbc1..daba4d5e0 100644 --- a/src/NzbDrone.Core/Tv/EpisodeRepository.cs +++ b/src/NzbDrone.Core/Tv/EpisodeRepository.cs @@ -11,8 +11,8 @@ namespace NzbDrone.Core.Tv public interface IEpisodeRepository : IBasicRepository<Episode> { Episode Find(int seriesId, int season, int episodeNumber); - Episode Get(int seriesId, DateTime date); - Episode Find(int seriesId, DateTime date); + Episode Get(int seriesId, String date); + Episode Find(int seriesId, String date); List<Episode> GetEpisodes(int seriesId); List<Episode> GetEpisodes(int seriesId, int seasonNumber); List<Episode> GetEpisodeByFileId(int fileId); @@ -39,14 +39,14 @@ namespace NzbDrone.Core.Tv return Query.SingleOrDefault(s => s.SeriesId == seriesId && s.SeasonNumber == season && s.EpisodeNumber == episodeNumber); } - public Episode Get(int seriesId, DateTime date) + public Episode Get(int seriesId, String date) { - return Query.Single(s => s.SeriesId == seriesId && s.AirDate == date.ToString(Episode.AIR_DATE_FORMAT)); + return Query.Single(s => s.SeriesId == seriesId && s.AirDate == date); } - public Episode Find(int seriesId, DateTime date) + public Episode Find(int seriesId, String date) { - return Query.SingleOrDefault(s => s.SeriesId == seriesId && s.AirDate == date.ToString(Episode.AIR_DATE_FORMAT)); + return Query.SingleOrDefault(s => s.SeriesId == seriesId && s.AirDate == date); } public List<Episode> GetEpisodes(int seriesId) diff --git a/src/NzbDrone.Core/Tv/EpisodeService.cs b/src/NzbDrone.Core/Tv/EpisodeService.cs index 8bd88187d..9ef46761f 100644 --- a/src/NzbDrone.Core/Tv/EpisodeService.cs +++ b/src/NzbDrone.Core/Tv/EpisodeService.cs @@ -14,8 +14,8 @@ namespace NzbDrone.Core.Tv { Episode GetEpisode(int id); Episode FindEpisode(int seriesId, int seasonNumber, int episodeNumber, bool useScene = false); - Episode GetEpisode(int seriesId, DateTime date); - Episode FindEpisode(int seriesId, DateTime date); + Episode GetEpisode(int seriesId, String date); + Episode FindEpisode(int seriesId, String date); List<Episode> GetEpisodeBySeries(int seriesId); List<Episode> GetEpisodesBySeason(int seriesId, int seasonNumber); PagingSpec<Episode> EpisodesWithoutFiles(PagingSpec<Episode> pagingSpec); @@ -62,12 +62,12 @@ namespace NzbDrone.Core.Tv return _episodeRepository.Find(seriesId, seasonNumber, episodeNumber); } - public Episode GetEpisode(int seriesId, DateTime date) + public Episode GetEpisode(int seriesId, String date) { return _episodeRepository.Get(seriesId, date); } - public Episode FindEpisode(int seriesId, DateTime date) + public Episode FindEpisode(int seriesId, String date) { return _episodeRepository.Find(seriesId, date); } diff --git a/src/NzbDrone.Core/Tv/SeriesRepository.cs b/src/NzbDrone.Core/Tv/SeriesRepository.cs index 0c7d0288e..dbdc1c191 100644 --- a/src/NzbDrone.Core/Tv/SeriesRepository.cs +++ b/src/NzbDrone.Core/Tv/SeriesRepository.cs @@ -10,6 +10,7 @@ namespace NzbDrone.Core.Tv { bool SeriesPathExists(string path); Series FindByTitle(string cleanTitle); + Series FindByTitle(string cleanTitle, int year); Series FindByTvdbId(int tvdbId); Series FindByTvRageId(int tvRageId); void SetSeriesType(int seriesId, SeriesTypes seriesTypes); @@ -32,6 +33,12 @@ namespace NzbDrone.Core.Tv return Query.SingleOrDefault(s => s.CleanTitle.Equals(cleanTitle, StringComparison.InvariantCultureIgnoreCase)); } + public Series FindByTitle(string cleanTitle, int year) + { + return Query.SingleOrDefault(s => s.CleanTitle.Equals(cleanTitle, StringComparison.InvariantCultureIgnoreCase) && + s.Year == year); + } + public Series FindByTvdbId(int tvdbId) { return Query.SingleOrDefault(s => s.TvdbId.Equals(tvdbId)); diff --git a/src/NzbDrone.Core/Tv/SeriesService.cs b/src/NzbDrone.Core/Tv/SeriesService.cs index 7496a15e7..6f94faa84 100644 --- a/src/NzbDrone.Core/Tv/SeriesService.cs +++ b/src/NzbDrone.Core/Tv/SeriesService.cs @@ -19,6 +19,7 @@ namespace NzbDrone.Core.Tv Series FindByTvdbId(int tvdbId); Series FindByTvRageId(int tvRageId); Series FindByTitle(string title); + Series FindByTitle(string title, int year); void SetSeriesType(int seriesId, SeriesTypes seriesTypes); void DeleteSeries(int seriesId, bool deleteFiles); List<Series> GetAllSeries(); @@ -100,6 +101,11 @@ namespace NzbDrone.Core.Tv return _seriesRepository.FindByTitle(Parser.Parser.CleanSeriesTitle(title)); } + public Series FindByTitle(string title, int year) + { + return _seriesRepository.FindByTitle(title, year); + } + public void SetSeriesType(int seriesId, SeriesTypes seriesTypes) { _seriesRepository.SetSeriesType(seriesId, seriesTypes); diff --git a/src/NzbDrone.Core/Update/Commands/InstallUpdateCommand.cs b/src/NzbDrone.Core/Update/Commands/InstallUpdateCommand.cs new file mode 100644 index 000000000..8dfe88f1c --- /dev/null +++ b/src/NzbDrone.Core/Update/Commands/InstallUpdateCommand.cs @@ -0,0 +1,13 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using NzbDrone.Core.Messaging.Commands; + +namespace NzbDrone.Core.Update.Commands +{ + public class InstallUpdateCommand : Command + { + public UpdatePackage UpdatePackage { get; set; } + } +} diff --git a/src/NzbDrone.Core/Update/InstallUpdateService.cs b/src/NzbDrone.Core/Update/InstallUpdateService.cs index 6b4b10ab3..15b1e8bad 100644 --- a/src/NzbDrone.Core/Update/InstallUpdateService.cs +++ b/src/NzbDrone.Core/Update/InstallUpdateService.cs @@ -16,7 +16,7 @@ namespace NzbDrone.Core.Update void InstallUpdate(UpdatePackage updatePackage); } - public class InstallUpdateService : IInstallUpdates, IExecute<ApplicationUpdateCommand> + public class InstallUpdateService : IInstallUpdates, IExecute<ApplicationUpdateCommand>, IExecute<InstallUpdateCommand> { private readonly ICheckUpdateService _checkUpdateService; private readonly Logger _logger; @@ -89,5 +89,10 @@ namespace NzbDrone.Core.Update InstallUpdate(latestAvailable); } } + + public void Execute(InstallUpdateCommand message) + { + InstallUpdate(message.UpdatePackage); + } } } diff --git a/src/UI/AddSeries/AddSeriesLayout.js b/src/UI/AddSeries/AddSeriesLayout.js index 23c21d2ed..1b778546d 100644 --- a/src/UI/AddSeries/AddSeriesLayout.js +++ b/src/UI/AddSeries/AddSeriesLayout.js @@ -37,7 +37,10 @@ define( initialize: function () { QualityProfileCollection.fetch(); - RootFolderCollection.fetch(); + RootFolderCollection.fetch() + .done(function () { + RootFolderCollection.synced = true; + }); }, onShow: function () { diff --git a/src/UI/AddSeries/RootFolders/Layout.js b/src/UI/AddSeries/RootFolders/Layout.js index 795f62edc..3b54c90a1 100644 --- a/src/UI/AddSeries/RootFolders/Layout.js +++ b/src/UI/AddSeries/RootFolders/Layout.js @@ -37,7 +37,7 @@ define( onRender: function () { this.currentDirs.show(new LoadingView()); - if (RootFolderCollection.any()) { + if (RootFolderCollection.synced) { this._showCurrentDirs(); } diff --git a/src/UI/Cells/EventTypeCell.js b/src/UI/Cells/EventTypeCell.js index 3b9bb8b0a..47c179061 100644 --- a/src/UI/Cells/EventTypeCell.js +++ b/src/UI/Cells/EventTypeCell.js @@ -29,6 +29,10 @@ define( icon = 'icon-nd-imported'; toolTip = 'Episode downloaded successfully and picked up from download client'; break; + case 'downloadFailed': + icon = 'icon-nd-download-failed'; + toolTip = 'Episode download failed'; + break; default : icon = 'icon-question'; toolTip = 'unknown event'; diff --git a/src/UI/Commands/CommandController.js b/src/UI/Commands/CommandController.js index 4bb78f011..60684bbf5 100644 --- a/src/UI/Commands/CommandController.js +++ b/src/UI/Commands/CommandController.js @@ -43,7 +43,7 @@ define( } }); - CommandCollection.bind('add sync', function () { + CommandCollection.bind('sync', function () { var command = CommandCollection.findCommand(options.command); if (command) { self._bindToCommandModel.call(self, command, options); diff --git a/src/UI/Content/icons.less b/src/UI/Content/icons.less index 131e82b07..14f35d6dd 100644 --- a/src/UI/Content/icons.less +++ b/src/UI/Content/icons.less @@ -156,4 +156,9 @@ .icon-fatal:before { .icon(@remove-sign); color : purple; +} + +.icon-nd-download-failed:before { + .icon(@cloud-download); + color: @errorText; } \ No newline at end of file diff --git a/src/UI/Handlebars/Helpers/Series.js b/src/UI/Handlebars/Helpers/Series.js index 69022243c..077b87814 100644 --- a/src/UI/Handlebars/Helpers/Series.js +++ b/src/UI/Handlebars/Helpers/Series.js @@ -68,6 +68,6 @@ define( return this.title; } - return '{0} ({1})'.format(this.title, this.year); + return new Handlebars.SafeString('{0} <em>({1})</em>'.format(this.title, this.year)); }); }); diff --git a/src/UI/History/Details/HistoryDetailsView.js b/src/UI/History/Details/HistoryDetailsView.js index b7c8e1a9d..c1470cb46 100644 --- a/src/UI/History/Details/HistoryDetailsView.js +++ b/src/UI/History/Details/HistoryDetailsView.js @@ -1,10 +1,30 @@ 'use strict'; define( [ - 'marionette' - ], function (Marionette) { + 'vent', + 'marionette', + 'jquery' + ], function (vent, Marionette, $) { return Marionette.ItemView.extend({ - template: 'History/Details/HistoryDetailsViewTemplate' + template: 'History/Details/HistoryDetailsViewTemplate', + + events: { + 'click .x-mark-as-failed': '_markAsFailed' + }, + + _markAsFailed: function () { + var url = window.NzbDrone.ApiRoot + '/history/failed'; + var data = { + id: this.model.get('id') + }; + + $.ajax({ + url: url, + type: 'POST', + data: data + }); + vent.trigger(vent.Commands.CloseModalCommand); + } }); }); diff --git a/src/UI/History/Details/HistoryDetailsViewTemplate.html b/src/UI/History/Details/HistoryDetailsViewTemplate.html index 2dd83ed5e..9e2a1433e 100644 --- a/src/UI/History/Details/HistoryDetailsViewTemplate.html +++ b/src/UI/History/Details/HistoryDetailsViewTemplate.html @@ -3,7 +3,9 @@ <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button> <h3> - Details + {{#if_eq eventType compare="grabbed"}}Grabbed{{/if_eq}} + {{#if_eq eventType compare="downloadFailed"}}Download Failed{{/if_eq}} + {{#if_eq eventType compare="downloadFolderImported"}}Episode Imported{{/if_eq}} </h3> </div> @@ -27,24 +29,33 @@ {{#if nzbInfoUrl}} <dt>Info</dt> - <dd><a href="{{infoUrl}}">{{infoUrl}}o</a></dd> + <dd><a href="{{nzbInfoUrl}}">{{nzbInfoUrl}}</a></dd> {{/if}} {{/with}} </dl> - {{else}} + {{/if_eq}} + {{#if_eq eventType compare="downloadFailed"}} + <dl class="dl-horizontal"> + {{#with data}} + <dt>Message</dt> + <dd>{{message}}</dd> + {{/with}} + </dl> + {{/if_eq}} + {{#if_eq eventType compare="downloadFolderImported"}} {{#if data}} {{#with data}} - <dl class="dl-horizontal"> - {{#if droppedPath}} - <dt>Source:</dt> - <dd>{{droppedPath}}</dd> - {{/if}} - - {{#if importedPath}} - <dt>Imported To:</dt> - <dd>{{importedPath}}</dd> - {{/if}} - </dl> + <dl class="dl-horizontal"> + {{#if droppedPath}} + <dt>Source:</dt> + <dd>{{droppedPath}}</dd> + {{/if}} + + {{#if importedPath}} + <dt>Imported To:</dt> + <dd>{{importedPath}}</dd> + {{/if}} + </dl> {{/with}} {{else}} No details available @@ -52,6 +63,7 @@ {{/if_eq}} </div> <div class="modal-footer"> + {{#if_eq eventType compare="grabbed"}}<button class="btn btn-danger x-mark-as-failed">mark as failed</button>{{/if_eq}} <button class="btn" data-dismiss="modal">close</button> </div> </div> diff --git a/src/UI/History/Table/ControlsColumnTemplate.html b/src/UI/History/Table/ControlsColumnTemplate.html deleted file mode 100644 index 869b7b965..000000000 --- a/src/UI/History/Table/ControlsColumnTemplate.html +++ /dev/null @@ -1,2 +0,0 @@ -<i class="icon-remove x-remove" title="Remove"/> -<i class="icon-repeat x-redownload" title="Re-Download"/> diff --git a/src/UI/History/Table/HistoryDetailsCell.js b/src/UI/History/Table/HistoryDetailsCell.js index 5f29097c3..64c268508 100644 --- a/src/UI/History/Table/HistoryDetailsCell.js +++ b/src/UI/History/Table/HistoryDetailsCell.js @@ -21,7 +21,7 @@ define( }, _showDetails: function () { - vent.trigger(vent.Commands.ShowHistoryDetails, { history: this.model }); + vent.trigger(vent.Commands.ShowHistoryDetails, { model: this.model }); } }); }); diff --git a/src/UI/Settings/MediaManagement/FileManagement/FileManagementView.js b/src/UI/Settings/MediaManagement/FileManagement/FileManagementView.js index ff6a247b9..8cd2c120e 100644 --- a/src/UI/Settings/MediaManagement/FileManagement/FileManagementView.js +++ b/src/UI/Settings/MediaManagement/FileManagement/FileManagementView.js @@ -10,11 +10,28 @@ define( template: 'Settings/MediaManagement/FileManagement/FileManagementViewTemplate', ui: { - recyclingBin: '.x-path' + recyclingBin : '.x-path', + failedDownloadHandlingCheckbox: '.x-failed-download-handling', + failedDownloadOptions : '.x-failed-download-options' + }, + + events: { + 'change .x-failed-download-handling': '_setFailedDownloadOptionsVisibility' }, onShow: function () { this.ui.recyclingBin.autoComplete('/directories'); + }, + + _setFailedDownloadOptionsVisibility: function () { + var checked = this.ui.failedDownloadHandlingCheckbox.prop('checked'); + if (checked) { + this.ui.failedDownloadOptions.slideDown(); + } + + else { + this.ui.failedDownloadOptions.slideUp(); + } } }); diff --git a/src/UI/Settings/MediaManagement/FileManagement/FileManagementViewTemplate.html b/src/UI/Settings/MediaManagement/FileManagement/FileManagementViewTemplate.html index 02938c4e0..ae02dc6a5 100644 --- a/src/UI/Settings/MediaManagement/FileManagement/FileManagementViewTemplate.html +++ b/src/UI/Settings/MediaManagement/FileManagement/FileManagementViewTemplate.html @@ -52,3 +52,69 @@ </div> </div> </fieldset> + +<fieldset class="advanced-setting"> + <legend>Failed Download Handling</legend> + + <div class="control-group"> + <label class="control-label">Enable</label> + + <div class="controls"> + <label class="checkbox toggle well"> + <input type="checkbox" name="enableFailedDownloadHandling" class="x-failed-download-handling"/> + <p> + <span>Yes</span> + <span>No</span> + </p> + + <div class="btn btn-primary slide-button"/> + </label> + + <span class="help-inline-checkbox"> + <i class="icon-question-sign" title="Process failed downloads and blacklist the release"/> + </span> + </div> + </div> + + <div class="x-failed-download-options"> + <div class="control-group"> + <label class="control-label">Redownload</label> + + <div class="controls"> + <label class="checkbox toggle well"> + <input type="checkbox" name="autoRedownloadFailed"/> + <p> + <span>Yes</span> + <span>No</span> + </p> + + <div class="btn btn-primary slide-button"/> + </label> + + <span class="help-inline-checkbox"> + <i class="icon-question-sign" title="Automatically search for and attempt to download another release when a download fails?"/> + </span> + </div> + </div> + + <div class="control-group"> + <label class="control-label">Remove</label> + + <div class="controls"> + <label class="checkbox toggle well"> + <input type="checkbox" name="removeFailedDownloads"/> + <p> + <span>Yes</span> + <span>No</span> + </p> + + <div class="btn btn-primary slide-button"/> + </label> + + <span class="help-inline-checkbox"> + <i class="icon-question-sign" title="Automatically remove failed downloads from history and encrypted downloads from queue?"/> + </span> + </div> + </div> + </div> +</fieldset> \ No newline at end of file diff --git a/src/UI/Settings/MediaManagement/Naming/NamingView.js b/src/UI/Settings/MediaManagement/Naming/NamingView.js index 3acadee56..5ca680643 100644 --- a/src/UI/Settings/MediaManagement/Naming/NamingView.js +++ b/src/UI/Settings/MediaManagement/Naming/NamingView.js @@ -17,7 +17,7 @@ define( }, events: { - 'change .x-rename-episodes': '_setNamingOptionsVisibility' + 'change .x-rename-episodes': '_setFailedDownloadOptionsVisibility' }, onRender: function () { @@ -32,7 +32,7 @@ define( this._updateSamples(); }, - _setNamingOptionsVisibility: function () { + _setFailedDownloadOptionsVisibility: function () { var checked = this.ui.renameEpisodesCheckbox.prop('checked'); if (checked) { this.ui.namingOptions.slideDown(); diff --git a/src/UI/Shared/Modal/Controller.js b/src/UI/Shared/Modal/Controller.js index 465119a0f..349db691d 100644 --- a/src/UI/Shared/Modal/Controller.js +++ b/src/UI/Shared/Modal/Controller.js @@ -7,8 +7,9 @@ define( 'Series/Edit/EditSeriesView', 'Series/Delete/DeleteSeriesView', 'Episode/EpisodeDetailsLayout', - 'History/Details/HistoryDetailsView' - ], function (vent, AppLayout, Marionette, EditSeriesView, DeleteSeriesView, EpisodeDetailsLayout, HistoryDetailsView) { + 'History/Details/HistoryDetailsView', + 'System/Logs/Table/Details/LogDetailsView' + ], function (vent, AppLayout, Marionette, EditSeriesView, DeleteSeriesView, EpisodeDetailsLayout, HistoryDetailsView, LogDetailsView) { return Marionette.AppRouter.extend({ @@ -18,6 +19,7 @@ define( vent.on(vent.Commands.DeleteSeriesCommand, this._deleteSeries, this); vent.on(vent.Commands.ShowEpisodeDetails, this._showEpisode, this); vent.on(vent.Commands.ShowHistoryDetails, this._showHistory, this); + vent.on(vent.Commands.ShowLogDetails, this._showLogDetails, this); }, _closeModal: function () { @@ -40,7 +42,12 @@ define( }, _showHistory: function (options) { - var view = new HistoryDetailsView({ model: options.history }); + var view = new HistoryDetailsView({ model: options.model }); + AppLayout.modalRegion.show(view); + }, + + _showLogDetails: function (options) { + var view = new LogDetailsView({ model: options.model }); AppLayout.modalRegion.show(view); } }); diff --git a/src/UI/System/Logs/Files/LogFileLayout.js b/src/UI/System/Logs/Files/LogFileLayout.js index e4c272dfe..f8de17828 100644 --- a/src/UI/System/Logs/Files/LogFileLayout.js +++ b/src/UI/System/Logs/Files/LogFileLayout.js @@ -130,12 +130,12 @@ define( filename: filename }); - this.listenToOnce(contentsModel, 'sync', this._showContents); + this.listenToOnce(contentsModel, 'sync', this._showDetails); contentsModel.fetch({ dataType: 'text' }); }, - _showContents: function (model) { + _showDetails: function (model) { this.contents.show(new ContentsView({ model: model })); }, diff --git a/src/UI/System/Logs/Files/Row.js b/src/UI/System/Logs/Files/Row.js index 543893b00..926869008 100644 --- a/src/UI/System/Logs/Files/Row.js +++ b/src/UI/System/Logs/Files/Row.js @@ -9,10 +9,10 @@ define( className: 'log-file-row', events: { - 'click': '_showContents' + 'click': '_showDetails' }, - _showContents: function () { + _showDetails: function () { vent.trigger(vent.Commands.ShowLogFile, { model: this.model }); } }); diff --git a/src/UI/System/Logs/Logs.less b/src/UI/System/Logs/Logs.less index c61c3a135..f5deaf3c5 100644 --- a/src/UI/System/Logs/Logs.less +++ b/src/UI/System/Logs/Logs.less @@ -18,4 +18,8 @@ .log-file-row { .clickable; +} + +.log-row { + .clickable; } \ No newline at end of file diff --git a/src/UI/System/Logs/Table/Details/LogDetailsView.js b/src/UI/System/Logs/Table/Details/LogDetailsView.js new file mode 100644 index 000000000..eba74360e --- /dev/null +++ b/src/UI/System/Logs/Table/Details/LogDetailsView.js @@ -0,0 +1,11 @@ +'use strict'; +define( + [ + 'vent', + 'marionette' + ], function (vent, Marionette) { + + return Marionette.ItemView.extend({ + template: 'System/Logs/Table/Details/LogDetailsViewTemplate' + }); + }); diff --git a/src/UI/System/Logs/Table/Details/LogDetailsViewTemplate.html b/src/UI/System/Logs/Table/Details/LogDetailsViewTemplate.html new file mode 100644 index 000000000..5ad8f7594 --- /dev/null +++ b/src/UI/System/Logs/Table/Details/LogDetailsViewTemplate.html @@ -0,0 +1,22 @@ +<div class="log-details-modal"> + <div class="modal-header"> + <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button> + + <h3>Details</h3> + + </div> + <div class="modal-body"> + Message + <pre>{{message}}</pre> + + {{#if exception}} + <br/> + Exception + <pre>{{exception}}</pre> + {{/if}} + </div> + <div class="modal-footer"> + <button class="btn" data-dismiss="modal">close</button> + </div> +</div> + diff --git a/src/UI/System/Logs/Table/LogRow.js b/src/UI/System/Logs/Table/LogRow.js new file mode 100644 index 000000000..1507f6ff3 --- /dev/null +++ b/src/UI/System/Logs/Table/LogRow.js @@ -0,0 +1,19 @@ +'use strict'; +define( + [ + 'vent', + 'backgrid' + ], function (vent, Backgrid) { + + return Backgrid.Row.extend({ + className: 'log-row', + + events: { + 'click': '_showDetails' + }, + + _showDetails: function () { + vent.trigger(vent.Commands.ShowLogDetails, { model: this.model }); + } + }); + }); diff --git a/src/UI/System/Logs/Table/LogsTableLayout.js b/src/UI/System/Logs/Table/LogsTableLayout.js index 9288474c3..95a59851a 100644 --- a/src/UI/System/Logs/Table/LogsTableLayout.js +++ b/src/UI/System/Logs/Table/LogsTableLayout.js @@ -6,11 +6,12 @@ define( 'backgrid', 'System/Logs/Table/LogTimeCell', 'System/Logs/Table/LogLevelCell', + 'System/Logs/Table/LogRow', 'Shared/Grid/Pager', 'System/Logs/LogsCollection', 'Shared/Toolbar/ToolbarLayout', 'Shared/LoadingView' - ], function (vent, Marionette, Backgrid, LogTimeCell, LogLevelCell, GridPager, LogCollection, ToolbarLayout, LoadingView) { + ], function (vent, Marionette, Backgrid, LogTimeCell, LogLevelCell, LogRow, GridPager, LogCollection, ToolbarLayout, LoadingView) { return Marionette.Layout.extend({ template: 'System/Logs/Table/LogsTableLayoutTemplate', @@ -77,7 +78,7 @@ define( _showTable: function () { this.grid.show(new Backgrid.Grid({ - row : Backgrid.Row, + row : LogRow, columns : this.columns, collection: this.collection, className : 'table table-hover' diff --git a/src/UI/System/Update/UpdateItemView.js b/src/UI/System/Update/UpdateItemView.js index 79186cd65..362b76690 100644 --- a/src/UI/System/Update/UpdateItemView.js +++ b/src/UI/System/Update/UpdateItemView.js @@ -2,8 +2,9 @@ define( [ - 'marionette' - ], function (Marionette) { + 'marionette', + 'Commands/CommandController' + ], function (Marionette, CommandController) { return Marionette.ItemView.extend({ template: 'System/Update/UpdateItemViewTemplate', @@ -12,7 +13,7 @@ define( }, _installUpdate: function () { - this.model.save(); + CommandController.Execute('installUpdate', { updatePackage: this.model.toJSON() }); } }); }); diff --git a/src/UI/vent.js b/src/UI/vent.js index b8b7eff51..4170ac72b 100644 --- a/src/UI/vent.js +++ b/src/UI/vent.js @@ -20,6 +20,7 @@ define( CloseModalCommand : 'CloseModalCommand', ShowEpisodeDetails : 'ShowEpisodeDetails', ShowHistoryDetails : 'ShowHistoryDetails', + ShowLogDetails : 'ShowLogDetails', SaveSettings : 'saveSettings', ShowLogFile : 'showLogFile' };