diff --git a/.editorconfig b/.editorconfig index 8eaf9a3bf..b74add49a 100644 --- a/.editorconfig +++ b/.editorconfig @@ -69,6 +69,7 @@ dotnet_diagnostic.SA1406.severity = suggestion dotnet_diagnostic.SA1410.severity = suggestion dotnet_diagnostic.SA1411.severity = suggestion dotnet_diagnostic.SA1413.severity = none +dotnet_diagnostic.SA1512.severity = none dotnet_diagnostic.SA1516.severity = none dotnet_diagnostic.SA1600.severity = none dotnet_diagnostic.SA1601.severity = none diff --git a/.gitignore b/.gitignore index 073135e2e..f6462057b 100644 --- a/.gitignore +++ b/.gitignore @@ -84,7 +84,6 @@ TestResults [Tt]est[Rr]esult* *.Cache ClientBin -[Ss]tyle[Cc]op.* ~$* *.dbmdl Generated_Code #added for RIA/Silverlight projects diff --git a/src/Directory.Build.props b/src/Directory.Build.props index e213bdc20..b9c4e8099 100644 --- a/src/Directory.Build.props +++ b/src/Directory.Build.props @@ -104,6 +104,16 @@ false + + + + + all + runtime; build; native; contentfiles; analyzers + + + + diff --git a/src/NzbDrone.Api.Test/ClientSchemaTests/SchemaBuilderFixture.cs b/src/NzbDrone.Api.Test/ClientSchemaTests/SchemaBuilderFixture.cs index 497725c65..8b675b5bf 100644 --- a/src/NzbDrone.Api.Test/ClientSchemaTests/SchemaBuilderFixture.cs +++ b/src/NzbDrone.Api.Test/ClientSchemaTests/SchemaBuilderFixture.cs @@ -16,7 +16,6 @@ public void should_return_field_for_every_property() schema.Should().HaveCount(2); } - [Test] public void schema_should_have_proper_fields() { @@ -32,7 +31,6 @@ public void schema_should_have_proper_fields() schema.Should().Contain(c => c.Order == 0 && c.Name == "firstName" && c.Label == "First Name" && c.HelpText == "Your First Name" && (string)c.Value == "Bob"); } - [Test] public void schema_should_have_nested_fields() { diff --git a/src/NzbDrone.Automation.Test/AutomationTestAttribute.cs b/src/NzbDrone.Automation.Test/AutomationTestAttribute.cs index d1cf9faec..2ed2fac7e 100644 --- a/src/NzbDrone.Automation.Test/AutomationTestAttribute.cs +++ b/src/NzbDrone.Automation.Test/AutomationTestAttribute.cs @@ -7,7 +7,6 @@ public class AutomationTestAttribute : CategoryAttribute public AutomationTestAttribute() : base("AutomationTest") { - } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Automation.Test/MainPagesTest.cs b/src/NzbDrone.Automation.Test/MainPagesTest.cs index 4dcc5556a..6711bbbc3 100644 --- a/src/NzbDrone.Automation.Test/MainPagesTest.cs +++ b/src/NzbDrone.Automation.Test/MainPagesTest.cs @@ -1,4 +1,5 @@ -using FluentAssertions; +using System.Reflection; +using FluentAssertions; using NUnit.Framework; using NzbDrone.Automation.Test.PageModel; using OpenQA.Selenium; @@ -8,73 +9,86 @@ namespace NzbDrone.Automation.Test [TestFixture] public class MainPagesTest : AutomationTest { - private PageBase page; + private PageBase _page; [SetUp] public void Setup() { - page = new PageBase(driver); + _page = new PageBase(driver); } [Test] public void series_page() { - page.SeriesNavIcon.Click(); - page.WaitForNoSpinner(); + _page.SeriesNavIcon.Click(); + _page.WaitForNoSpinner(); - page.Find(By.CssSelector("div[class*='SeriesIndex']")).Should().NotBeNull(); + var imageName = MethodBase.GetCurrentMethod().Name; + TakeScreenshot(imageName); + + _page.Find(By.CssSelector("div[class*='SeriesIndex']")).Should().NotBeNull(); } [Test] public void calendar_page() { - page.CalendarNavIcon.Click(); - page.WaitForNoSpinner(); + _page.CalendarNavIcon.Click(); + _page.WaitForNoSpinner(); - page.Find(By.CssSelector("div[class*='CalendarPage']")).Should().NotBeNull(); + var imageName = MethodBase.GetCurrentMethod().Name; + TakeScreenshot(imageName); + + _page.Find(By.CssSelector("div[class*='CalendarPage']")).Should().NotBeNull(); } [Test] public void activity_page() { - page.ActivityNavIcon.Click(); - page.WaitForNoSpinner(); + _page.ActivityNavIcon.Click(); + _page.WaitForNoSpinner(); - page.Find(By.LinkText("Queue")).Should().NotBeNull(); - page.Find(By.LinkText("History")).Should().NotBeNull(); - page.Find(By.LinkText("Blocklist")).Should().NotBeNull(); + var imageName = MethodBase.GetCurrentMethod().Name; + TakeScreenshot(imageName); + + _page.Find(By.LinkText("Queue")).Should().NotBeNull(); + _page.Find(By.LinkText("History")).Should().NotBeNull(); + _page.Find(By.LinkText("Blocklist")).Should().NotBeNull(); } [Test] public void wanted_page() { - page.WantedNavIcon.Click(); - page.WaitForNoSpinner(); + _page.WantedNavIcon.Click(); + _page.WaitForNoSpinner(); - page.Find(By.LinkText("Missing")).Should().NotBeNull(); - page.Find(By.LinkText("Cutoff Unmet")).Should().NotBeNull(); + _page.Find(By.LinkText("Missing")).Should().NotBeNull(); + _page.Find(By.LinkText("Cutoff Unmet")).Should().NotBeNull(); } [Test] public void system_page() { - page.SystemNavIcon.Click(); - page.WaitForNoSpinner(); + _page.SystemNavIcon.Click(); + _page.WaitForNoSpinner(); - page.Find(By.CssSelector("div[class*='Health']")).Should().NotBeNull(); + var imageName = MethodBase.GetCurrentMethod().Name; + TakeScreenshot(imageName); + + _page.Find(By.CssSelector("div[class*='Health']")).Should().NotBeNull(); } [Test] public void add_series_page() { - page.SeriesNavIcon.Click(); - page.WaitForNoSpinner(); + _page.SeriesNavIcon.Click(); + _page.WaitForNoSpinner(); - page.Find(By.LinkText("Add New")).Click(); + _page.Find(By.LinkText("Add New")).Click(); - page.WaitForNoSpinner(); + var imageName = MethodBase.GetCurrentMethod().Name; + TakeScreenshot(imageName); - page.Find(By.CssSelector("input[class*='AddNewSeries/searchInput']")).Should().NotBeNull(); + _page.Find(By.CssSelector("input[class*='AddNewSeries-searchInput']")).Should().NotBeNull(); } } } diff --git a/src/NzbDrone.Automation.Test/PageModel/PageBase.cs b/src/NzbDrone.Automation.Test/PageModel/PageBase.cs index b030536c5..00d084f13 100644 --- a/src/NzbDrone.Automation.Test/PageModel/PageBase.cs +++ b/src/NzbDrone.Automation.Test/PageModel/PageBase.cs @@ -59,4 +59,4 @@ public void WaitForNoSpinner(int timeout = 30) public IWebElement SystemNavIcon => Find(By.PartialLinkText("System")); } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Automation.Test/Sonarr.Automation.Test.csproj b/src/NzbDrone.Automation.Test/Sonarr.Automation.Test.csproj index b5388248b..be3d4d4db 100644 --- a/src/NzbDrone.Automation.Test/Sonarr.Automation.Test.csproj +++ b/src/NzbDrone.Automation.Test/Sonarr.Automation.Test.csproj @@ -4,7 +4,7 @@ - + diff --git a/src/NzbDrone.Common.Test/CacheTests/CachedDictionaryFixture.cs b/src/NzbDrone.Common.Test/CacheTests/CachedDictionaryFixture.cs index 23781d033..4b98d7313 100644 --- a/src/NzbDrone.Common.Test/CacheTests/CachedDictionaryFixture.cs +++ b/src/NzbDrone.Common.Test/CacheTests/CachedDictionaryFixture.cs @@ -99,4 +99,4 @@ public Dictionary GetDict() return result; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common.Test/CacheTests/CachedFixture.cs b/src/NzbDrone.Common.Test/CacheTests/CachedFixture.cs index 54b2a0e01..7c892047d 100644 --- a/src/NzbDrone.Common.Test/CacheTests/CachedFixture.cs +++ b/src/NzbDrone.Common.Test/CacheTests/CachedFixture.cs @@ -26,7 +26,6 @@ public void should_call_function_once() _cachedString.Get("Test", _worker.GetString); _worker.HitCount.Should().Be(1); - } [Test] @@ -38,7 +37,6 @@ public void multiple_calls_should_return_same_result() first.Should().Be(second); } - [Test] public void should_be_able_to_update_key() { @@ -48,7 +46,6 @@ public void should_be_able_to_update_key() _cachedString.Find("Key").Should().Be("New"); } - [Test] public void should_be_able_to_remove_key() { @@ -70,7 +67,6 @@ public void should_store_null() { int hitCount = 0; - for (int i = 0; i < 10; i++) { _cachedString.Get("key", () => @@ -84,6 +80,7 @@ public void should_store_null() } [Test] + [Platform(Exclude = "MacOsX")] public void should_honor_ttl() { int hitCount = 0; @@ -91,11 +88,13 @@ public void should_honor_ttl() for (int i = 0; i < 10; i++) { - _cachedString.Get("key", () => + _cachedString.Get("key", + () => { hitCount++; return null; - }, TimeSpan.FromMilliseconds(300)); + }, + TimeSpan.FromMilliseconds(300)); Thread.Sleep(100); } @@ -114,4 +113,4 @@ public string GetString() return "Hit count is " + HitCount; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common.Test/CacheTests/CachedManagerFixture.cs b/src/NzbDrone.Common.Test/CacheTests/CachedManagerFixture.cs index ec3f9de35..29d4516fb 100644 --- a/src/NzbDrone.Common.Test/CacheTests/CachedManagerFixture.cs +++ b/src/NzbDrone.Common.Test/CacheTests/CachedManagerFixture.cs @@ -26,4 +26,4 @@ public void multiple_calls_should_get_the_same_cache() result1.Should().BeSameAs(result2); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common.Test/ConfigFileProviderTest.cs b/src/NzbDrone.Common.Test/ConfigFileProviderTest.cs index 92df06ded..9622f4e01 100644 --- a/src/NzbDrone.Common.Test/ConfigFileProviderTest.cs +++ b/src/NzbDrone.Common.Test/ConfigFileProviderTest.cs @@ -62,10 +62,8 @@ public void GetInt_Success() const string key = "Port"; const int value = 8989; - var result = Subject.GetValueInt(key, value); - result.Should().Be(value); } @@ -75,20 +73,16 @@ public void GetBool_Success() const string key = "LaunchBrowser"; const bool value = true; - var result = Subject.GetValueBoolean(key, value); - result.Should().BeTrue(); } [Test] public void GetLaunchBrowser_Success() { - var result = Subject.LaunchBrowser; - result.Should().Be(true); } @@ -97,10 +91,8 @@ public void GetPort_Success() { const int value = 8989; - var result = Subject.Port; - result.Should().Be(value); } @@ -110,10 +102,8 @@ public void SetValue_bool() const string key = "LaunchBrowser"; const bool value = false; - Subject.SetValue(key, value); - var result = Subject.LaunchBrowser; result.Should().Be(value); } @@ -124,10 +114,8 @@ public void SetValue_int() const string key = "Port"; const int value = 12345; - Subject.SetValue(key, value); - var result = Subject.Port; result.Should().Be(value); } @@ -138,10 +126,8 @@ public void GetValue_New_Key() const string key = "Hello"; const string value = "World"; - var result = Subject.GetValue(key, value); - result.Should().Be(value); } @@ -178,7 +164,6 @@ public void SaveDictionary_should_only_save_specified_values() dic["SslPort"] = origSslPort; Subject.SaveConfigDictionary(dic); - dic = new Dictionary(); dic["SslPort"] = sslPort; Subject.SaveConfigDictionary(dic); @@ -213,4 +198,4 @@ public void should_throw_if_config_file_contains_invalid_xml() Assert.Throws(() => Subject.GetValue("key", "value")); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common.Test/DiskTests/DirectoryLookupServiceFixture.cs b/src/NzbDrone.Common.Test/DiskTests/DirectoryLookupServiceFixture.cs index 70b68ca0a..78aa99f7d 100644 --- a/src/NzbDrone.Common.Test/DiskTests/DirectoryLookupServiceFixture.cs +++ b/src/NzbDrone.Common.Test/DiskTests/DirectoryLookupServiceFixture.cs @@ -76,7 +76,7 @@ public void should_not_contain_recycling_bin_or_system_volume_information_for_ro .Returns(_folders); var result = Subject.LookupContents(root, false, false); - + result.Directories.Should().HaveCount(_folders.Count - 3); result.Directories.Should().NotContain(f => f.Name == RECYCLING_BIN); diff --git a/src/NzbDrone.Common.Test/DiskTests/DiskProviderFixtureBase.cs b/src/NzbDrone.Common.Test/DiskTests/DiskProviderFixtureBase.cs index 77f048f33..b1994d103 100644 --- a/src/NzbDrone.Common.Test/DiskTests/DiskProviderFixtureBase.cs +++ b/src/NzbDrone.Common.Test/DiskTests/DiskProviderFixtureBase.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.IO; using FluentAssertions; using NUnit.Framework; @@ -7,7 +7,8 @@ namespace NzbDrone.Common.Test.DiskTests { - public abstract class DiskProviderFixtureBase : TestBase where TSubject : class, IDiskProvider + public abstract class DiskProviderFixtureBase : TestBase + where TSubject : class, IDiskProvider { [Test] [Retry(5)] @@ -154,7 +155,7 @@ public void folder_should_return_correct_value_for_last_write() public void should_return_false_for_unlocked_file() { var testFile = GetTempFilePath(); - Subject.WriteAllText(testFile, new Guid().ToString()); + Subject.WriteAllText(testFile, default(Guid).ToString()); Subject.IsFileLocked(testFile).Should().BeFalse(); } @@ -163,7 +164,7 @@ public void should_return_false_for_unlocked_file() public void should_return_false_for_unlocked_and_readonly_file() { var testFile = GetTempFilePath(); - Subject.WriteAllText(testFile, new Guid().ToString()); + Subject.WriteAllText(testFile, default(Guid).ToString()); File.SetAttributes(testFile, FileAttributes.ReadOnly); @@ -174,7 +175,7 @@ public void should_return_false_for_unlocked_and_readonly_file() public void should_return_true_for_unlocked_file() { var testFile = GetTempFilePath(); - Subject.WriteAllText(testFile, new Guid().ToString()); + Subject.WriteAllText(testFile, default(Guid).ToString()); using (var file = File.OpenWrite(testFile)) { @@ -186,7 +187,7 @@ public void should_return_true_for_unlocked_file() public void should_be_able_to_set_permission_from_parrent() { var testFile = GetTempFilePath(); - Subject.WriteAllText(testFile, new Guid().ToString()); + Subject.WriteAllText(testFile, default(Guid).ToString()); Subject.InheritFolderPermissions(testFile); } @@ -195,7 +196,7 @@ public void should_be_able_to_set_permission_from_parrent() public void should_be_set_last_file_write() { var testFile = GetTempFilePath(); - Subject.WriteAllText(testFile, new Guid().ToString()); + Subject.WriteAllText(testFile, default(Guid).ToString()); var lastWriteTime = DateTime.SpecifyKind(new DateTime(2012, 1, 2), DateTimeKind.Utc); diff --git a/src/NzbDrone.Common.Test/DiskTests/DiskTransferServiceFixture.cs b/src/NzbDrone.Common.Test/DiskTests/DiskTransferServiceFixture.cs index 2be842067..084bd6752 100644 --- a/src/NzbDrone.Common.Test/DiskTests/DiskTransferServiceFixture.cs +++ b/src/NzbDrone.Common.Test/DiskTests/DiskTransferServiceFixture.cs @@ -751,7 +751,9 @@ private void WithExistingFolder(string path, bool exists = true) { var dir = Path.GetDirectoryName(path); if (exists && dir.IsNotNullOrWhiteSpace()) + { WithExistingFolder(dir); + } Mocker.GetMock() .Setup(v => v.FolderExists(path)) @@ -762,7 +764,9 @@ private void WithExistingFile(string path, bool exists = true, int size = 1000) { var dir = Path.GetDirectoryName(path); if (exists && dir.IsNotNullOrWhiteSpace()) + { WithExistingFolder(dir); + } Mocker.GetMock() .Setup(v => v.FileExists(path)) @@ -816,7 +820,6 @@ private void WithEmulatedDiskProvider() WithExistingFile(v, false); }); - Mocker.GetMock() .Setup(v => v.FolderExists(It.IsAny())) .Returns(false); @@ -834,6 +837,7 @@ private void WithEmulatedDiskProvider() { WithExistingFolder(s, false); WithExistingFolder(d); + // Note: Should also deal with the files. }); @@ -842,6 +846,7 @@ private void WithEmulatedDiskProvider() .Callback((f, r) => { WithExistingFolder(f, false); + // Note: Should also deal with the files. }); @@ -907,8 +912,13 @@ private void WithRealDiskProvider() Mocker.GetMock() .Setup(v => v.MoveFile(It.IsAny(), It.IsAny(), It.IsAny())) - .Callback((s,d,o) => { - if (File.Exists(d) && o) File.Delete(d); + .Callback((s, d, o) => + { + if (File.Exists(d) && o) + { + File.Delete(d); + } + File.Move(s, d); }); diff --git a/src/NzbDrone.Common.Test/DiskTests/FreeSpaceFixtureBase.cs b/src/NzbDrone.Common.Test/DiskTests/FreeSpaceFixtureBase.cs index bf6d8ec27..2b4d356cd 100644 --- a/src/NzbDrone.Common.Test/DiskTests/FreeSpaceFixtureBase.cs +++ b/src/NzbDrone.Common.Test/DiskTests/FreeSpaceFixtureBase.cs @@ -7,7 +7,8 @@ namespace NzbDrone.Common.Test.DiskTests { - public abstract class FreeSpaceFixtureBase : TestBase where TSubject : class, IDiskProvider + public abstract class FreeSpaceFixtureBase : TestBase + where TSubject : class, IDiskProvider { [Test] public void should_get_free_space_for_folder() diff --git a/src/NzbDrone.Common.Test/EnsureTest/PathExtensionFixture.cs b/src/NzbDrone.Common.Test/EnsureTest/PathExtensionFixture.cs index 9d51e806f..0ff119ec2 100644 --- a/src/NzbDrone.Common.Test/EnsureTest/PathExtensionFixture.cs +++ b/src/NzbDrone.Common.Test/EnsureTest/PathExtensionFixture.cs @@ -15,7 +15,6 @@ public void EnsureWindowsPath(string path) Ensure.That(path, () => path).IsValidPath(); } - [TestCase(@"/var/user/file with, comma.mkv")] public void EnsureLinuxPath(string path) { diff --git a/src/NzbDrone.Common.Test/EnvironmentProviderTest.cs b/src/NzbDrone.Common.Test/EnvironmentProviderTest.cs index dd7e8fcf0..1d9936a8b 100644 --- a/src/NzbDrone.Common.Test/EnvironmentProviderTest.cs +++ b/src/NzbDrone.Common.Test/EnvironmentProviderTest.cs @@ -10,13 +10,11 @@ namespace NzbDrone.Common.Test [TestFixture] public class IAppDirectoryInfoTest : TestBase { - [Test] public void StartupPath_should_not_be_empty() { Subject.StartUpFolder.Should().NotBeNullOrWhiteSpace(); Path.IsPathRooted(Subject.StartUpFolder).Should().BeTrue("Path is not rooted"); - } [Test] diff --git a/src/NzbDrone.Common.Test/EnvironmentTests/EnvironmentProviderTest.cs b/src/NzbDrone.Common.Test/EnvironmentTests/EnvironmentProviderTest.cs index 826cf9520..a4f0bdc6d 100644 --- a/src/NzbDrone.Common.Test/EnvironmentTests/EnvironmentProviderTest.cs +++ b/src/NzbDrone.Common.Test/EnvironmentTests/EnvironmentProviderTest.cs @@ -9,13 +9,11 @@ namespace NzbDrone.Common.Test.EnvironmentTests [TestFixture] public class BuildInfoTest : TestBase { - [TestCase("0.0.0.0")] [TestCase("1.0.0.0")] public void Application_version_should_not_be_default(string version) { BuildInfo.Version.Should().NotBe(new Version(version)); } - } } diff --git a/src/NzbDrone.Common.Test/EnvironmentTests/StartupArgumentsFixture.cs b/src/NzbDrone.Common.Test/EnvironmentTests/StartupArgumentsFixture.cs index c34c0cf70..07df9c79e 100644 --- a/src/NzbDrone.Common.Test/EnvironmentTests/StartupArgumentsFixture.cs +++ b/src/NzbDrone.Common.Test/EnvironmentTests/StartupArgumentsFixture.cs @@ -26,7 +26,6 @@ public void should_parse_single_flag(string arg) args.Flags.Contains("t").Should().BeTrue(); } - [TestCase("/key=value")] [TestCase("/KEY=value")] [TestCase(" /key=\"value\"")] @@ -37,7 +36,6 @@ public void should_parse_args_with_alues(string arg) args.Args["key"].Should().Be("value"); } - [TestCase("/data=test", "/data=test")] [TestCase("/Data=/a/b/c", "/data=/a/b/c")] public void should_preserver_data(string arg, string preserved) @@ -55,7 +53,6 @@ public void should_preserver_no_browser(string arg, string preserved) args.PreservedArguments.Should().Be(preserved); } - [Test] public void should_preserver_both() { diff --git a/src/NzbDrone.Common.Test/ExtensionTests/IEnumerableExtensionTests/ExceptByFixture.cs b/src/NzbDrone.Common.Test/ExtensionTests/IEnumerableExtensionTests/ExceptByFixture.cs index 1688fd8c4..2b7ef935b 100644 --- a/src/NzbDrone.Common.Test/ExtensionTests/IEnumerableExtensionTests/ExceptByFixture.cs +++ b/src/NzbDrone.Common.Test/ExtensionTests/IEnumerableExtensionTests/ExceptByFixture.cs @@ -56,7 +56,7 @@ public void should_return_objects_that_do_not_have_a_match_in_the_second_list() var result = first.ExceptBy(o => o.Prop1, second, o => o.Prop1, StringComparer.InvariantCultureIgnoreCase).ToList(); result.Should().HaveCount(1); - result.First().GetType().Should().Be(typeof (Object1)); + result.First().GetType().Should().Be(typeof(Object1)); result.First().Prop1.Should().Be("two"); } } diff --git a/src/NzbDrone.Common.Test/ExtensionTests/IPAddressExtensionsFixture.cs b/src/NzbDrone.Common.Test/ExtensionTests/IPAddressExtensionsFixture.cs index 978742af3..f7ed71f94 100644 --- a/src/NzbDrone.Common.Test/ExtensionTests/IPAddressExtensionsFixture.cs +++ b/src/NzbDrone.Common.Test/ExtensionTests/IPAddressExtensionsFixture.cs @@ -24,7 +24,6 @@ public void should_return_true_for_local_ip_address(string ipAddress) public void should_return_false_for_public_ip_address(string ipAddress) { IPAddress.Parse(ipAddress).IsLocalAddress().Should().BeFalse(); - } } } diff --git a/src/NzbDrone.Common.Test/HashUtilFixture.cs b/src/NzbDrone.Common.Test/HashUtilFixture.cs index 02869fa24..d487b78ba 100644 --- a/src/NzbDrone.Common.Test/HashUtilFixture.cs +++ b/src/NzbDrone.Common.Test/HashUtilFixture.cs @@ -18,4 +18,4 @@ public void should_create_the_same_id() HashUtil.AnonymousToken().Should().Be(HashUtil.AnonymousToken()); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common.Test/Http/HttpClientFixture.cs b/src/NzbDrone.Common.Test/Http/HttpClientFixture.cs index e11c6a2a6..2fa05cea4 100644 --- a/src/NzbDrone.Common.Test/Http/HttpClientFixture.cs +++ b/src/NzbDrone.Common.Test/Http/HttpClientFixture.cs @@ -23,7 +23,8 @@ namespace NzbDrone.Common.Test.Http [Ignore("httpbin is bugged")] [IntegrationTest] [TestFixture(typeof(ManagedHttpDispatcher))] - public class HttpClientFixture : TestBase where TDispatcher : IHttpDispatcher + public class HttpClientFixture : TestBase + where TDispatcher : IHttpDispatcher { private string[] _httpBinHosts; private int _httpBinSleep; @@ -35,6 +36,7 @@ public class HttpClientFixture : TestBase where TDispat public void FixtureSetUp() { var candidates = new[] { "eu.httpbin.org", /*"httpbin.org",*/ "www.httpbin.org" }; + // httpbin.org is broken right now, occassionally redirecting to https if it's unavailable. _httpBinHosts = candidates.Where(IsTestSiteAvailable).ToArray(); @@ -49,7 +51,10 @@ private bool IsTestSiteAvailable(string site) { var req = WebRequest.Create($"http://{site}/get") as HttpWebRequest; var res = req.GetResponse() as HttpWebResponse; - if (res.StatusCode != HttpStatusCode.OK) return false; + if (res.StatusCode != HttpStatusCode.OK) + { + return false; + } try { @@ -61,7 +66,10 @@ private bool IsTestSiteAvailable(string site) res = ex.Response as HttpWebResponse; } - if (res == null || res.StatusCode != (HttpStatusCode)429) return false; + if (res == null || res.StatusCode != (HttpStatusCode)429) + { + return false; + } return true; } @@ -688,7 +696,7 @@ public void should_throw_on_http429_too_many_requests() [Test] public void should_call_interceptor() { - Mocker.SetConstant>(new [] { Mocker.GetMock().Object }); + Mocker.SetConstant>(new[] { Mocker.GetMock().Object }); Mocker.GetMock() .Setup(v => v.PreRequest(It.IsAny())) diff --git a/src/NzbDrone.Common.Test/Http/HttpHeaderFixture.cs b/src/NzbDrone.Common.Test/Http/HttpHeaderFixture.cs index e0a22072e..e5221e408 100644 --- a/src/NzbDrone.Common.Test/Http/HttpHeaderFixture.cs +++ b/src/NzbDrone.Common.Test/Http/HttpHeaderFixture.cs @@ -1,11 +1,11 @@ -using NUnit.Framework; -using FluentAssertions; -using NzbDrone.Test.Common; -using System; -using System.Text; -using NzbDrone.Common.Http; +using System; using System.Collections.Specialized; using System.Linq; +using System.Text; +using FluentAssertions; +using NUnit.Framework; +using NzbDrone.Common.Http; +using NzbDrone.Test.Common; namespace NzbDrone.Common.Test.Http { diff --git a/src/NzbDrone.Common.Test/Http/HttpRequestBuilderFixture.cs b/src/NzbDrone.Common.Test/Http/HttpRequestBuilderFixture.cs index 8bc2a265b..4af9bb501 100644 --- a/src/NzbDrone.Common.Test/Http/HttpRequestBuilderFixture.cs +++ b/src/NzbDrone.Common.Test/Http/HttpRequestBuilderFixture.cs @@ -35,7 +35,6 @@ public void should_remove_duplicated_slashes() var request = builder.Resource("/v1/").Build(); request.Url.FullUri.Should().Be("http://domain/v1/"); - } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common.Test/Http/HttpRequestFixture.cs b/src/NzbDrone.Common.Test/Http/HttpRequestFixture.cs index 94b55f9f3..060504beb 100644 --- a/src/NzbDrone.Common.Test/Http/HttpRequestFixture.cs +++ b/src/NzbDrone.Common.Test/Http/HttpRequestFixture.cs @@ -6,4 +6,4 @@ namespace NzbDrone.Common.Test.Http public class HttpRequestFixture { } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common.Test/Http/UserAgentBuilderFixture.cs b/src/NzbDrone.Common.Test/Http/UserAgentBuilderFixture.cs index 6b99793ea..5b764c206 100644 --- a/src/NzbDrone.Common.Test/Http/UserAgentBuilderFixture.cs +++ b/src/NzbDrone.Common.Test/Http/UserAgentBuilderFixture.cs @@ -27,4 +27,4 @@ public void should_get_use_os_family_if_name_is_null() Subject.GetUserAgent(false).Should().NotBeNullOrWhiteSpace(); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common.Test/InstrumentationTests/CleanseLogMessageFixture.cs b/src/NzbDrone.Common.Test/InstrumentationTests/CleanseLogMessageFixture.cs index 35da0066b..f01a72912 100644 --- a/src/NzbDrone.Common.Test/InstrumentationTests/CleanseLogMessageFixture.cs +++ b/src/NzbDrone.Common.Test/InstrumentationTests/CleanseLogMessageFixture.cs @@ -1,6 +1,6 @@ -using NUnit.Framework; -using NzbDrone.Common.Instrumentation; using FluentAssertions; +using NUnit.Framework; +using NzbDrone.Common.Instrumentation; namespace NzbDrone.Common.Test.InstrumentationTests { @@ -16,9 +16,11 @@ public class CleanseLogMessageFixture [TestCase(@"https://baconbits.org/feeds.php?feed=torrents_tv&user=12345&auth=2b51db35e1910123321025a12b9933d2&passkey=mySecret&authkey=2b51db35e1910123321025a12b9933d2")] [TestCase(@"http://127.0.0.1:9117/dl/indexername?jackett_apikey=flwjiefewklfjacketmySecretsdfldskjfsdlk&path=we0re9f0sdfbase64sfdkfjsdlfjk&file=The+Torrent+File+Name.torrent")] [TestCase(@"http://nzb.su/getnzb/2b51db35e1912ffc138825a12b9933d2.nzb&i=37292&r=2b51db35e1910123321025a12b9933d2")] + // NzbGet [TestCase(@"{ ""Name"" : ""ControlUsername"", ""Value"" : ""mySecret"" }, { ""Name"" : ""ControlPassword"", ""Value"" : ""mySecret"" }, ")] [TestCase(@"{ ""Name"" : ""Server1.Username"", ""Value"" : ""mySecret"" }, { ""Name"" : ""Server1.Password"", ""Value"" : ""mySecret"" }, ")] + // Sabnzbd [TestCase(@"http://127.0.0.1:1234/api/call?vv=1&apikey=mySecret")] [TestCase(@"http://127.0.0.1:1234/api/call?vv=1&ma_username=mySecret&ma_password=mySecret")] @@ -29,6 +31,7 @@ public class CleanseLogMessageFixture [TestCase(@"""misc"":{""username"":""mySecret"",""api_key"":""mySecret"",""password"":""mySecret"",""nzb_key"":""mySecret""}")] [TestCase(@"""servers"":[{""username"":""mySecret"",""password"":""mySecret""}]")] [TestCase(@"""misc"":{""email_account"":""mySecret"",""email_to"":[],""email_from"":"""",""email_pwd"":""mySecret""}")] + // uTorrent [TestCase(@"http://localhost:9091/gui/?token=wThmph5l0ZXfH-a6WOA4lqiLvyjCP0FpMrMeXmySecret_VXBO11HoKL751MAAAAA&list=1")] [TestCase(@",[""boss_key"",0,""mySecret"",{""access"":""Y""}],[""boss_key_salt"",0,""mySecret"",{""access"":""W""}]")] @@ -36,22 +39,28 @@ public class CleanseLogMessageFixture [TestCase(@",[""webui.uconnect_username"",2,""mySecret"",{""access"":""Y""}],[""webui.uconnect_password"",2,""mySecret"",{""access"":""Y""}]")] [TestCase(@",[""proxy.proxy"",2,""mySecret"",{""access"":""Y""}]")] [TestCase(@",[""proxy.username"",2,""mySecret"",{""access"":""Y""}],[""proxy.password"",2,""mySecret"",{""access"":""Y""}]")] + // Deluge [TestCase(@",{""download_location"": ""C:\Users\\mySecret mySecret\\Downloads""}")] [TestCase(@",{""download_location"": ""/home/mySecret/Downloads""}")] [TestCase(@"auth.login(""mySecret"")")] + // Download Station [TestCase(@"webapi/entry.cgi?api=(removed)&version=2&method=login&account=01233210&passwd=mySecret&format=sid&session=DownloadStation")] + // BroadcastheNet [TestCase(@"method: ""getTorrents"", ""params"": [ ""mySecret"",")] [TestCase(@"getTorrents(""mySecret"", [asdfasdf], 100, 0)")] [TestCase(@"""DownloadURL"":""https:\/\/broadcasthe.net\/torrents.php?action=download&id=123&authkey=mySecret&torrent_pass=mySecret""")] + // Plex [TestCase(@" http://localhost:32400/library/metadata/12345/refresh?X-Plex-Client-Identifier=1234530f-422f-4aac-b6b3-01233210aaaa&X-Plex-Product=Sonarr&X-Plex-Platform=Windows&X-Plex-Platform-Version=7&X-Plex-Device-Name=Sonarr&X-Plex-Version=3.0.3.833&X-Plex-Token=mySecret")] + // Internal [TestCase(@"OutputPath=/home/mySecret/Downloads")] [TestCase("Hardlinking episode file: /home/mySecret/Downloads to /media/abc.mkv")] [TestCase("Hardlink '/home/mySecret/Downloads/abs.mkv' to '/media/abc.mkv' failed.")] + // Announce URLs (passkeys) Magnet & Tracker [TestCase(@"magnet_uri"":""magnet:?xt=urn:btih:9pr04sgkillroyimaveql2tyu8xyui&dn=&tr=https%3a%2f%2fxxx.yyy%2f9pr04sg601233210imaveql2tyu8xyui%2fannounce""}")] [TestCase(@"magnet_uri"":""magnet:?xt=urn:btih:9pr04sgkillroyimaveql2tyu8xyui&dn=&tr=https%3a%2f%2fxxx.yyy%2ftracker.php%2f9pr04sg601233210imaveql2tyu8xyui%2fannounce""}")] @@ -62,6 +71,7 @@ public class CleanseLogMessageFixture [TestCase(@"tracker"":""https://xxx.yyy/announce/9pr04sg601233210imaveql2tyu8xyui""}")] [TestCase(@"tracker"":""https://xxx.yyy/announce.php?passkey=9pr04sg601233210imaveql2tyu8xyui""}")] [TestCase(@"tracker"":""http://xxx.yyy/announce.php?passkey=9pr04sg601233210imaveql2tyu8xyui"",""info"":""http://xxx.yyy/info?a=b""")] + // Webhooks - Notifiarr [TestCase(@"https://xxx.yyy/api/v1/notification/sonarr/9pr04sg6-0123-3210-imav-eql2tyu8xyui")] diff --git a/src/NzbDrone.Common.Test/InstrumentationTests/SentryTargetFixture.cs b/src/NzbDrone.Common.Test/InstrumentationTests/SentryTargetFixture.cs index 70c701b74..75c6f0b52 100644 --- a/src/NzbDrone.Common.Test/InstrumentationTests/SentryTargetFixture.cs +++ b/src/NzbDrone.Common.Test/InstrumentationTests/SentryTargetFixture.cs @@ -1,24 +1,25 @@ -using NUnit.Framework; -using FluentAssertions; -using NzbDrone.Common.Instrumentation.Sentry; using System; -using NLog; -using NzbDrone.Test.Common; using System.Globalization; using System.Linq; +using FluentAssertions; +using NLog; +using NUnit.Framework; +using NzbDrone.Common.Instrumentation.Sentry; +using NzbDrone.Test.Common; namespace NzbDrone.Common.Test.InstrumentationTests { [TestFixture] public class SentryTargetFixture : TestBase { - private SentryTarget Subject; + private SentryTarget _subject; private static LogLevel[] AllLevels = LogLevel.AllLevels.ToArray(); private static LogLevel[] SentryLevels = LogLevel.AllLevels.Where(x => x >= LogLevel.Error).ToArray(); private static LogLevel[] OtherLevels = AllLevels.Except(SentryLevels).ToArray(); - private static Exception[] FilteredExceptions = new Exception[] { + private static Exception[] FilteredExceptions = new Exception[] + { new UnauthorizedAccessException(), new TinyIoC.TinyIoCResolutionException(typeof(string)) }; @@ -26,7 +27,7 @@ public class SentryTargetFixture : TestBase [SetUp] public void Setup() { - Subject = new SentryTarget("https://aaaaaaaaaaaaaaaaaaaaaaaaaa@sentry.io/111111"); + _subject = new SentryTarget("https://aaaaaaaaaaaaaaaaaaaaaaaaaa@sentry.io/111111"); } private LogEventInfo GivenLogEvent(LogLevel level, Exception ex, string message) @@ -34,44 +35,50 @@ private LogEventInfo GivenLogEvent(LogLevel level, Exception ex, string message) return LogEventInfo.Create(level, "SentryTest", ex, CultureInfo.InvariantCulture, message); } - [Test, TestCaseSource("AllLevels")] + [Test] + [TestCaseSource("AllLevels")] public void log_without_error_is_not_sentry_event(LogLevel level) { - Subject.IsSentryMessage(GivenLogEvent(level, null, "test")).Should().BeFalse(); + _subject.IsSentryMessage(GivenLogEvent(level, null, "test")).Should().BeFalse(); } - [Test, TestCaseSource("SentryLevels")] + [Test] + [TestCaseSource("SentryLevels")] public void error_or_worse_with_exception_is_sentry_event(LogLevel level) { - Subject.IsSentryMessage(GivenLogEvent(level, new Exception(), "test")).Should().BeTrue(); + _subject.IsSentryMessage(GivenLogEvent(level, new Exception(), "test")).Should().BeTrue(); } - [Test, TestCaseSource("OtherLevels")] + [Test] + [TestCaseSource("OtherLevels")] public void less_than_error_with_exception_is_not_sentry_event(LogLevel level) { - Subject.IsSentryMessage(GivenLogEvent(level, new Exception(), "test")).Should().BeFalse(); + _subject.IsSentryMessage(GivenLogEvent(level, new Exception(), "test")).Should().BeFalse(); } - [Test, TestCaseSource("FilteredExceptions")] + [Test] + [TestCaseSource("FilteredExceptions")] public void should_filter_event_for_filtered_exception_types(Exception ex) { var log = GivenLogEvent(LogLevel.Error, ex, "test"); - Subject.IsSentryMessage(log).Should().BeFalse(); + _subject.IsSentryMessage(log).Should().BeFalse(); } - [Test, TestCaseSource("FilteredExceptions")] + [Test] + [TestCaseSource("FilteredExceptions")] public void should_not_filter_event_for_filtered_exception_types_if_filtering_disabled(Exception ex) { - Subject.FilterEvents = false; + _subject.FilterEvents = false; var log = GivenLogEvent(LogLevel.Error, ex, "test"); - Subject.IsSentryMessage(log).Should().BeTrue(); + _subject.IsSentryMessage(log).Should().BeTrue(); } - [Test, TestCaseSource(typeof(SentryTarget), "FilteredExceptionMessages")] + [Test] + [TestCaseSource(typeof(SentryTarget), "FilteredExceptionMessages")] public void should_filter_event_for_filtered_exception_messages(string message) { var log = GivenLogEvent(LogLevel.Error, new Exception("aaaaaaa" + message + "bbbbbbb"), "test"); - Subject.IsSentryMessage(log).Should().BeFalse(); + _subject.IsSentryMessage(log).Should().BeFalse(); } [TestCase("A message that isn't filtered")] @@ -79,7 +86,7 @@ public void should_filter_event_for_filtered_exception_messages(string message) public void should_not_filter_event_for_exception_messages_that_are_not_filtered(string message) { var log = GivenLogEvent(LogLevel.Error, new Exception(message), "test"); - Subject.IsSentryMessage(log).Should().BeTrue(); + _subject.IsSentryMessage(log).Should().BeTrue(); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common.Test/OsPathFixture.cs b/src/NzbDrone.Common.Test/OsPathFixture.cs index 992ea11fd..c31abefc7 100644 --- a/src/NzbDrone.Common.Test/OsPathFixture.cs +++ b/src/NzbDrone.Common.Test/OsPathFixture.cs @@ -1,7 +1,7 @@ -using NUnit.Framework; +using FluentAssertions; +using NUnit.Framework; using NzbDrone.Common.Disk; using NzbDrone.Test.Common; -using FluentAssertions; namespace NzbDrone.Common.Test { diff --git a/src/NzbDrone.Common.Test/PathExtensionFixture.cs b/src/NzbDrone.Common.Test/PathExtensionFixture.cs index f86bceac3..2744271fc 100644 --- a/src/NzbDrone.Common.Test/PathExtensionFixture.cs +++ b/src/NzbDrone.Common.Test/PathExtensionFixture.cs @@ -110,6 +110,7 @@ public void should_return_true_when_folder_is_parent_of_a_file() _parent.IsParentPath(path).Should().BeTrue(); } + [TestCase(@"C:\Test\", @"C:\Test\mydir")] [TestCase(@"C:\Test\", @"C:\Test\mydir\")] [TestCase(@"C:\Test", @"C:\Test\30.Rock.S01E01.Pilot.avi")] @@ -198,10 +199,9 @@ public void normalize_path_exception_null() public void get_actual_casing_for_none_existing_file_return_partially_fixed_result() { WindowsOnly(); - "C:\\WINDOWS\\invalidfile.exe".GetActualCasing().Should().Be("C:\\Windows\\invalidfile.exe"); + "C:\\WINDOWS\\invalidfile.exe".GetActualCasing().Should().Be("C:\\Windows\\invalidfile.exe"); } - [Test] public void get_actual_casing_for_none_existing_folder_return_partially_fixed_result() { @@ -218,7 +218,6 @@ public void get_actual_casing_should_return_actual_casing_for_local_file_in_wind path.ToLower().GetActualCasing().Should().Be(path); } - [Test] public void get_actual_casing_should_return_actual_casing_for_local_dir_in_windows() { diff --git a/src/NzbDrone.Common.Test/ProcessProviderFixture.cs b/src/NzbDrone.Common.Test/ProcessProviderFixture.cs index 796f63382..dbf5d8a59 100644 --- a/src/NzbDrone.Common.Test/ProcessProviderFixture.cs +++ b/src/NzbDrone.Common.Test/ProcessProviderFixture.cs @@ -18,7 +18,6 @@ namespace NzbDrone.Common.Test [TestFixture] public class ProcessProviderFixture : TestBase { - [SetUp] public void Setup() { @@ -44,7 +43,6 @@ public void TearDown() { TestLogger.Warn(ex, "{0} when killing process", ex.Message); } - }); } @@ -134,7 +132,6 @@ public void Should_be_able_to_start_python() } } - [Test] [Platform(Exclude = "MacOsX")] [Retry(3)] diff --git a/src/NzbDrone.Common.Test/ServiceFactoryFixture.cs b/src/NzbDrone.Common.Test/ServiceFactoryFixture.cs index 1c9dbe102..9dfdde396 100644 --- a/src/NzbDrone.Common.Test/ServiceFactoryFixture.cs +++ b/src/NzbDrone.Common.Test/ServiceFactoryFixture.cs @@ -29,4 +29,4 @@ public void event_handlers_should_be_unique() handlers.Should().OnlyHaveUniqueItems(); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common.Test/ServiceProviderFixture.cs b/src/NzbDrone.Common.Test/ServiceProviderFixture.cs index 93ee3d703..fd48c49ce 100644 --- a/src/NzbDrone.Common.Test/ServiceProviderFixture.cs +++ b/src/NzbDrone.Common.Test/ServiceProviderFixture.cs @@ -36,7 +36,6 @@ public void TearDown() } } - private void CleanupService() { if (Subject.ServiceExist(TEMP_SERVICE_NAME)) @@ -62,7 +61,6 @@ public void Exists_should_not_find_random_service() Subject.ServiceExist("random_service_name").Should().BeFalse(); } - [Test] public void Service_should_be_installed_and_then_uninstalled() { @@ -123,7 +121,6 @@ public void should_throw_if_starting_a_running_service() Subject.Start(ALWAYS_INSTALLED_SERVICE); Assert.Throws(() => Subject.Start(ALWAYS_INSTALLED_SERVICE)); - ExceptionVerification.ExpectedWarns(1); } @@ -133,15 +130,14 @@ public void Should_log_warn_if_on_stop_if_service_is_already_stopped() Subject.GetService(ALWAYS_INSTALLED_SERVICE).Status .Should().NotBe(ServiceControllerStatus.Running); - Subject.Stop(ALWAYS_INSTALLED_SERVICE); - Subject.GetService(ALWAYS_INSTALLED_SERVICE).Status .Should().Be(ServiceControllerStatus.Stopped); ExceptionVerification.ExpectedWarns(1); } + private static bool IsAnAdministrator() { var principal = new WindowsPrincipal(WindowsIdentity.GetCurrent()); diff --git a/src/NzbDrone.Common.Test/TPLTests/DebouncerFixture.cs b/src/NzbDrone.Common.Test/TPLTests/DebouncerFixture.cs index 29e7bb7ec..c8844b2f3 100644 --- a/src/NzbDrone.Common.Test/TPLTests/DebouncerFixture.cs +++ b/src/NzbDrone.Common.Test/TPLTests/DebouncerFixture.cs @@ -19,7 +19,6 @@ public void Hit() } } - [Test] [Retry(3)] public void should_hold_the_call_for_debounce_duration() @@ -33,11 +32,9 @@ public void should_hold_the_call_for_debounce_duration() counter.Count.Should().Be(0); - Thread.Sleep(100); counter.Count.Should().Be(1); - } [Test] @@ -53,7 +50,6 @@ public void should_throttle_calls() counter.Count.Should().Be(0); - Thread.Sleep(200); debounceFunction.Execute(); @@ -63,7 +59,6 @@ public void should_throttle_calls() Thread.Sleep(200); counter.Count.Should().Be(2); - } [Test] @@ -126,4 +121,4 @@ public void should_handle_pause_reentrancy() counter.Count.Should().Be(1); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common.Test/TPLTests/RateLimitServiceFixture.cs b/src/NzbDrone.Common.Test/TPLTests/RateLimitServiceFixture.cs index b2ff87a06..a92eed1f1 100644 --- a/src/NzbDrone.Common.Test/TPLTests/RateLimitServiceFixture.cs +++ b/src/NzbDrone.Common.Test/TPLTests/RateLimitServiceFixture.cs @@ -1,11 +1,11 @@ using System; using System.Collections.Concurrent; using System.Diagnostics; +using FluentAssertions; using NUnit.Framework; using NzbDrone.Common.Cache; using NzbDrone.Common.TPL; using NzbDrone.Test.Common; -using FluentAssertions; namespace NzbDrone.Common.Test.TPLTests { diff --git a/src/NzbDrone.Common/ArchiveService.cs b/src/NzbDrone.Common/ArchiveService.cs index 1871bd8ad..39745eb3b 100644 --- a/src/NzbDrone.Common/ArchiveService.cs +++ b/src/NzbDrone.Common/ArchiveService.cs @@ -73,7 +73,9 @@ private void ExtractZip(string compressedFile, string destination) { continue; // Ignore directories } + string entryFileName = zipEntry.Name; + // to remove the folder from the entry:- entryFileName = Path.GetFileName(entryFileName); // Optionally match entrynames against a selection list here to skip as desired. // The unpacked length is available in the zipEntry.Size property. diff --git a/src/NzbDrone.Common/Cache/CacheManager.cs b/src/NzbDrone.Common/Cache/CacheManager.cs index 7b7f0d3e0..7d6bb128f 100644 --- a/src/NzbDrone.Common/Cache/CacheManager.cs +++ b/src/NzbDrone.Common/Cache/CacheManager.cs @@ -21,7 +21,6 @@ public class CacheManager : ICacheManager public CacheManager() { _cache = new Cached(); - } public void Clear() @@ -61,4 +60,4 @@ public ICachedDictionary GetCacheDictionary(Type host, string name, Func)_cache.Get("dict_" + host.FullName + "_" + name, () => new CachedDictionary(fetchFunc, lifeTime)); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common/Cache/Cached.cs b/src/NzbDrone.Common/Cache/Cached.cs index db7f8d5a3..b0dfc3eb2 100644 --- a/src/NzbDrone.Common/Cache/Cached.cs +++ b/src/NzbDrone.Common/Cache/Cached.cs @@ -7,7 +7,6 @@ namespace NzbDrone.Common.Cache { - public class Cached : ICached { private class CacheItem @@ -144,6 +143,5 @@ private bool TryRemove(string key, CacheItem value) return collection.Remove(new KeyValuePair(key, value)); } - } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common/Cache/CachedDictionary.cs b/src/NzbDrone.Common/Cache/CachedDictionary.cs index 7bbda022a..3d860f831 100644 --- a/src/NzbDrone.Common/Cache/CachedDictionary.cs +++ b/src/NzbDrone.Common/Cache/CachedDictionary.cs @@ -5,7 +5,6 @@ namespace NzbDrone.Common.Cache { - public class CachedDictionary : ICachedDictionary { private readonly Func> _fetchFunc; diff --git a/src/NzbDrone.Common/Cache/ICached.cs b/src/NzbDrone.Common/Cache/ICached.cs index 179491a4f..e64b1637c 100644 --- a/src/NzbDrone.Common/Cache/ICached.cs +++ b/src/NzbDrone.Common/Cache/ICached.cs @@ -19,4 +19,4 @@ public interface ICached : ICached ICollection Values { get; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common/Composition/Container.cs b/src/NzbDrone.Common/Composition/Container.cs index 3b9b2c8fe..6ae1e4bfa 100644 --- a/src/NzbDrone.Common/Composition/Container.cs +++ b/src/NzbDrone.Common/Composition/Container.cs @@ -24,12 +24,14 @@ public void Register() _container.Register(); } - public void Register(T instance) where T : class + public void Register(T instance) + where T : class { _container.Register(instance); } - public T Resolve() where T : class + public T Resolve() + where T : class { return _container.Resolve(); } @@ -44,7 +46,8 @@ public void Register(Type serviceType, Type implementationType) _container.Register(serviceType, implementationType); } - public void Register(Func factory) where TService : class + public void Register(Func factory) + where TService : class { _container.Register((c, n) => factory(this)); } @@ -67,7 +70,8 @@ public void RegisterSingleton(Type service, Type implementation) }); } - public IEnumerable ResolveAll() where T : class + public IEnumerable ResolveAll() + where T : class { return _container.ResolveAll(); } @@ -103,8 +107,7 @@ public IEnumerable GetImplementations(Type contractType) .Where(implementation => contractType.IsAssignableFrom(implementation) && !implementation.IsInterface && - !implementation.IsAbstract - ); + !implementation.IsAbstract); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common/Composition/ContainerBuilderBase.cs b/src/NzbDrone.Common/Composition/ContainerBuilderBase.cs index 009b356ef..c3ce47940 100644 --- a/src/NzbDrone.Common/Composition/ContainerBuilderBase.cs +++ b/src/NzbDrone.Common/Composition/ContainerBuilderBase.cs @@ -121,6 +121,7 @@ private void AutoRegisterImplementations(Type contractType) { return; } + if (implementations.Count == 1) { var impl = implementations.Single(); diff --git a/src/NzbDrone.Common/Composition/IContainer.cs b/src/NzbDrone.Common/Composition/IContainer.cs index 87d076842..9e7402017 100644 --- a/src/NzbDrone.Common/Composition/IContainer.cs +++ b/src/NzbDrone.Common/Composition/IContainer.cs @@ -5,20 +5,24 @@ namespace NzbDrone.Common.Composition { public interface IContainer { - void Register(T instance) where T : class; + void Register(T instance) + where T : class; void Register() where TImplementation : class, TService where TService : class; - T Resolve() where T : class; + T Resolve() + where T : class; object Resolve(Type type); void Register(Type serviceType, Type implementationType); - void Register(Func factory) where TService : class; + void Register(Func factory) + where TService : class; void RegisterSingleton(Type service, Type implementation); - IEnumerable ResolveAll() where T : class; + IEnumerable ResolveAll() + where T : class; void RegisterAllAsSingleton(Type registrationType, IEnumerable implementationList); bool IsTypeRegistered(Type type); IEnumerable GetImplementations(Type contractType); } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common/Crypto/HashProvider.cs b/src/NzbDrone.Common/Crypto/HashProvider.cs index 04868cb8c..10a09f359 100644 --- a/src/NzbDrone.Common/Crypto/HashProvider.cs +++ b/src/NzbDrone.Common/Crypto/HashProvider.cs @@ -28,4 +28,4 @@ public byte[] ComputeMd5(string path) } } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common/Disk/DestinationAlreadyExistsException.cs b/src/NzbDrone.Common/Disk/DestinationAlreadyExistsException.cs index 986413742..ffdc36e0e 100644 --- a/src/NzbDrone.Common/Disk/DestinationAlreadyExistsException.cs +++ b/src/NzbDrone.Common/Disk/DestinationAlreadyExistsException.cs @@ -10,19 +10,23 @@ public DestinationAlreadyExistsException() { } - public DestinationAlreadyExistsException(string message) : base(message) + public DestinationAlreadyExistsException(string message) + : base(message) { } - public DestinationAlreadyExistsException(string message, int hresult) : base(message, hresult) + public DestinationAlreadyExistsException(string message, int hresult) + : base(message, hresult) { } - public DestinationAlreadyExistsException(string message, Exception innerException) : base(message, innerException) + public DestinationAlreadyExistsException(string message, Exception innerException) + : base(message, innerException) { } - protected DestinationAlreadyExistsException(SerializationInfo info, StreamingContext context) : base(info, context) + protected DestinationAlreadyExistsException(SerializationInfo info, StreamingContext context) + : base(info, context) { } } diff --git a/src/NzbDrone.Common/Disk/DiskProviderBase.cs b/src/NzbDrone.Common/Disk/DiskProviderBase.cs index e2dd26586..23f35981d 100644 --- a/src/NzbDrone.Common/Disk/DiskProviderBase.cs +++ b/src/NzbDrone.Common/Disk/DiskProviderBase.cs @@ -117,6 +117,7 @@ public bool FileExists(string path, StringComparison stringComparison) { return File.Exists(path) && path == path.GetActualCasing(); } + default: { return File.Exists(path); @@ -367,7 +368,7 @@ private static void RemoveReadOnly(string path) if (attributes.HasFlag(FileAttributes.ReadOnly)) { - var newAttributes = attributes & ~(FileAttributes.ReadOnly); + var newAttributes = attributes & ~FileAttributes.ReadOnly; File.SetAttributes(path, newAttributes); } } diff --git a/src/NzbDrone.Common/Disk/DiskTransferService.cs b/src/NzbDrone.Common/Disk/DiskTransferService.cs index 42e672e8a..44d28a9df 100644 --- a/src/NzbDrone.Common/Disk/DiskTransferService.cs +++ b/src/NzbDrone.Common/Disk/DiskTransferService.cs @@ -14,7 +14,7 @@ public interface IDiskTransferService TransferMode TransferFile(string sourcePath, string targetPath, TransferMode mode, bool overwrite = false); int MirrorFolder(string sourcePath, string targetPath); } - + public class DiskTransferService : IDiskTransferService { private readonly IDiskProvider _diskProvider; @@ -40,7 +40,7 @@ private string ResolveRealParentPath(string path) return realParentPath + partialChildPath; } - + public TransferMode TransferFolder(string sourcePath, string targetPath, TransferMode mode) { Ensure.That(sourcePath, () => sourcePath).IsValidPath(); @@ -101,14 +101,20 @@ public TransferMode TransferFolder(string sourcePath, string targetPath, Transfe foreach (var subDir in _diskProvider.GetDirectoryInfos(sourcePath)) { - if (ShouldIgnore(subDir)) continue; + if (ShouldIgnore(subDir)) + { + continue; + } result &= TransferFolder(subDir.FullName, Path.Combine(targetPath, subDir.Name), mode); } foreach (var sourceFile in _diskProvider.GetFileInfos(sourcePath)) { - if (ShouldIgnore(sourceFile)) continue; + if (ShouldIgnore(sourceFile)) + { + continue; + } var destFile = Path.Combine(targetPath, sourceFile.Name); @@ -152,14 +158,20 @@ public int MirrorFolder(string sourcePath, string targetPath) foreach (var subDir in targetFolders.Where(v => !sourceFolders.Any(d => d.Name == v.Name))) { - if (ShouldIgnore(subDir)) continue; + if (ShouldIgnore(subDir)) + { + continue; + } _diskProvider.DeleteFolder(subDir.FullName, true); } foreach (var subDir in sourceFolders) { - if (ShouldIgnore(subDir)) continue; + if (ShouldIgnore(subDir)) + { + continue; + } filesCopied += MirrorFolder(subDir.FullName, Path.Combine(targetPath, subDir.Name)); } @@ -169,14 +181,20 @@ public int MirrorFolder(string sourcePath, string targetPath) foreach (var targetFile in targetFiles.Where(v => !sourceFiles.Any(d => d.Name == v.Name))) { - if (ShouldIgnore(targetFile)) continue; + if (ShouldIgnore(targetFile)) + { + continue; + } _diskProvider.DeleteFile(targetFile.FullName); } foreach (var sourceFile in sourceFiles) { - if (ShouldIgnore(sourceFile)) continue; + if (ShouldIgnore(sourceFile)) + { + continue; + } var targetFile = Path.Combine(targetPath, sourceFile.Name); @@ -305,6 +323,7 @@ public TransferMode TransferFile(string sourcePath, string targetPath, TransferM { return TransferMode.HardLink; } + if (!mode.HasFlag(TransferMode.Copy)) { throw new IOException("Hardlinking from '" + sourcePath + "' to '" + targetPath + "' failed."); @@ -315,14 +334,14 @@ public TransferMode TransferFile(string sourcePath, string targetPath, TransferM var sourceMount = _diskProvider.GetMount(sourcePath); var targetMount = _diskProvider.GetMount(targetPath); - var isSameMount = (sourceMount != null && targetMount != null && sourceMount.RootDirectory == targetMount.RootDirectory); + var isSameMount = sourceMount != null && targetMount != null && sourceMount.RootDirectory == targetMount.RootDirectory; var sourceDriveFormat = sourceMount?.DriveFormat ?? string.Empty; var targetDriveFormat = targetMount?.DriveFormat ?? string.Empty; var isCifs = targetDriveFormat == "cifs"; var isBtrfs = sourceDriveFormat == "btrfs" && targetDriveFormat == "btrfs"; - + if (mode.HasFlag(TransferMode.Copy)) { if (isBtrfs) @@ -363,7 +382,7 @@ public TransferMode TransferFile(string sourcePath, string targetPath, TransferM _diskProvider.DeleteFile(sourcePath); return TransferMode.Move; } - + TryMoveFileVerified(sourcePath, targetPath, originalSize); return TransferMode.Move; } diff --git a/src/NzbDrone.Common/Disk/FileAlreadyExistsException.cs b/src/NzbDrone.Common/Disk/FileAlreadyExistsException.cs index 6a987444d..69acb4cd7 100644 --- a/src/NzbDrone.Common/Disk/FileAlreadyExistsException.cs +++ b/src/NzbDrone.Common/Disk/FileAlreadyExistsException.cs @@ -6,7 +6,8 @@ public class FileAlreadyExistsException : Exception { public string Filename { get; set; } - public FileAlreadyExistsException(string message, string filename) : base(message) + public FileAlreadyExistsException(string message, string filename) + : base(message) { Filename = filename; } diff --git a/src/NzbDrone.Common/Disk/FileSystemLookupService.cs b/src/NzbDrone.Common/Disk/FileSystemLookupService.cs index 40f7adfb0..63529697e 100644 --- a/src/NzbDrone.Common/Disk/FileSystemLookupService.cs +++ b/src/NzbDrone.Common/Disk/FileSystemLookupService.cs @@ -125,7 +125,6 @@ private FileSystemResult GetResult(string path, bool includeFiles) result.Files = GetFiles(path); } } - catch (DirectoryNotFoundException) { return new FileSystemResult { Parent = GetParent(path) }; diff --git a/src/NzbDrone.Common/Disk/LongPathSupport.cs b/src/NzbDrone.Common/Disk/LongPathSupport.cs index 7336bb1d6..8d10f78d6 100644 --- a/src/NzbDrone.Common/Disk/LongPathSupport.cs +++ b/src/NzbDrone.Common/Disk/LongPathSupport.cs @@ -54,7 +54,11 @@ public static int MaxFilePathLength { get { - if (MAX_PATH == 0) DetectLongPathLimits(); + if (MAX_PATH == 0) + { + DetectLongPathLimits(); + } + return MAX_PATH; } } @@ -63,7 +67,11 @@ public static int MaxFileNameLength { get { - if (MAX_NAME == 0) DetectLongPathLimits(); + if (MAX_NAME == 0) + { + DetectLongPathLimits(); + } + return MAX_NAME; } } diff --git a/src/NzbDrone.Common/Disk/NotParentException.cs b/src/NzbDrone.Common/Disk/NotParentException.cs index 0ae384722..4859c29be 100644 --- a/src/NzbDrone.Common/Disk/NotParentException.cs +++ b/src/NzbDrone.Common/Disk/NotParentException.cs @@ -4,11 +4,13 @@ namespace NzbDrone.Common.Disk { public class NotParentException : NzbDroneException { - public NotParentException(string message, params object[] args) : base(message, args) + public NotParentException(string message, params object[] args) + : base(message, args) { } - public NotParentException(string message) : base(message) + public NotParentException(string message) + : base(message) { } } diff --git a/src/NzbDrone.Common/Disk/OsPath.cs b/src/NzbDrone.Common/Disk/OsPath.cs index 9028ec1f7..c4327ddeb 100644 --- a/src/NzbDrone.Common/Disk/OsPath.cs +++ b/src/NzbDrone.Common/Disk/OsPath.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using NzbDrone.Common.Extensions; @@ -44,22 +44,36 @@ private static OsPathKind DetectPathKind(string path) { return OsPathKind.Unix; } + if (HasWindowsDriveLetter(path) || path.Contains('\\')) { return OsPathKind.Windows; } + if (path.Contains('/')) { return OsPathKind.Unix; } + return OsPathKind.Unknown; } private static bool HasWindowsDriveLetter(string path) { - if (path.Length < 2) return false; - if (!char.IsLetter(path[0]) || path[1] != ':') return false; - if (path.Length > 2 && path[2] != '\\' && path[2] != '/') return false; + if (path.Length < 2) + { + return false; + } + + if (!char.IsLetter(path[0]) || path[1] != ':') + { + return false; + } + + if (path.Length > 2 && path[2] != '\\' && path[2] != '/') + { + return false; + } return true; } @@ -76,6 +90,7 @@ private static string FixSlashes(string path, OsPathKind kind) { path = path.Replace("//", "/"); } + return path; } @@ -98,11 +113,12 @@ public bool IsRooted { return _path.StartsWith(@"\\") || HasWindowsDriveLetter(_path); } + if (IsUnixPath) { return _path.StartsWith("/"); } - + return false; } } @@ -117,7 +133,7 @@ public OsPath Directory { return new OsPath(null); } - + return new OsPath(_path.Substring(0, index), _kind).AsDirectory(); } } @@ -141,7 +157,7 @@ public string FileName return path; } - + return _path.Substring(index).Trim('\\', '/'); } } @@ -196,10 +212,12 @@ public override bool Equals(object obj) { return Equals((OsPath)obj); } + if (obj is string) { return Equals(new OsPath(obj as string)); } + return false; } @@ -217,6 +235,7 @@ public OsPath AsDirectory() case OsPathKind.Unix: return new OsPath(_path.TrimEnd('/') + "/", _kind); } + return this; } @@ -250,7 +269,10 @@ public bool Contains(OsPath other) public bool Equals(OsPath other) { - if (ReferenceEquals(other, null)) return false; + if (ReferenceEquals(other, null)) + { + return false; + } if (_path == other._path) { @@ -264,19 +286,26 @@ public bool Equals(OsPath other) { return string.Equals(left, right, StringComparison.InvariantCultureIgnoreCase); } + return string.Equals(left, right, StringComparison.InvariantCulture); } public static bool operator ==(OsPath left, OsPath right) { - if (ReferenceEquals(left, null)) return ReferenceEquals(right, null); + if (ReferenceEquals(left, null)) + { + return ReferenceEquals(right, null); + } return left.Equals(right); } public static bool operator !=(OsPath left, OsPath right) { - if (ReferenceEquals(left, null)) return !ReferenceEquals(right, null); + if (ReferenceEquals(left, null)) + { + return !ReferenceEquals(right, null); + } return !left.Equals(right); } @@ -302,10 +331,12 @@ public bool Equals(OsPath other) { return new OsPath(string.Join("\\", left._path.TrimEnd('\\'), right._path.TrimStart('\\')), OsPathKind.Windows); } + if (left.Kind == OsPathKind.Unix || right.Kind == OsPathKind.Unix) { return new OsPath(string.Join("/", left._path.TrimEnd('/'), right._path), OsPathKind.Unix); } + return new OsPath(string.Join("/", left._path, right._path), OsPathKind.Unknown); } @@ -361,6 +392,7 @@ public bool Equals(OsPath other) { return new OsPath(string.Join("\\", newFragments), OsPathKind.Unknown); } + return new OsPath(string.Join("/", newFragments), OsPathKind.Unknown); } } diff --git a/src/NzbDrone.Common/EnsureThat/Ensure.cs b/src/NzbDrone.Common/EnsureThat/Ensure.cs index d918d0e66..cb63dd14c 100644 --- a/src/NzbDrone.Common/EnsureThat/Ensure.cs +++ b/src/NzbDrone.Common/EnsureThat/Ensure.cs @@ -20,4 +20,4 @@ public static TypeParam ThatTypeFor(T value, string name = Param.DefaultName) return new TypeParam(name, value.GetType()); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common/EnsureThat/EnsureBoolExtensions.cs b/src/NzbDrone.Common/EnsureThat/EnsureBoolExtensions.cs index de18bb06c..a393d556c 100644 --- a/src/NzbDrone.Common/EnsureThat/EnsureBoolExtensions.cs +++ b/src/NzbDrone.Common/EnsureThat/EnsureBoolExtensions.cs @@ -9,7 +9,9 @@ public static class EnsureBoolExtensions public static Param IsTrue(this Param param) { if (!param.Value) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotTrue); + } return param; } @@ -18,9 +20,11 @@ public static Param IsTrue(this Param param) public static Param IsFalse(this Param param) { if (param.Value) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotFalse); + } return param; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common/EnsureThat/EnsureCollectionExtensions.cs b/src/NzbDrone.Common/EnsureThat/EnsureCollectionExtensions.cs index 34565f8a0..cf0392487 100644 --- a/src/NzbDrone.Common/EnsureThat/EnsureCollectionExtensions.cs +++ b/src/NzbDrone.Common/EnsureThat/EnsureCollectionExtensions.cs @@ -10,10 +10,13 @@ namespace NzbDrone.Common.EnsureThat public static class EnsureCollectionExtensions { [DebuggerStepThrough] - public static Param HasItems(this Param param) where T : class, ICollection + public static Param HasItems(this Param param) + where T : class, ICollection { if (param.Value == null || param.Value.Count < 1) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsEmptyCollection); + } return param; } @@ -22,7 +25,9 @@ public static Param HasItems(this Param param) where T : class, ICollec public static Param> HasItems(this Param> param) { if (param.Value == null || param.Value.Count < 1) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsEmptyCollection); + } return param; } @@ -31,7 +36,9 @@ public static Param> HasItems(this Param> param) public static Param> HasItems(this Param> param) { if (param.Value == null || !param.Value.Any()) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsEmptyCollection); + } return param; } @@ -40,7 +47,9 @@ public static Param> HasItems(this Param> param public static Param HasItems(this Param param) { if (param.Value == null || param.Value.Length < 1) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsEmptyCollection); + } return param; } @@ -49,19 +58,22 @@ public static Param HasItems(this Param param) public static Param> HasItems(this Param> param) { if (param.Value == null || param.Value.Count < 1) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsEmptyCollection); + } return param; } - [DebuggerStepThrough] public static Param> HasItems(this Param> param) { if (param.Value == null || param.Value.Count < 1) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsEmptyCollection); + } return param; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common/EnsureThat/EnsureDateTimeExtensions.cs b/src/NzbDrone.Common/EnsureThat/EnsureDateTimeExtensions.cs index 8586c4ddf..97d9f58ee 100644 --- a/src/NzbDrone.Common/EnsureThat/EnsureDateTimeExtensions.cs +++ b/src/NzbDrone.Common/EnsureThat/EnsureDateTimeExtensions.cs @@ -7,14 +7,15 @@ namespace NzbDrone.Common.EnsureThat { public static class EnsureDateTimeExtensions { - private static readonly DateTime _minTime = new DateTime(1960, 1, 1); [DebuggerStepThrough] public static Param IsLt(this Param param, DateTime limit) { if (param.Value >= limit) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotLt.Inject(param.Value, limit)); + } return param; } @@ -23,7 +24,9 @@ public static Param IsLt(this Param param, DateTime limit) public static Param IsLte(this Param param, DateTime limit) { if (!(param.Value <= limit)) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotLte.Inject(param.Value, limit)); + } return param; } @@ -32,7 +35,9 @@ public static Param IsLte(this Param param, DateTime limit) public static Param IsGt(this Param param, DateTime limit) { if (param.Value <= limit) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotGt.Inject(param.Value, limit)); + } return param; } @@ -41,7 +46,9 @@ public static Param IsGt(this Param param, DateTime limit) public static Param IsGte(this Param param, DateTime limit) { if (!(param.Value >= limit)) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotGte.Inject(param.Value, limit)); + } return param; } @@ -50,10 +57,14 @@ public static Param IsGte(this Param param, DateTime limit) public static Param IsInRange(this Param param, DateTime min, DateTime max) { if (param.Value < min) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotInRange_ToLow.Inject(param.Value, min)); + } if (param.Value > max) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotInRange_ToHigh.Inject(param.Value, max)); + } return param; } @@ -62,15 +73,17 @@ public static Param IsInRange(this Param param, DateTime min public static Param IsUtc(this Param param) { if (param.Value.Kind != DateTimeKind.Utc) + { throw ExceptionFactory.CreateForParamValidation(param.Name, "Excepted time to be in UTC but was [{0}]".Inject(param.Value.Kind)); + } + return param; } - [DebuggerStepThrough] public static Param IsValid(this Param param) { return IsGt(param, _minTime); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common/EnsureThat/EnsureDecimalExtensions.cs b/src/NzbDrone.Common/EnsureThat/EnsureDecimalExtensions.cs index 5fa967337..e1bf3ba6d 100644 --- a/src/NzbDrone.Common/EnsureThat/EnsureDecimalExtensions.cs +++ b/src/NzbDrone.Common/EnsureThat/EnsureDecimalExtensions.cs @@ -10,7 +10,9 @@ public static class EnsureDecimalExtensions public static Param IsLt(this Param param, decimal limit) { if (param.Value >= limit) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotLt.Inject(param.Value, limit)); + } return param; } @@ -19,7 +21,9 @@ public static Param IsLt(this Param param, decimal limit) public static Param IsLte(this Param param, decimal limit) { if (!(param.Value <= limit)) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotLte.Inject(param.Value, limit)); + } return param; } @@ -28,7 +32,9 @@ public static Param IsLte(this Param param, decimal limit) public static Param IsGt(this Param param, decimal limit) { if (param.Value <= limit) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotGt.Inject(param.Value, limit)); + } return param; } @@ -37,7 +43,9 @@ public static Param IsGt(this Param param, decimal limit) public static Param IsGte(this Param param, decimal limit) { if (!(param.Value >= limit)) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotGte.Inject(param.Value, limit)); + } return param; } @@ -46,12 +54,16 @@ public static Param IsGte(this Param param, decimal limit) public static Param IsInRange(this Param param, decimal min, decimal max) { if (param.Value < min) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotInRange_ToLow.Inject(param.Value, min)); + } if (param.Value > max) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotInRange_ToHigh.Inject(param.Value, max)); + } return param; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common/EnsureThat/EnsureDoubleExtensions.cs b/src/NzbDrone.Common/EnsureThat/EnsureDoubleExtensions.cs index 7c91f41b4..d67abe512 100644 --- a/src/NzbDrone.Common/EnsureThat/EnsureDoubleExtensions.cs +++ b/src/NzbDrone.Common/EnsureThat/EnsureDoubleExtensions.cs @@ -10,7 +10,9 @@ public static class EnsureDoubleExtensions public static Param IsLt(this Param param, double limit) { if (param.Value >= limit) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotLt.Inject(param.Value, limit)); + } return param; } @@ -19,7 +21,9 @@ public static Param IsLt(this Param param, double limit) public static Param IsLte(this Param param, double limit) { if (!(param.Value <= limit)) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotLte.Inject(param.Value, limit)); + } return param; } @@ -28,7 +32,9 @@ public static Param IsLte(this Param param, double limit) public static Param IsGt(this Param param, double limit) { if (param.Value <= limit) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotGt.Inject(param.Value, limit)); + } return param; } @@ -37,7 +43,9 @@ public static Param IsGt(this Param param, double limit) public static Param IsGte(this Param param, double limit) { if (!(param.Value >= limit)) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotGte.Inject(param.Value, limit)); + } return param; } @@ -46,12 +54,16 @@ public static Param IsGte(this Param param, double limit) public static Param IsInRange(this Param param, double min, double max) { if (param.Value < min) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotInRange_ToLow.Inject(param.Value, min)); + } if (param.Value > max) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotInRange_ToHigh.Inject(param.Value, max)); + } return param; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common/EnsureThat/EnsureGuidExtensions.cs b/src/NzbDrone.Common/EnsureThat/EnsureGuidExtensions.cs index 77a7be433..a9d6190b3 100644 --- a/src/NzbDrone.Common/EnsureThat/EnsureGuidExtensions.cs +++ b/src/NzbDrone.Common/EnsureThat/EnsureGuidExtensions.cs @@ -10,9 +10,11 @@ public static class EnsureGuidExtensions public static Param IsNotEmpty(this Param param) { if (Guid.Empty.Equals(param.Value)) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsEmptyGuid); + } return param; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common/EnsureThat/EnsureIntExtensions.cs b/src/NzbDrone.Common/EnsureThat/EnsureIntExtensions.cs index ecbdb0e3f..77ecaf669 100644 --- a/src/NzbDrone.Common/EnsureThat/EnsureIntExtensions.cs +++ b/src/NzbDrone.Common/EnsureThat/EnsureIntExtensions.cs @@ -10,7 +10,9 @@ public static class EnsureIntExtensions public static Param IsLessThan(this Param param, int limit) { if (param.Value >= limit) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotLt.Inject(param.Value, limit)); + } return param; } @@ -19,7 +21,9 @@ public static Param IsLessThan(this Param param, int limit) public static Param IsLessThanOrEqualTo(this Param param, int limit) { if (!(param.Value <= limit)) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotLte.Inject(param.Value, limit)); + } return param; } @@ -28,7 +32,9 @@ public static Param IsLessThanOrEqualTo(this Param param, int limit) public static Param IsGreaterThan(this Param param, int limit) { if (param.Value <= limit) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotGt.Inject(param.Value, limit)); + } return param; } @@ -37,7 +43,9 @@ public static Param IsGreaterThan(this Param param, int limit) public static Param IsGreaterThanZero(this Param param) { if (param.Value <= 0) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotGt.Inject(param.Value, 0)); + } return param; } @@ -46,7 +54,9 @@ public static Param IsGreaterThanZero(this Param param) public static Param IsGreaterOrEqualTo(this Param param, int limit) { if (!(param.Value >= limit)) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotGte.Inject(param.Value, limit)); + } return param; } @@ -55,12 +65,16 @@ public static Param IsGreaterOrEqualTo(this Param param, int limit) public static Param IsInRange(this Param param, int min, int max) { if (param.Value < min) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotInRange_ToLow.Inject(param.Value, min)); + } if (param.Value > max) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotInRange_ToHigh.Inject(param.Value, max)); + } return param; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common/EnsureThat/EnsureLongExtensions.cs b/src/NzbDrone.Common/EnsureThat/EnsureLongExtensions.cs index 066c78c2f..568fefb5a 100644 --- a/src/NzbDrone.Common/EnsureThat/EnsureLongExtensions.cs +++ b/src/NzbDrone.Common/EnsureThat/EnsureLongExtensions.cs @@ -10,7 +10,9 @@ public static class EnsureLongExtensions public static Param IsLt(this Param param, long limit) { if (param.Value >= limit) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotLt.Inject(param.Value, limit)); + } return param; } @@ -19,7 +21,9 @@ public static Param IsLt(this Param param, long limit) public static Param IsLte(this Param param, long limit) { if (!(param.Value <= limit)) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotLte.Inject(param.Value, limit)); + } return param; } @@ -28,7 +32,9 @@ public static Param IsLte(this Param param, long limit) public static Param IsGt(this Param param, long limit) { if (param.Value <= limit) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotGt.Inject(param.Value, limit)); + } return param; } @@ -37,7 +43,9 @@ public static Param IsGt(this Param param, long limit) public static Param IsGte(this Param param, long limit) { if (!(param.Value >= limit)) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotGte.Inject(param.Value, limit)); + } return param; } @@ -46,12 +54,16 @@ public static Param IsGte(this Param param, long limit) public static Param IsInRange(this Param param, long min, long max) { if (param.Value < min) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotInRange_ToLow.Inject(param.Value, min)); + } if (param.Value > max) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotInRange_ToHigh.Inject(param.Value, max)); + } return param; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common/EnsureThat/EnsureNullableValueTypeExtensions.cs b/src/NzbDrone.Common/EnsureThat/EnsureNullableValueTypeExtensions.cs index 54d5af7ad..3603da257 100644 --- a/src/NzbDrone.Common/EnsureThat/EnsureNullableValueTypeExtensions.cs +++ b/src/NzbDrone.Common/EnsureThat/EnsureNullableValueTypeExtensions.cs @@ -6,12 +6,15 @@ namespace NzbDrone.Common.EnsureThat public static class EnsureNullableValueTypeExtensions { [DebuggerStepThrough] - public static Param IsNotNull(this Param param) where T : struct + public static Param IsNotNull(this Param param) + where T : struct { if (param.Value == null || !param.Value.HasValue) + { throw ExceptionFactory.CreateForParamNullValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotNull); + } return param; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common/EnsureThat/EnsureObjectExtensions.cs b/src/NzbDrone.Common/EnsureThat/EnsureObjectExtensions.cs index a5fe6a23f..7833d02e5 100644 --- a/src/NzbDrone.Common/EnsureThat/EnsureObjectExtensions.cs +++ b/src/NzbDrone.Common/EnsureThat/EnsureObjectExtensions.cs @@ -6,12 +6,15 @@ namespace NzbDrone.Common.EnsureThat public static class EnsureObjectExtensions { [DebuggerStepThrough] - public static Param IsNotNull(this Param param) where T : class + public static Param IsNotNull(this Param param) + where T : class { if (param.Value == null) + { throw ExceptionFactory.CreateForParamNullValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotNull); + } return param; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common/EnsureThat/EnsureShortExtensions.cs b/src/NzbDrone.Common/EnsureThat/EnsureShortExtensions.cs index 425494d43..54f082b8f 100644 --- a/src/NzbDrone.Common/EnsureThat/EnsureShortExtensions.cs +++ b/src/NzbDrone.Common/EnsureThat/EnsureShortExtensions.cs @@ -10,7 +10,9 @@ public static class EnsureShortExtensions public static Param IsLt(this Param param, short limit) { if (param.Value >= limit) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotLt.Inject(param.Value, limit)); + } return param; } @@ -19,7 +21,9 @@ public static Param IsLt(this Param param, short limit) public static Param IsLte(this Param param, short limit) { if (!(param.Value <= limit)) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotLte.Inject(param.Value, limit)); + } return param; } @@ -28,7 +32,9 @@ public static Param IsLte(this Param param, short limit) public static Param IsGt(this Param param, short limit) { if (param.Value <= limit) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotGt.Inject(param.Value, limit)); + } return param; } @@ -37,7 +43,9 @@ public static Param IsGt(this Param param, short limit) public static Param IsGte(this Param param, short limit) { if (!(param.Value >= limit)) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotGte.Inject(param.Value, limit)); + } return param; } @@ -46,12 +54,16 @@ public static Param IsGte(this Param param, short limit) public static Param IsInRange(this Param param, short min, short max) { if (param.Value < min) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotInRange_ToLow.Inject(param.Value, min)); + } if (param.Value > max) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotInRange_ToHigh.Inject(param.Value, max)); + } return param; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common/EnsureThat/EnsureStringExtensions.cs b/src/NzbDrone.Common/EnsureThat/EnsureStringExtensions.cs index 99f348667..1c10c9f28 100644 --- a/src/NzbDrone.Common/EnsureThat/EnsureStringExtensions.cs +++ b/src/NzbDrone.Common/EnsureThat/EnsureStringExtensions.cs @@ -13,7 +13,9 @@ public static class EnsureStringExtensions public static Param IsNotNullOrWhiteSpace(this Param param) { if (string.IsNullOrWhiteSpace(param.Value)) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotNullOrWhiteSpace); + } return param; } @@ -22,7 +24,9 @@ public static Param IsNotNullOrWhiteSpace(this Param param) public static Param IsNotNullOrEmpty(this Param param) { if (string.IsNullOrEmpty(param.Value)) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotNullOrEmpty); + } return param; } @@ -31,15 +35,21 @@ public static Param IsNotNullOrEmpty(this Param param) public static Param HasLengthBetween(this Param param, int minLength, int maxLength) { if (string.IsNullOrEmpty(param.Value)) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotNullOrEmpty); + } var length = param.Value.Length; if (length < minLength) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotInRange_ToShort.Inject(minLength, maxLength, length)); + } if (length > maxLength) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotInRange_ToLong.Inject(minLength, maxLength, length)); + } return param; } @@ -48,12 +58,16 @@ public static Param HasLengthBetween(this Param param, int minLe public static Param IsLongerThan(this Param param, int minLength) { if (string.IsNullOrEmpty(param.Value)) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotNullOrEmpty); + } var length = param.Value.Length; if (length < minLength) + { throw ExceptionFactory.CreateForParamValidation(param.Name, "The string is not long enough. Must be at least '{0}' but was '{1}' characters long.".Inject(minLength, length)); + } return param; } @@ -71,6 +85,7 @@ public static Param Matches(this Param param, Regex match) { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_NoMatch.Inject(param.Value, match)); } + return param; } @@ -78,7 +93,9 @@ public static Param Matches(this Param param, Regex match) public static Param IsRelativePath(this Param param) { if (string.IsNullOrWhiteSpace(param.Value)) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotNullOrWhiteSpace); + } if (!param.Value.EndsWith("\\")) { @@ -97,9 +114,14 @@ public static Param IsRelativePath(this Param param) public static Param IsValidPath(this Param param) { if (string.IsNullOrWhiteSpace(param.Value)) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotNullOrWhiteSpace); + } - if (param.Value.IsPathValid()) return param; + if (param.Value.IsPathValid()) + { + return param; + } if (OsInfo.IsWindows) { diff --git a/src/NzbDrone.Common/EnsureThat/EnsureTypeExtensions.cs b/src/NzbDrone.Common/EnsureThat/EnsureTypeExtensions.cs index 74f4246fb..00c1b4dc2 100644 --- a/src/NzbDrone.Common/EnsureThat/EnsureTypeExtensions.cs +++ b/src/NzbDrone.Common/EnsureThat/EnsureTypeExtensions.cs @@ -9,7 +9,7 @@ public static class EnsureTypeExtensions { private static class Types { - internal static readonly Type IntType = typeof (int); + internal static readonly Type IntType = typeof(int); internal static readonly Type ShortType = typeof(short); @@ -78,10 +78,12 @@ public static TypeParam IsString(this TypeParam param) public static TypeParam IsOfType(this TypeParam param, Type type) { if (!param.Type.Equals(type)) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotOfType.Inject(param.Type.FullName)); + } return param; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common/EnsureThat/ExceptionFactory.cs b/src/NzbDrone.Common/EnsureThat/ExceptionFactory.cs index 42bbb1b5c..d3f24a43f 100644 --- a/src/NzbDrone.Common/EnsureThat/ExceptionFactory.cs +++ b/src/NzbDrone.Common/EnsureThat/ExceptionFactory.cs @@ -19,4 +19,4 @@ internal static ArgumentNullException CreateForParamNullValidation(string paramN return new ArgumentNullException(paramName, message); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common/EnsureThat/ExpressionExtensions.cs b/src/NzbDrone.Common/EnsureThat/ExpressionExtensions.cs index 7e72fe4ed..baea52fcb 100644 --- a/src/NzbDrone.Common/EnsureThat/ExpressionExtensions.cs +++ b/src/NzbDrone.Common/EnsureThat/ExpressionExtensions.cs @@ -9,7 +9,9 @@ internal static string ToPath(this MemberExpression e) var path = ""; if (e.Expression is MemberExpression parent) + { path = parent.ToPath() + "."; + } return path + e.Member.Name; } @@ -22,17 +24,23 @@ internal static string GetPath(this Expression expression) private static MemberExpression GetRightMostMember(Expression e) { if (e is LambdaExpression) + { return GetRightMostMember(((LambdaExpression)e).Body); + } if (e is MemberExpression) + { return (MemberExpression)e; + } if (e is MethodCallExpression) { var callExpression = (MethodCallExpression)e; if (callExpression.Object is MethodCallExpression || callExpression.Object is MemberExpression) + { return GetRightMostMember(callExpression.Object); + } var member = callExpression.Arguments.Count > 0 ? callExpression.Arguments[0] : callExpression.Object; return GetRightMostMember(member); @@ -47,4 +55,4 @@ private static MemberExpression GetRightMostMember(Expression e) return null; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common/EnsureThat/Param.cs b/src/NzbDrone.Common/EnsureThat/Param.cs index c1ff3c963..1eea2851d 100644 --- a/src/NzbDrone.Common/EnsureThat/Param.cs +++ b/src/NzbDrone.Common/EnsureThat/Param.cs @@ -16,9 +16,10 @@ public class Param : Param { public readonly T Value; - internal Param(string name, T value) : base(name) + internal Param(string name, T value) + : base(name) { Value = value; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common/EnsureThat/TypeParam.cs b/src/NzbDrone.Common/EnsureThat/TypeParam.cs index 202dacf87..09788e446 100644 --- a/src/NzbDrone.Common/EnsureThat/TypeParam.cs +++ b/src/NzbDrone.Common/EnsureThat/TypeParam.cs @@ -12,4 +12,4 @@ internal TypeParam(string name, Type type) Type = type; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common/EnvironmentInfo/AppFolderFactory.cs b/src/NzbDrone.Common/EnvironmentInfo/AppFolderFactory.cs index b48110a52..1995dcb47 100644 --- a/src/NzbDrone.Common/EnvironmentInfo/AppFolderFactory.cs +++ b/src/NzbDrone.Common/EnvironmentInfo/AppFolderFactory.cs @@ -95,9 +95,20 @@ private void MigrateAppDataFolder() RemovePidFile(); } - if (_appFolderInfo.LegacyAppDataFolder.IsNullOrWhiteSpace()) return; - if (_diskProvider.FileExists(_appFolderInfo.GetDatabase()) || _diskProvider.FileExists(_appFolderInfo.GetConfigPath())) return; - if (!_diskProvider.FolderExists(_appFolderInfo.LegacyAppDataFolder)) return; + if (_appFolderInfo.LegacyAppDataFolder.IsNullOrWhiteSpace()) + { + return; + } + + if (_diskProvider.FileExists(_appFolderInfo.GetDatabase()) || _diskProvider.FileExists(_appFolderInfo.GetConfigPath())) + { + return; + } + + if (!_diskProvider.FolderExists(_appFolderInfo.LegacyAppDataFolder)) + { + return; + } // Delete the bin folder on Windows var binFolder = Path.Combine(_appFolderInfo.LegacyAppDataFolder, "bin"); diff --git a/src/NzbDrone.Common/EnvironmentInfo/IOsVersionAdapter.cs b/src/NzbDrone.Common/EnvironmentInfo/IOsVersionAdapter.cs index 25a3cbf1f..b844a29c2 100644 --- a/src/NzbDrone.Common/EnvironmentInfo/IOsVersionAdapter.cs +++ b/src/NzbDrone.Common/EnvironmentInfo/IOsVersionAdapter.cs @@ -1,6 +1,5 @@ namespace NzbDrone.Common.EnvironmentInfo { - public interface IOsVersionAdapter { bool Enabled { get; } diff --git a/src/NzbDrone.Common/EnvironmentInfo/OsInfo.cs b/src/NzbDrone.Common/EnvironmentInfo/OsInfo.cs index 2c9bf896a..bb94ec267 100644 --- a/src/NzbDrone.Common/EnvironmentInfo/OsInfo.cs +++ b/src/NzbDrone.Common/EnvironmentInfo/OsInfo.cs @@ -34,6 +34,7 @@ static OsInfo() Os = Os.Windows; break; } + case PlatformID.MacOSX: case PlatformID.Unix: { diff --git a/src/NzbDrone.Common/EnvironmentInfo/OsVersionModel.cs b/src/NzbDrone.Common/EnvironmentInfo/OsVersionModel.cs index c20865813..f5e8074fc 100644 --- a/src/NzbDrone.Common/EnvironmentInfo/OsVersionModel.cs +++ b/src/NzbDrone.Common/EnvironmentInfo/OsVersionModel.cs @@ -2,8 +2,6 @@ namespace NzbDrone.Common.EnvironmentInfo { public class OsVersionModel { - - public OsVersionModel(string name, string version, string fullName = null) { Name = Trim(name); diff --git a/src/NzbDrone.Common/EnvironmentInfo/PlatformInfo.cs b/src/NzbDrone.Common/EnvironmentInfo/PlatformInfo.cs index 23fcc00b1..76f323652 100644 --- a/src/NzbDrone.Common/EnvironmentInfo/PlatformInfo.cs +++ b/src/NzbDrone.Common/EnvironmentInfo/PlatformInfo.cs @@ -2,7 +2,6 @@ namespace NzbDrone.Common.EnvironmentInfo { - public enum PlatformType { DotNet = 0, diff --git a/src/NzbDrone.Common/EnvironmentInfo/RuntimeInfo.cs b/src/NzbDrone.Common/EnvironmentInfo/RuntimeInfo.cs index f5d06bf64..c4a22fcc7 100644 --- a/src/NzbDrone.Common/EnvironmentInfo/RuntimeInfo.cs +++ b/src/NzbDrone.Common/EnvironmentInfo/RuntimeInfo.cs @@ -124,7 +124,6 @@ public RuntimeMode Mode public static bool IsProduction { get; } public static bool IsDevelopment { get; } - private static bool InternalIsTesting() { try @@ -153,7 +152,6 @@ private static bool InternalIsTesting() } catch { - } try diff --git a/src/NzbDrone.Common/Exceptions/NzbDroneException.cs b/src/NzbDrone.Common/Exceptions/NzbDroneException.cs index 7e0be7312..015ffc0b5 100644 --- a/src/NzbDrone.Common/Exceptions/NzbDroneException.cs +++ b/src/NzbDrone.Common/Exceptions/NzbDroneException.cs @@ -7,19 +7,16 @@ public abstract class NzbDroneException : ApplicationException protected NzbDroneException(string message, params object[] args) : base(string.Format(message, args)) { - } protected NzbDroneException(string message) : base(message) { - } protected NzbDroneException(string message, Exception innerException, params object[] args) : base(string.Format(message, args), innerException) { - } protected NzbDroneException(string message, Exception innerException) diff --git a/src/NzbDrone.Common/Exceptions/SonarrStartupException.cs b/src/NzbDrone.Common/Exceptions/SonarrStartupException.cs index 899596d8d..f39ab31d8 100644 --- a/src/NzbDrone.Common/Exceptions/SonarrStartupException.cs +++ b/src/NzbDrone.Common/Exceptions/SonarrStartupException.cs @@ -7,19 +7,16 @@ public class SonarrStartupException : NzbDroneException public SonarrStartupException(string message, params object[] args) : base("Sonarr failed to start: " + string.Format(message, args)) { - } public SonarrStartupException(string message) : base("Sonarr failed to start: " + message) { - } public SonarrStartupException() : base("Sonarr failed to start") { - } public SonarrStartupException(Exception innerException, string message, params object[] args) @@ -35,7 +32,6 @@ public SonarrStartupException(Exception innerException, string message) public SonarrStartupException(Exception innerException) : base("Sonarr failed to start: " + innerException.Message) { - } } } diff --git a/src/NzbDrone.Common/Expansive/CircularReferenceException.cs b/src/NzbDrone.Common/Expansive/CircularReferenceException.cs index 93478ad00..737663c54 100644 --- a/src/NzbDrone.Common/Expansive/CircularReferenceException.cs +++ b/src/NzbDrone.Common/Expansive/CircularReferenceException.cs @@ -9,4 +9,4 @@ public CircularReferenceException(string message) { } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common/Expansive/Expansive.cs b/src/NzbDrone.Common/Expansive/Expansive.cs index 9ad255ce6..7f7a2816b 100644 --- a/src/NzbDrone.Common/Expansive/Expansive.cs +++ b/src/NzbDrone.Common/Expansive/Expansive.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Dynamic; @@ -11,7 +11,6 @@ public static class Expansive { private static PatternStyle _patternStyle; - public static bool RequireAllExpansions { get; set; } public static Func DefaultExpansionFactory { get; set; } @@ -26,7 +25,6 @@ public static string Expand(this string source) return source.Expand(DefaultExpansionFactory); } - public static string Expand(this string source, params string[] args) { var output = source; @@ -50,9 +48,11 @@ public static string Expand(this string source, params string[] args) { tokenIndex = tokens.IndexOf(token); } + output = Regex.Replace(output, _patternStyle.OutputFilter(match.Value), "{" + tokenIndex + "}"); } } + var newArgs = new List(); foreach (var arg in args) { @@ -63,15 +63,20 @@ public static string Expand(this string source, params string[] args) foreach (Match match in tokenPattern.Matches(newArg)) { var token = _patternStyle.TokenReplaceFilter(match.Value); - if (calls.Contains(string.Format("{0}:{1}", callingToken, token))) throw new CircularReferenceException(string.Format("Circular Reference Detected for token '{0}'.", callingToken)); + if (calls.Contains(string.Format("{0}:{1}", callingToken, token))) + { + throw new CircularReferenceException(string.Format("Circular Reference Detected for token '{0}'.", callingToken)); + } + calls.Push(string.Format("{0}:{1}", callingToken, token)); callingToken = token; newArg = Regex.Replace(newArg, _patternStyle.OutputFilter(match.Value), args[tokens.IndexOf(token)]); } - } + newArgs.Add(newArg); } + return string.Format(output, newArgs.ToArray()); } @@ -80,9 +85,6 @@ public static string Expand(this string source, Func expansionFa return source.ExpandInternal(expansionFactory); } - - - public static string Expand(this string source, object model) { return source.ExpandInternal( @@ -116,7 +118,10 @@ private static void Initialize() private static string ExpandInternal(this string source, Func expansionFactory) { - if (expansionFactory == null) throw new ApplicationException("ExpansionFactory not defined.\nDefine a DefaultExpansionFactory or call Expand(source, Func expansionFactory))"); + if (expansionFactory == null) + { + throw new ApplicationException("ExpansionFactory not defined.\nDefine a DefaultExpansionFactory or call Expand(source, Func expansionFactory))"); + } var pattern = new Regex(_patternStyle.TokenMatchPattern, RegexOptions.IgnoreCase); @@ -139,9 +144,12 @@ private static string Explode(this string source, Regex pattern, PatternStyle pa // if we have already encountered this token in this call tree, we have a circular reference if (thisNode.CallTree.Contains(token)) + { throw new CircularReferenceException(string.Format("Circular Reference Detected for token '{0}'. Call Tree: {1}->{2}", token, - string.Join("->", thisNode.CallTree.ToArray().Reverse()), token)); + string.Join("->", thisNode.CallTree.ToArray().Reverse()), + token)); + } // expand this match var expandedValue = expansionFactory(token); @@ -156,6 +164,7 @@ private static string Explode(this string source, Regex pattern, PatternStyle pa output = Regex.Replace(output, patternStyle.OutputFilter(match.Value), child); } } + return output; } @@ -171,7 +180,11 @@ private static dynamic ToExpando(this object o) { var result = new ExpandoObject(); var d = result as IDictionary; //work with the Expando as a Dictionary - if (o is ExpandoObject) return o; //shouldn't have to... but just in case + if (o is ExpandoObject) + { + return o; //shouldn't have to... but just in case + } + if (o is NameValueCollection || o.GetType().IsSubclassOf(typeof(NameValueCollection))) { var nv = (NameValueCollection)o; @@ -185,8 +198,10 @@ private static dynamic ToExpando(this object o) d.Add(item.Name, item.GetValue(o, null)); } } + return result; } + /// /// Turns the object into a Dictionary /// @@ -195,4 +210,4 @@ private static IDictionary ToDictionary(this object thingy) return (IDictionary)thingy.ToExpando(); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common/Expansive/PatternStyle.cs b/src/NzbDrone.Common/Expansive/PatternStyle.cs index 0e4f0fcc1..011e77315 100644 --- a/src/NzbDrone.Common/Expansive/PatternStyle.cs +++ b/src/NzbDrone.Common/Expansive/PatternStyle.cs @@ -9,4 +9,4 @@ internal class PatternStyle public Func TokenReplaceFilter { get; set; } public Func OutputFilter { get; set; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common/Expansive/Tree.cs b/src/NzbDrone.Common/Expansive/Tree.cs index 24be6b642..744c0714e 100644 --- a/src/NzbDrone.Common/Expansive/Tree.cs +++ b/src/NzbDrone.Common/Expansive/Tree.cs @@ -8,4 +8,4 @@ public Tree(T rootValue) Value = rootValue; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common/Expansive/TreeNode.cs b/src/NzbDrone.Common/Expansive/TreeNode.cs index d3470072a..1b928db16 100644 --- a/src/NzbDrone.Common/Expansive/TreeNode.cs +++ b/src/NzbDrone.Common/Expansive/TreeNode.cs @@ -1,4 +1,4 @@ -using System.Collections.Generic; +using System.Collections.Generic; namespace NzbDrone.Common.Expansive { @@ -7,25 +7,29 @@ internal class TreeNode private List _CallTree; private TreeNode _Parent; - public TreeNode(T Value) + public TreeNode(T value) { - this.Value = Value; + Value = value; Parent = null; Children = new TreeNodeList(this); _CallTree = new List(); } - public TreeNode(T Value, TreeNode Parent) + public TreeNode(T value, TreeNode parent) { - this.Value = Value; - this.Parent = Parent; + Value = value; + Parent = parent; Children = new TreeNodeList(this); _CallTree = new List(); } public TreeNode Parent { - get { return _Parent; } + get + { + return _Parent; + } + set { if (value == _Parent) @@ -58,6 +62,7 @@ public TreeNode Root { node = node.Parent; } + return node; } } @@ -75,11 +80,16 @@ public List CallTree node = node.Parent; _CallTree.Add(node.Value); } + return _CallTree; } - private set { _CallTree = value; } + + private set + { + _CallTree = value; + } } public T Value { get; set; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common/Expansive/TreeNodeList.cs b/src/NzbDrone.Common/Expansive/TreeNodeList.cs index 3c92944b2..6e9303a1e 100644 --- a/src/NzbDrone.Common/Expansive/TreeNodeList.cs +++ b/src/NzbDrone.Common/Expansive/TreeNodeList.cs @@ -6,27 +6,26 @@ internal class TreeNodeList : List> { public TreeNode Parent; - public TreeNodeList(TreeNode Parent) + public TreeNodeList(TreeNode parent) { - this.Parent = Parent; + this.Parent = parent; } - public new TreeNode Add(TreeNode Node) + public new TreeNode Add(TreeNode node) { - base.Add(Node); - Node.Parent = Parent; - return Node; + base.Add(node); + node.Parent = Parent; + return node; } - public TreeNode Add(T Value) + public TreeNode Add(T value) { - return Add(new TreeNode(Value)); + return Add(new TreeNode(value)); } - public override string ToString() { return "Count=" + Count.ToString(); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common/Extensions/ExceptionExtensions.cs b/src/NzbDrone.Common/Extensions/ExceptionExtensions.cs index ec07e73ed..cdc57681b 100644 --- a/src/NzbDrone.Common/Extensions/ExceptionExtensions.cs +++ b/src/NzbDrone.Common/Extensions/ExceptionExtensions.cs @@ -7,30 +7,37 @@ namespace NzbDrone.Common.Extensions { public static class ExceptionExtensions { - public static T WithData(this T ex, string key, string value) where T : Exception + public static T WithData(this T ex, string key, string value) + where T : Exception { ex.AddData(key, value); return ex; } - public static T WithData(this T ex, string key, int value) where T : Exception + + public static T WithData(this T ex, string key, int value) + where T : Exception { ex.AddData(key, value.ToString()); return ex; } - public static T WithData(this T ex, string key, Http.HttpUri value) where T : Exception + public static T WithData(this T ex, string key, Http.HttpUri value) + where T : Exception { ex.AddData(key, value.ToString()); return ex; } - - public static T WithData(this T ex, Http.HttpResponse response, int maxSampleLength = 512) where T : Exception + public static T WithData(this T ex, Http.HttpResponse response, int maxSampleLength = 512) + where T : Exception { - if (response == null || response.Content == null) return ex; + if (response == null || response.Content == null) + { + return ex; + } var contentSample = response.Content.Substring(0, Math.Min(response.Content.Length, maxSampleLength)); @@ -50,16 +57,19 @@ public static T WithData(this T ex, Http.HttpResponse response, int maxSample { ex.AddData("ContentType", response.Headers.ContentType ?? string.Empty); } + ex.AddData("ContentLength", response.Content.Length.ToString()); ex.AddData("ContentSample", contentSample); return ex; } - private static void AddData(this Exception ex, string key, string value) { - if (value.IsNullOrWhiteSpace()) return; + if (value.IsNullOrWhiteSpace()) + { + return; + } ex.Data[key] = value; } diff --git a/src/NzbDrone.Common/Extensions/IEnumerableExtensions.cs b/src/NzbDrone.Common/Extensions/IEnumerableExtensions.cs index 0d2b6fb11..4af3c5f67 100644 --- a/src/NzbDrone.Common/Extensions/IEnumerableExtensions.cs +++ b/src/NzbDrone.Common/Extensions/IEnumerableExtensions.cs @@ -7,9 +7,11 @@ namespace NzbDrone.Common.Extensions { public static class EnumerableExtensions { - public static IEnumerable IntersectBy(this IEnumerable first, Func firstKeySelector, - IEnumerable second, Func secondKeySelector, - IEqualityComparer keyComparer) + public static IEnumerable IntersectBy(this IEnumerable first, + Func firstKeySelector, + IEnumerable second, + Func secondKeySelector, + IEqualityComparer keyComparer) { var keys = new HashSet(second.Select(secondKeySelector), keyComparer); @@ -25,9 +27,11 @@ public static IEnumerable IntersectBy(this IEnume } } - public static IEnumerable ExceptBy(this IEnumerable first, Func firstKeySelector, - IEnumerable second, Func secondKeySelector, - IEqualityComparer keyComparer) + public static IEnumerable ExceptBy(this IEnumerable first, + Func firstKeySelector, + IEnumerable second, + Func secondKeySelector, + IEqualityComparer keyComparer) { var keys = new HashSet(second.Select(secondKeySelector), keyComparer); var matchedKeys = new HashSet(); @@ -56,6 +60,7 @@ public static Dictionary ToDictionaryIgnoreDuplicates( result[key] = item; } } + return result; } @@ -70,6 +75,7 @@ public static Dictionary ToDictionaryIgnoreDuplicates(this T source) where T : new() + public static T JsonClone(this T source) + where T : new() { var json = source.ToJson(); return Json.Deserialize(json); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common/Extensions/PathExtensions.cs b/src/NzbDrone.Common/Extensions/PathExtensions.cs index d03e2b1fd..e46311f39 100644 --- a/src/NzbDrone.Common/Extensions/PathExtensions.cs +++ b/src/NzbDrone.Common/Extensions/PathExtensions.cs @@ -113,6 +113,7 @@ public static bool IsParentPath(this string parentPath, string childPath) { parentPath = parentPath.TrimEnd(Path.DirectorySeparatorChar); } + if (childPath != "/" && !parentPath.EndsWith(":\\")) { childPath = childPath.TrimEnd(Path.DirectorySeparatorChar); diff --git a/src/NzbDrone.Common/Extensions/StreamExtensions.cs b/src/NzbDrone.Common/Extensions/StreamExtensions.cs index 6283f5fc0..8f6036baa 100644 --- a/src/NzbDrone.Common/Extensions/StreamExtensions.cs +++ b/src/NzbDrone.Common/Extensions/StreamExtensions.cs @@ -14,6 +14,7 @@ public static byte[] ToBytes(this Stream input) { ms.Write(buffer, 0, read); } + return ms.ToArray(); } } diff --git a/src/NzbDrone.Common/Extensions/StringExtensions.cs b/src/NzbDrone.Common/Extensions/StringExtensions.cs index 827a34aa3..fa9d4e7ba 100644 --- a/src/NzbDrone.Common/Extensions/StringExtensions.cs +++ b/src/NzbDrone.Common/Extensions/StringExtensions.cs @@ -18,7 +18,11 @@ public static string NullSafe(this string target) public static object NullSafe(this object target) { - if (target != null) return target; + if (target != null) + { + return target; + } + return "[NULL]"; } @@ -76,7 +80,9 @@ public static string RemoveAccent(this string text) public static string TrimEnd(this string text, string postfix) { if (text.EndsWith(postfix)) + { text = text.Substring(0, text.Length - postfix.Length); + } return text; } @@ -134,7 +140,7 @@ public static string WrapInQuotes(this string text) public static byte[] HexToByteArray(this string input) { return Enumerable.Range(0, input.Length) - .Where(x => x%2 == 0) + .Where(x => x % 2 == 0) .Select(x => Convert.ToByte(input.Substring(x, 2), 16)) .ToArray(); } @@ -151,9 +157,9 @@ public static string FromOctalString(this string octalValue) var first = int.Parse(octalValue.Substring(0, 1)); var second = int.Parse(octalValue.Substring(1, 1)); var third = int.Parse(octalValue.Substring(2, 1)); - var byteResult = (byte)((first << 6) | (second << 3) | (third)); + var byteResult = (byte)((first << 6) | (second << 3) | third); - return Encoding.ASCII.GetString(new [] { byteResult }); + return Encoding.ASCII.GetString(new[] { byteResult }); } public static string SplitCamelCase(this string input) @@ -165,7 +171,7 @@ public static bool ContainsIgnoreCase(this IEnumerable source, string va { return source.Contains(value, StringComparer.InvariantCultureIgnoreCase); } - + public static string ToUrlSlug(this string value) { //First to lower case diff --git a/src/NzbDrone.Common/Extensions/UrlExtensions.cs b/src/NzbDrone.Common/Extensions/UrlExtensions.cs index 50e0b9856..e44843838 100644 --- a/src/NzbDrone.Common/Extensions/UrlExtensions.cs +++ b/src/NzbDrone.Common/Extensions/UrlExtensions.cs @@ -28,7 +28,6 @@ public static bool IsValidUrl(this string path) } return true; - } } } diff --git a/src/NzbDrone.Common/HashUtil.cs b/src/NzbDrone.Common/HashUtil.cs index 9038848a8..a60349271 100644 --- a/src/NzbDrone.Common/HashUtil.cs +++ b/src/NzbDrone.Common/HashUtil.cs @@ -24,6 +24,7 @@ public static string CalculateCrc(string input) } } } + return $"{mCrc:x8}"; } diff --git a/src/NzbDrone.Common/Http/Dispatchers/ManagedHttpDispatcher.cs b/src/NzbDrone.Common/Http/Dispatchers/ManagedHttpDispatcher.cs index 48e8b6ec6..538e8b79e 100644 --- a/src/NzbDrone.Common/Http/Dispatchers/ManagedHttpDispatcher.cs +++ b/src/NzbDrone.Common/Http/Dispatchers/ManagedHttpDispatcher.cs @@ -197,6 +197,7 @@ private void AbortWebRequest(HttpWebRequest webRequest) { var responseStreamInfo = currentOperation.GetType().GetField("responseStream", BindingFlags.NonPublic | BindingFlags.Instance); var responseStream = responseStreamInfo.GetValue(currentOperation) as Stream; + // Note that responseStream will likely be null once mono fixes it. responseStream?.Dispose(); } diff --git a/src/NzbDrone.Common/Http/GZipWebClient.cs b/src/NzbDrone.Common/Http/GZipWebClient.cs index 6b8ddb582..191bfb10b 100644 --- a/src/NzbDrone.Common/Http/GZipWebClient.cs +++ b/src/NzbDrone.Common/Http/GZipWebClient.cs @@ -12,4 +12,4 @@ protected override WebRequest GetWebRequest(Uri address) return request; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common/Http/HttpAccept.cs b/src/NzbDrone.Common/Http/HttpAccept.cs index 478d1efe8..21367b3a6 100644 --- a/src/NzbDrone.Common/Http/HttpAccept.cs +++ b/src/NzbDrone.Common/Http/HttpAccept.cs @@ -6,7 +6,7 @@ public sealed class HttpAccept public static readonly HttpAccept Json = new HttpAccept("application/json"); public static readonly HttpAccept JsonCharset = new HttpAccept("application/json; charset=utf-8"); public static readonly HttpAccept Html = new HttpAccept("text/html"); - + public string Value { get; private set; } public HttpAccept(string accept) diff --git a/src/NzbDrone.Common/Http/HttpClient.cs b/src/NzbDrone.Common/Http/HttpClient.cs index 41bb511ba..775c12fb6 100644 --- a/src/NzbDrone.Common/Http/HttpClient.cs +++ b/src/NzbDrone.Common/Http/HttpClient.cs @@ -18,10 +18,12 @@ public interface IHttpClient HttpResponse Execute(HttpRequest request); void DownloadFile(string url, string fileName); HttpResponse Get(HttpRequest request); - HttpResponse Get(HttpRequest request) where T : new(); + HttpResponse Get(HttpRequest request) + where T : new(); HttpResponse Head(HttpRequest request); HttpResponse Post(HttpRequest request); - HttpResponse Post(HttpRequest request) where T : new(); + HttpResponse Post(HttpRequest request) + where T : new(); } public class HttpClient : IHttpClient @@ -258,11 +260,13 @@ public void DownloadFile(string url, string fileName) throw new HttpException(request, response, "Site responded with html content."); } } + stopWatch.Stop(); if (File.Exists(fileName)) { File.Delete(fileName); } + File.Move(fileNamePart, fileName); _logger.Debug("Downloading Completed. took {0:0}s", stopWatch.Elapsed.Seconds); } @@ -271,7 +275,7 @@ public void DownloadFile(string url, string fileName) if (File.Exists(fileNamePart)) { File.Delete(fileNamePart); - } + } } } @@ -281,7 +285,8 @@ public HttpResponse Get(HttpRequest request) return Execute(request); } - public HttpResponse Get(HttpRequest request) where T : new() + public HttpResponse Get(HttpRequest request) + where T : new() { var response = Get(request); CheckResponseContentType(response); @@ -300,7 +305,8 @@ public HttpResponse Post(HttpRequest request) return Execute(request); } - public HttpResponse Post(HttpRequest request) where T : new() + public HttpResponse Post(HttpRequest request) + where T : new() { var response = Post(request); CheckResponseContentType(response); diff --git a/src/NzbDrone.Common/Http/HttpException.cs b/src/NzbDrone.Common/Http/HttpException.cs index d3f5c2da4..c3ad7a1fa 100644 --- a/src/NzbDrone.Common/Http/HttpException.cs +++ b/src/NzbDrone.Common/Http/HttpException.cs @@ -17,13 +17,11 @@ public HttpException(HttpRequest request, HttpResponse response, string message) public HttpException(HttpRequest request, HttpResponse response) : this(request, response, string.Format("HTTP request failed: [{0}:{1}] [{2}] at [{3}]", (int)response.StatusCode, response.StatusCode, request.Method, request.Url)) { - } public HttpException(HttpResponse response) : this(response.Request, response) { - } public override string ToString() diff --git a/src/NzbDrone.Common/Http/HttpHeader.cs b/src/NzbDrone.Common/Http/HttpHeader.cs index 8cf25489a..2794f6dc4 100644 --- a/src/NzbDrone.Common/Http/HttpHeader.cs +++ b/src/NzbDrone.Common/Http/HttpHeader.cs @@ -1,11 +1,11 @@ using System; -using System.Linq; +using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; +using System.Globalization; +using System.Linq; using System.Text; using NzbDrone.Common.Extensions; -using System.Collections; -using System.Globalization; namespace NzbDrone.Common.Http { @@ -14,12 +14,10 @@ public class HttpHeader : NameValueCollection, IEnumerable 1) { throw new ApplicationException($"Expected {key} to occur only once, but was {values.Join("|")}."); @@ -43,7 +42,8 @@ public string GetSingleValue(string key) return values[0]; } - protected T? GetSingleValue(string key, Func converter) where T : struct + protected T? GetSingleValue(string key, Func converter) + where T : struct { var value = GetSingleValue(key); if (value == null) @@ -53,6 +53,7 @@ public string GetSingleValue(string key) return converter(value); } + protected void SetSingleValue(string key, string value) { if (value == null) @@ -65,7 +66,8 @@ protected void SetSingleValue(string key, string value) } } - protected void SetSingleValue(string key, T? value, Func converter = null) where T : struct + protected void SetSingleValue(string key, T? value, Func converter = null) + where T : struct { if (!value.HasValue) { diff --git a/src/NzbDrone.Common/Http/HttpMethod.cs b/src/NzbDrone.Common/Http/HttpMethod.cs index c5f7b5307..8839c0c52 100644 --- a/src/NzbDrone.Common/Http/HttpMethod.cs +++ b/src/NzbDrone.Common/Http/HttpMethod.cs @@ -11,4 +11,4 @@ public enum HttpMethod PATCH, MERGE } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common/Http/HttpRequest.cs b/src/NzbDrone.Common/Http/HttpRequest.cs index 641df0c37..4b9e80f67 100644 --- a/src/NzbDrone.Common/Http/HttpRequest.cs +++ b/src/NzbDrone.Common/Http/HttpRequest.cs @@ -19,7 +19,6 @@ public HttpRequest(string url, HttpAccept httpAccept = null) LogHttpError = true; Cookies = new Dictionary(); - if (!RuntimeInfo.IsProduction) { AllowAutoRedirect = false; diff --git a/src/NzbDrone.Common/Http/HttpRequestBuilder.cs b/src/NzbDrone.Common/Http/HttpRequestBuilder.cs index 128405202..fe4b2a4ca 100644 --- a/src/NzbDrone.Common/Http/HttpRequestBuilder.cs +++ b/src/NzbDrone.Common/Http/HttpRequestBuilder.cs @@ -48,7 +48,6 @@ public HttpRequestBuilder(string baseUrl) public HttpRequestBuilder(bool useHttps, string host, int port, string urlBase = null) : this(BuildBaseUrl(useHttps, host, port, urlBase)) { - } public static string BuildBaseUrl(bool useHttps, string host, int port, string urlBase = null) @@ -151,7 +150,10 @@ public IHttpRequestBuilderFactory CreateFactory() protected virtual void ApplyFormData(HttpRequest request) { - if (FormData.Empty()) return; + if (FormData.Empty()) + { + return; + } if (request.ContentData != null) { @@ -176,11 +178,22 @@ protected virtual void ApplyFormData(HttpRequest request) writer.Write(partBoundary); writer.Write("Content-Disposition: form-data"); - if (formData.Name.IsNotNullOrWhiteSpace()) writer.Write("; name=\"{0}\"", formData.Name); - if (formData.FileName.IsNotNullOrWhiteSpace()) writer.Write("; filename=\"{0}\"", formData.FileName); + if (formData.Name.IsNotNullOrWhiteSpace()) + { + writer.Write("; name=\"{0}\"", formData.Name); + } + + if (formData.FileName.IsNotNullOrWhiteSpace()) + { + writer.Write("; filename=\"{0}\"", formData.FileName); + } + writer.Write("\r\n"); - if (formData.ContentType.IsNotNullOrWhiteSpace()) writer.Write("Content-Type: {0}\r\n", formData.ContentType); + if (formData.ContentType.IsNotNullOrWhiteSpace()) + { + writer.Write("Content-Type: {0}\r\n", formData.ContentType); + } writer.Write("\r\n"); writer.Flush(); @@ -382,5 +395,4 @@ public virtual HttpRequestBuilder AddFormUpload(string name, string fileName, by return this; } } - } diff --git a/src/NzbDrone.Common/Http/HttpRequestBuilderFactory.cs b/src/NzbDrone.Common/Http/HttpRequestBuilderFactory.cs index 18ee914a7..b7a616143 100644 --- a/src/NzbDrone.Common/Http/HttpRequestBuilderFactory.cs +++ b/src/NzbDrone.Common/Http/HttpRequestBuilderFactory.cs @@ -16,7 +16,6 @@ public HttpRequestBuilderFactory(HttpRequestBuilder rootBuilder) protected HttpRequestBuilderFactory() { - } protected void SetRootBuilder(HttpRequestBuilder rootBuilder) diff --git a/src/NzbDrone.Common/Http/HttpResponse.cs b/src/NzbDrone.Common/Http/HttpResponse.cs index 8f58d0a1a..475367dea 100644 --- a/src/NzbDrone.Common/Http/HttpResponse.cs +++ b/src/NzbDrone.Common/Http/HttpResponse.cs @@ -48,7 +48,6 @@ public string Content } } - public bool HasHttpError => (int)StatusCode >= 400; public bool HasHttpRedirect => StatusCode == HttpStatusCode.Moved || @@ -93,8 +92,8 @@ public override string ToString() } } - - public class HttpResponse : HttpResponse where T : new() + public class HttpResponse : HttpResponse + where T : new() { public HttpResponse(HttpResponse response) : base(response.Request, response.Headers, response.ResponseData, response.StatusCode) diff --git a/src/NzbDrone.Common/Http/HttpUri.cs b/src/NzbDrone.Common/Http/HttpUri.cs index a1398e393..248e4fddc 100644 --- a/src/NzbDrone.Common/Http/HttpUri.cs +++ b/src/NzbDrone.Common/Http/HttpUri.cs @@ -47,6 +47,7 @@ public HttpUri(string scheme, string host, int? port, string path, string query, { builder.Append('/'); } + builder.Append(path.TrimStart('/')); } @@ -78,7 +79,7 @@ private void Parse() var query = match.Groups["query"]; var fragment = match.Groups["fragment"]; - if (!match.Success || scheme.Success && !host.Success && path.Success) + if (!match.Success || (scheme.Success && !host.Success && path.Success)) { throw new ArgumentException("Uri didn't match expected pattern: " + _uri); } @@ -126,6 +127,7 @@ private IList> QueryParams _queryParams = dict.AsReadOnly(); } + return _queryParams; } } @@ -200,6 +202,7 @@ public HttpUri AddQueryParams(IEnumerable> queryPar { builder.Append("&"); } + builder.Append(Uri.EscapeDataString(pair.Key)); builder.Append("="); builder.Append(Uri.EscapeDataString(pair.Value)); @@ -208,7 +211,6 @@ public HttpUri AddQueryParams(IEnumerable> queryPar return SetQuery(builder.ToString()); } - public override int GetHashCode() { return _uri.GetHashCode(); @@ -237,7 +239,10 @@ public override bool Equals(object obj) public bool Equals(HttpUri other) { - if (object.ReferenceEquals(other, null)) return false; + if (object.ReferenceEquals(other, null)) + { + return false; + } return _uri.Equals(other._uri); } diff --git a/src/NzbDrone.Common/Http/JsonRpcRequestBuilder.cs b/src/NzbDrone.Common/Http/JsonRpcRequestBuilder.cs index 3722fd9ce..ae987a23d 100644 --- a/src/NzbDrone.Common/Http/JsonRpcRequestBuilder.cs +++ b/src/NzbDrone.Common/Http/JsonRpcRequestBuilder.cs @@ -22,7 +22,7 @@ public JsonRpcRequestBuilder(string baseUrl) } public JsonRpcRequestBuilder(string baseUrl, string method, IEnumerable parameters) - : base (baseUrl) + : base(baseUrl) { Method = HttpMethod.POST; JsonMethod = method; diff --git a/src/NzbDrone.Common/Http/Proxy/HttpProxySettings.cs b/src/NzbDrone.Common/Http/Proxy/HttpProxySettings.cs index 3d22f245f..58a7541da 100644 --- a/src/NzbDrone.Common/Http/Proxy/HttpProxySettings.cs +++ b/src/NzbDrone.Common/Http/Proxy/HttpProxySettings.cs @@ -30,15 +30,17 @@ public string[] BypassListAsArray if (!string.IsNullOrWhiteSpace(BypassFilter)) { var hostlist = BypassFilter.Split(','); - for(int i = 0; i < hostlist.Length; i++) + for (int i = 0; i < hostlist.Length; i++) { - if(hostlist[i].StartsWith("*")) + if (hostlist[i].StartsWith("*")) { hostlist[i] = ";" + hostlist[i]; } } + return hostlist; } + return new string[] { }; } } diff --git a/src/NzbDrone.Common/Http/Proxy/ManagedWebProxyFactory.cs b/src/NzbDrone.Common/Http/Proxy/ManagedWebProxyFactory.cs index 4e0a8458b..ca58fedee 100644 --- a/src/NzbDrone.Common/Http/Proxy/ManagedWebProxyFactory.cs +++ b/src/NzbDrone.Common/Http/Proxy/ManagedWebProxyFactory.cs @@ -31,6 +31,7 @@ public IWebProxy GetWebProxy(HttpProxySettings proxySettings) return proxy; } + private IWebProxy CreateWebProxy(HttpProxySettings proxySettings) { switch (proxySettings.Type) @@ -44,6 +45,7 @@ private IWebProxy CreateWebProxy(HttpProxySettings proxySettings) { return new WebProxy(proxySettings.Host + ":" + proxySettings.Port, proxySettings.BypassLocalAddress, proxySettings.BypassListAsArray); } + case ProxyType.Socks4: return new SocksWebProxy(new ProxyConfig(IPAddress.Loopback, GetNextFreePort(), GetProxyIpAddress(proxySettings.Host), proxySettings.Port, ProxyConfig.SocksVersion.Four, proxySettings.Username, proxySettings.Password), false); case ProxyType.Socks5: diff --git a/src/NzbDrone.Common/Http/TlsFailureException.cs b/src/NzbDrone.Common/Http/TlsFailureException.cs index cb1b5f93a..f144ec69a 100644 --- a/src/NzbDrone.Common/Http/TlsFailureException.cs +++ b/src/NzbDrone.Common/Http/TlsFailureException.cs @@ -11,8 +11,6 @@ public class TlsFailureException : WebException public TlsFailureException(WebRequest request, WebException innerException) : base("Failed to establish secure https connection to '" + request.RequestUri + "'.", innerException, WebExceptionStatus.SecureChannelFailure, innerException.Response) { - } - } } diff --git a/src/NzbDrone.Common/Http/UnexpectedHtmlContentException.cs b/src/NzbDrone.Common/Http/UnexpectedHtmlContentException.cs index 4264f7cfe..9007930a4 100644 --- a/src/NzbDrone.Common/Http/UnexpectedHtmlContentException.cs +++ b/src/NzbDrone.Common/Http/UnexpectedHtmlContentException.cs @@ -7,7 +7,6 @@ public class UnexpectedHtmlContentException : HttpException public UnexpectedHtmlContentException(HttpResponse response) : base(response.Request, response, $"Site responded with browser content instead of api data. This disruption may be temporary, please try again later. [{response.Request.Url}]") { - } } } diff --git a/src/NzbDrone.Common/Http/UserAgentBuilder.cs b/src/NzbDrone.Common/Http/UserAgentBuilder.cs index 525b8ee0b..b750cffe7 100644 --- a/src/NzbDrone.Common/Http/UserAgentBuilder.cs +++ b/src/NzbDrone.Common/Http/UserAgentBuilder.cs @@ -37,4 +37,4 @@ public UserAgentBuilder(IOsInfo osInfo) _userAgentSimplified = $"{BuildInfo.AppName}/{BuildInfo.Version.ToString(2)}"; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common/Instrumentation/CleanseLogMessage.cs b/src/NzbDrone.Common/Instrumentation/CleanseLogMessage.cs index 92969a0e9..2c56d6929 100644 --- a/src/NzbDrone.Common/Instrumentation/CleanseLogMessage.cs +++ b/src/NzbDrone.Common/Instrumentation/CleanseLogMessage.cs @@ -18,10 +18,10 @@ public class CleanseLogMessage new Regex(@"iptorrents\.com/[/a-z0-9?&;]*?(?:[?&;](u|tp)=(?[^&=;]+?))+(?= |;|&|$)", RegexOptions.Compiled | RegexOptions.IgnoreCase), new Regex(@"/fetch/[a-z0-9]{32}/(?[a-z0-9]{32})", RegexOptions.Compiled), new Regex(@"getnzb.*?(?<=\?|&)(r)=(?[^&=]+?)(?= |&|$)", RegexOptions.Compiled | RegexOptions.IgnoreCase), - + // Trackers Announce Keys; Designed for Qbit Json; should work for all in theory new Regex(@"announce(\.php)?(/|%2f|%3fpasskey%3d)(?[a-z0-9]{16,})|(?[a-z0-9]{16,})(/|%2f)announce"), - + // Path new Regex(@"C:\\Users\\(?[^\""]+?)(\\|$)", RegexOptions.Compiled | RegexOptions.IgnoreCase), new Regex(@"/home/(?[^/""]+?)(/|$)", RegexOptions.Compiled | RegexOptions.IgnoreCase), diff --git a/src/NzbDrone.Common/Instrumentation/CleansingJsonVisitor.cs b/src/NzbDrone.Common/Instrumentation/CleansingJsonVisitor.cs index f33f4587b..bb9f0c4c9 100644 --- a/src/NzbDrone.Common/Instrumentation/CleansingJsonVisitor.cs +++ b/src/NzbDrone.Common/Instrumentation/CleansingJsonVisitor.cs @@ -19,6 +19,7 @@ public override void Visit(JArray json) json[i] = new JValue(CleanseLogMessage.Cleanse(text)); } } + foreach (JToken token in json) { Visit(token); diff --git a/src/NzbDrone.Common/Instrumentation/LogEventExtensions.cs b/src/NzbDrone.Common/Instrumentation/LogEventExtensions.cs index 4589050e0..2c8e7c8a0 100644 --- a/src/NzbDrone.Common/Instrumentation/LogEventExtensions.cs +++ b/src/NzbDrone.Common/Instrumentation/LogEventExtensions.cs @@ -29,10 +29,9 @@ public static string GetFormattedMessage(this LogEventInfo logEvent) message += ": " + logEvent.Exception.Message; } } - } return message; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common/Instrumentation/NzbDroneLogger.cs b/src/NzbDrone.Common/Instrumentation/NzbDroneLogger.cs index 35eafdaf6..4b2186779 100644 --- a/src/NzbDrone.Common/Instrumentation/NzbDroneLogger.cs +++ b/src/NzbDrone.Common/Instrumentation/NzbDroneLogger.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Diagnostics; using System.IO; using System.Linq; @@ -13,6 +13,8 @@ namespace NzbDrone.Common.Instrumentation { public static class NzbDroneLogger { + private const string FILE_LOG_LAYOUT = @"${date:format=yyyy-MM-dd HH\:mm\:ss.f}|${level}|${logger}|${message}${onexception:inner=${newline}${newline}[v${assembly-version}] ${exception:format=ToString}${newline}}"; + private static bool _isConfigured; static NzbDroneLogger() @@ -20,7 +22,6 @@ static NzbDroneLogger() LogManager.Configuration = new LoggingConfiguration(); } - public static void Register(IStartupContext startupContext, bool updateApp, bool inConsole) { if (_isConfigured) @@ -69,7 +70,6 @@ private static void RegisterSentry(bool updateClient) dsn = RuntimeInfo.IsProduction ? "https://80777986b95f44a1a90d1eb2f3af1e36@sentry.sonarr.tv/11" : "https://6168f0946aba4e60ac23e469ac08eac5@sentry.sonarr.tv/9"; - } else { @@ -131,8 +131,6 @@ private static void RegisterConsole() LogManager.Configuration.LoggingRules.Add(loggingRule); } - private const string FILE_LOG_LAYOUT = @"${date:format=yyyy-MM-dd HH\:mm\:ss.f}|${level}|${logger}|${message}${onexception:inner=${newline}${newline}[v${assembly-version}] ${exception:format=ToString}${newline}}"; - private static void RegisterAppFile(IAppFolderInfo appFolderInfo) { RegisterAppFile(appFolderInfo, "appFileInfo", "sonarr.txt", 5, LogLevel.Info); @@ -208,6 +206,5 @@ public static Logger GetLogger(object obj) { return GetLogger(obj.GetType()); } - } } diff --git a/src/NzbDrone.Common/Instrumentation/Sentry/SentryCleanser.cs b/src/NzbDrone.Common/Instrumentation/Sentry/SentryCleanser.cs index 7d351a55a..76f0bcb54 100644 --- a/src/NzbDrone.Common/Instrumentation/Sentry/SentryCleanser.cs +++ b/src/NzbDrone.Common/Instrumentation/Sentry/SentryCleanser.cs @@ -36,7 +36,6 @@ public static SentryEvent CleanseEvent(SentryEvent sentryEvent) } catch (Exception) { - } return sentryEvent; @@ -50,9 +49,8 @@ public static Breadcrumb CleanseBreadcrumb(Breadcrumb b) var data = b.Data?.ToDictionary(x => x.Key, y => CleanseLogMessage.Cleanse(y.Value)); return new Breadcrumb(message, b.Type, data, b.Category, b.Level); } - catch(Exception) + catch (Exception) { - } return b; @@ -60,7 +58,6 @@ public static Breadcrumb CleanseBreadcrumb(Breadcrumb b) private static string ShortenPath(string path) { - if (string.IsNullOrWhiteSpace(path)) { return null; @@ -68,7 +65,7 @@ private static string ShortenPath(string path) // the paths in the stacktrace depend on where it was compiled, // not the current OS - var rootDirs = new [] { "\\src\\", "/src/" }; + var rootDirs = new[] { "\\src\\", "/src/" }; foreach (var rootDir in rootDirs) { var index = path.IndexOf(rootDir, StringComparison.Ordinal); diff --git a/src/NzbDrone.Common/Instrumentation/Sentry/SentryDebounce.cs b/src/NzbDrone.Common/Instrumentation/Sentry/SentryDebounce.cs index 942f3934a..77585e7a7 100644 --- a/src/NzbDrone.Common/Instrumentation/Sentry/SentryDebounce.cs +++ b/src/NzbDrone.Common/Instrumentation/Sentry/SentryDebounce.cs @@ -35,4 +35,4 @@ public void Clear() _cache.Clear(); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common/Instrumentation/Sentry/SentryTarget.cs b/src/NzbDrone.Common/Instrumentation/Sentry/SentryTarget.cs index 3248354b8..585d5a4af 100644 --- a/src/NzbDrone.Common/Instrumentation/Sentry/SentryTarget.cs +++ b/src/NzbDrone.Common/Instrumentation/Sentry/SentryTarget.cs @@ -40,8 +40,10 @@ public class SentryTarget : TargetWithLayout { // UnauthorizedAccessExceptions will just be user configuration issues "UnauthorizedAccessException", + // Filter out people stuck in boot loops "CorruptDatabaseException", + // This also filters some people in boot loops "TinyIoCResolutionException" }; @@ -202,6 +204,7 @@ private static List GetFingerPrint(LogEventInfo logEvent) { fingerPrint.Add(ex.TargetSite.ToString()); } + if (ex.InnerException != null) { fingerPrint.Add(ex.InnerException.GetType().FullName); @@ -249,7 +252,6 @@ public bool IsSentryMessage(LogEventInfo logEvent) return false; } - protected override void Write(LogEventInfo logEvent) { if (_unauthorized || !SentryEnabled) @@ -314,6 +316,7 @@ protected override void Dispose(bool disposing) { _sdk?.Dispose(); } + // Flag us as disposed. This allows us to handle multiple calls to Dispose() as well as ObjectDisposedException _disposed = true; } diff --git a/src/NzbDrone.Common/Messaging/IEvent.cs b/src/NzbDrone.Common/Messaging/IEvent.cs index 00f40b449..70800b9e1 100644 --- a/src/NzbDrone.Common/Messaging/IEvent.cs +++ b/src/NzbDrone.Common/Messaging/IEvent.cs @@ -3,4 +3,4 @@ namespace NzbDrone.Common.Messaging public interface IEvent : IMessage { } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common/Messaging/IMessage.cs b/src/NzbDrone.Common/Messaging/IMessage.cs index 1c7b25371..5a005a093 100644 --- a/src/NzbDrone.Common/Messaging/IMessage.cs +++ b/src/NzbDrone.Common/Messaging/IMessage.cs @@ -3,4 +3,4 @@ namespace NzbDrone.Common.Messaging public interface IMessage { } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common/Model/ProcessInfo.cs b/src/NzbDrone.Common/Model/ProcessInfo.cs index 9eb8df647..4f4943189 100644 --- a/src/NzbDrone.Common/Model/ProcessInfo.cs +++ b/src/NzbDrone.Common/Model/ProcessInfo.cs @@ -11,4 +11,4 @@ public override string ToString() return string.Format("{0}:{1} [{2}]", Id, Name ?? "Unknown", StartPath ?? "Unknown"); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common/OAuth/OAuthRequest.cs b/src/NzbDrone.Common/OAuth/OAuthRequest.cs index 4b5692c2a..99275bf03 100644 --- a/src/NzbDrone.Common/OAuth/OAuthRequest.cs +++ b/src/NzbDrone.Common/OAuth/OAuthRequest.cs @@ -492,5 +492,3 @@ private static bool IsNullOrBlank(string value) } } } - - diff --git a/src/NzbDrone.Common/OAuth/OAuthTools.cs b/src/NzbDrone.Common/OAuth/OAuthTools.cs index 17422478e..20ea671b6 100644 --- a/src/NzbDrone.Common/OAuth/OAuthTools.cs +++ b/src/NzbDrone.Common/OAuth/OAuthTools.cs @@ -71,6 +71,7 @@ public static string GetNonce() nonce[i] = chars[_random.Next(0, chars.Length)]; } } + return new string(nonce); } @@ -138,6 +139,7 @@ private static string PercentEncode(string s) sb.Append(string.Format("%{0:X}", b)); } } + return sb.ToString(); } @@ -380,6 +382,7 @@ public static string GetSignature(OAuthSignatureMethod signatureMethod, break; } + default: throw new NotImplementedException("Only HMAC-SHA1 is currently supported."); } diff --git a/src/NzbDrone.Common/OAuth/WebParameterCollection.cs b/src/NzbDrone.Common/OAuth/WebParameterCollection.cs index af3e92439..a1084a0ef 100644 --- a/src/NzbDrone.Common/OAuth/WebParameterCollection.cs +++ b/src/NzbDrone.Common/OAuth/WebParameterCollection.cs @@ -1,8 +1,8 @@ using System; using System.Collections; using System.Collections.Generic; -using System.Linq; using System.Collections.Specialized; +using System.Linq; namespace NzbDrone.Common.OAuth { @@ -15,13 +15,13 @@ public virtual WebParameter this[string name] get { var parameters = this.Where(p => p.Name.Equals(name)); - - if(parameters.Count() == 0) + + if (parameters.Count() == 0) { return null; } - if(parameters.Count() == 1) + if (parameters.Count() == 1) { return parameters.Single(); } @@ -47,7 +47,8 @@ public WebParameterCollection(IEnumerable parameters) } #if !WINRT - public WebParameterCollection(NameValueCollection collection) : this() + public WebParameterCollection(NameValueCollection collection) + : this() { AddCollection(collection); } @@ -67,7 +68,8 @@ private void AddCollection(NameValueCollection collection) } #endif - public WebParameterCollection(IDictionary collection) : this() + public WebParameterCollection(IDictionary collection) + : this() { AddCollection(collection); } @@ -128,8 +130,6 @@ public virtual void Add(string name, string value) _parameters.Add(pair); } - #region IList Members - public virtual IEnumerator GetEnumerator() { return _parameters.GetEnumerator(); @@ -142,7 +142,6 @@ IEnumerator IEnumerable.GetEnumerator() public virtual void Add(WebParameter parameter) { - _parameters.Add(parameter); } @@ -196,7 +195,5 @@ public virtual WebParameter this[int index] get { return _parameters[index]; } set { _parameters[index] = value; } } - - #endregion } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common/PathEqualityComparer.cs b/src/NzbDrone.Common/PathEqualityComparer.cs index f015792c3..d443a3bf0 100644 --- a/src/NzbDrone.Common/PathEqualityComparer.cs +++ b/src/NzbDrone.Common/PathEqualityComparer.cs @@ -10,7 +10,6 @@ public class PathEqualityComparer : IEqualityComparer private PathEqualityComparer() { - } public bool Equals(string x, string y) diff --git a/src/NzbDrone.Common/Processes/ProcessProvider.cs b/src/NzbDrone.Common/Processes/ProcessProvider.cs index 829dcacb4..0cff38afe 100644 --- a/src/NzbDrone.Common/Processes/ProcessProvider.cs +++ b/src/NzbDrone.Common/Processes/ProcessProvider.cs @@ -135,7 +135,6 @@ public Process Start(string path, string args = null, StringDictionary environme { _logger.Error(e, "Unable to set environment variable '{0}', value is null", environmentVariable.Key); } - else { _logger.Error(e, "Unable to set environment variable '{0}'", environmentVariable.Key); @@ -323,7 +322,6 @@ private ProcessInfo ConvertToProcessInfo(Process process) } return processInfo; - } private static string GetExeFileName(Process process) diff --git a/src/NzbDrone.Common/Reflection/ReflectionExtensions.cs b/src/NzbDrone.Common/Reflection/ReflectionExtensions.cs index 2dba971c6..d832e0f27 100644 --- a/src/NzbDrone.Common/Reflection/ReflectionExtensions.cs +++ b/src/NzbDrone.Common/Reflection/ReflectionExtensions.cs @@ -29,7 +29,6 @@ public static bool IsSimpleType(this Type type) type = type.GetGenericArguments()[0]; } - return type.IsPrimitive || type.IsEnum || type == typeof(string) @@ -48,7 +47,8 @@ public static bool IsWritable(this PropertyInfo propertyInfo) return propertyInfo.CanWrite && propertyInfo.GetSetMethod(false) != null; } - public static T GetAttribute(this MemberInfo member, bool isRequired = true) where T : Attribute + public static T GetAttribute(this MemberInfo member, bool isRequired = true) + where T : Attribute { var attribute = member.GetCustomAttributes(typeof(T), false).SingleOrDefault(); @@ -60,7 +60,8 @@ public static T GetAttribute(this MemberInfo member, bool isRequired = true) return (T)attribute; } - public static T[] GetAttributes(this MemberInfo member) where T : Attribute + public static T[] GetAttributes(this MemberInfo member) + where T : Attribute { return member.GetCustomAttributes(typeof(T), false).OfType().ToArray(); } diff --git a/src/NzbDrone.Common/Serializer/HttpUriConverter.cs b/src/NzbDrone.Common/Serializer/HttpUriConverter.cs index d11f76b9f..0cba98e8d 100644 --- a/src/NzbDrone.Common/Serializer/HttpUriConverter.cs +++ b/src/NzbDrone.Common/Serializer/HttpUriConverter.cs @@ -28,4 +28,4 @@ public override bool CanConvert(Type objectType) return objectType == typeof(HttpUri); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common/Serializer/IntConverter.cs b/src/NzbDrone.Common/Serializer/IntConverter.cs index 105dee3a6..e49676735 100644 --- a/src/NzbDrone.Common/Serializer/IntConverter.cs +++ b/src/NzbDrone.Common/Serializer/IntConverter.cs @@ -23,6 +23,7 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist { throw new JsonSerializationException("Can't convert type " + existingValue.GetType().FullName + " to number"); } + if (objectType == typeof(long)) { return Convert.ToInt64(reader.Value); @@ -36,4 +37,4 @@ public override bool CanConvert(Type objectType) return objectType == typeof(int) || objectType == typeof(long) || objectType == typeof(int); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common/Serializer/Json.cs b/src/NzbDrone.Common/Serializer/Json.cs index fe05b01a4..8a23c3f86 100644 --- a/src/NzbDrone.Common/Serializer/Json.cs +++ b/src/NzbDrone.Common/Serializer/Json.cs @@ -36,7 +36,8 @@ public static JsonSerializerSettings GetSerializerSettings() return serializerSettings; } - public static T Deserialize(string json) where T : new() + public static T Deserialize(string json) + where T : new() { try { @@ -95,7 +96,8 @@ private static JsonReaderException DetailedJsonReaderException(JsonReaderExcepti return ex; } - public static bool TryDeserialize(string json, out T result) where T : new() + public static bool TryDeserialize(string json, out T result) + where T : new() { try { diff --git a/src/NzbDrone.Common/Serializer/JsonVisitor.cs b/src/NzbDrone.Common/Serializer/JsonVisitor.cs index 87fdeeeec..d12cfc695 100644 --- a/src/NzbDrone.Common/Serializer/JsonVisitor.cs +++ b/src/NzbDrone.Common/Serializer/JsonVisitor.cs @@ -6,7 +6,6 @@ namespace NzbDrone.Common.Serializer { - public class JsonVisitor { protected void Dispatch(JToken json) @@ -70,6 +69,7 @@ public virtual void Visit(JArray json) Visit(token); } } + public virtual void Visit(JConstructor json) { } @@ -89,7 +89,6 @@ public virtual void Visit(JProperty property) public virtual void Visit(JValue value) { - } } } diff --git a/src/NzbDrone.Common/Serializer/UnderscoreStringEnumConverter.cs b/src/NzbDrone.Common/Serializer/UnderscoreStringEnumConverter.cs index 9022c029f..772f5640c 100644 --- a/src/NzbDrone.Common/Serializer/UnderscoreStringEnumConverter.cs +++ b/src/NzbDrone.Common/Serializer/UnderscoreStringEnumConverter.cs @@ -48,8 +48,10 @@ public override void WriteJson(JsonWriter writer, object value, JsonSerializer s { builder.Append('_'); } + builder.Append(char.ToLower(enumText[i])); } + enumText = builder.ToString(); writer.WriteValue(enumText); diff --git a/src/NzbDrone.Common/ServiceFactory.cs b/src/NzbDrone.Common/ServiceFactory.cs index 3e1d3aba9..4f7e4bb0b 100644 --- a/src/NzbDrone.Common/ServiceFactory.cs +++ b/src/NzbDrone.Common/ServiceFactory.cs @@ -1,14 +1,16 @@ using System; -using System.Linq; using System.Collections.Generic; +using System.Linq; using NzbDrone.Common.Composition; namespace NzbDrone.Common { public interface IServiceFactory { - T Build() where T : class; - IEnumerable BuildAll() where T : class; + T Build() + where T : class; + IEnumerable BuildAll() + where T : class; object Build(Type contract); IEnumerable GetImplementations(Type contract); } @@ -22,12 +24,14 @@ public ServiceFactory(IContainer container) _container = container; } - public T Build() where T : class + public T Build() + where T : class { return _container.Resolve(); } - public IEnumerable BuildAll() where T : class + public IEnumerable BuildAll() + where T : class { return _container.ResolveAll().GroupBy(c => c.GetType().FullName).Select(g => g.First()); } @@ -42,4 +46,4 @@ public IEnumerable GetImplementations(Type contract) return _container.GetImplementations(contract); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common/TPL/LimitedConcurrencyLevelTaskScheduler.cs b/src/NzbDrone.Common/TPL/LimitedConcurrencyLevelTaskScheduler.cs index 890ba16df..f4614831b 100644 --- a/src/NzbDrone.Common/TPL/LimitedConcurrencyLevelTaskScheduler.cs +++ b/src/NzbDrone.Common/TPL/LimitedConcurrencyLevelTaskScheduler.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Threading; @@ -11,30 +11,37 @@ public class LimitedConcurrencyLevelTaskScheduler : TaskScheduler /// Whether the current thread is processing work items. [ThreadStatic] private static bool _currentThreadIsProcessingItems; - /// The list of tasks to be executed. - private readonly LinkedList _tasks = new LinkedList(); // protected by lock(_tasks) - /// The maximum concurrency level allowed by this scheduler. - private readonly int _maxDegreeOfParallelism; - /// Whether the scheduler is currently processing work items. - private int _delegatesQueuedOrRunning = 0; // protected by lock(_tasks) - /// - /// Initializes an instance of the LimitedConcurrencyLevelTaskScheduler class with the - /// specified degree of parallelism. - /// + /// The list of tasks to be executed. + private readonly LinkedList _tasks = new LinkedList(); // protected by lock(_tasks) + + /// The maximum concurrency level allowed by this scheduler. + private readonly int _maxDegreeOfParallelism; + + /// Whether the scheduler is currently processing work items. + private int _delegatesQueuedOrRunning = 0; // protected by lock(_tasks) + + /// + /// Initializes an instance of the LimitedConcurrencyLevelTaskScheduler class with the + /// specified degree of parallelism. + /// /// The maximum degree of parallelism provided by this scheduler. public LimitedConcurrencyLevelTaskScheduler(int maxDegreeOfParallelism) { - if (maxDegreeOfParallelism < 1) throw new ArgumentOutOfRangeException(nameof(maxDegreeOfParallelism)); + if (maxDegreeOfParallelism < 1) + { + throw new ArgumentOutOfRangeException(nameof(maxDegreeOfParallelism)); + } + _maxDegreeOfParallelism = maxDegreeOfParallelism; } - /// Queues a task to the scheduler. + /// Queues a task to the scheduler. /// The task to be queued. protected sealed override void QueueTask(Task task) { - // Add the task to the list of tasks to be processed. If there aren't enough - // delegates currently queued or running to process tasks, schedule another. + // Add the task to the list of tasks to be processed. If there aren't enough + // delegates currently queued or running to process tasks, schedule another. lock (_tasks) { _tasks.AddLast(task); @@ -46,26 +53,26 @@ protected sealed override void QueueTask(Task task) } } - /// - /// Informs the ThreadPool that there's work to be executed for this scheduler. - /// + /// + /// Informs the ThreadPool that there's work to be executed for this scheduler. + /// private void NotifyThreadPoolOfPendingWork() { ThreadPool.UnsafeQueueUserWorkItem(_ => { - // Note that the current thread is now processing work items. + // Note that the current thread is now processing work items. // This is necessary to enable inlining of tasks into this thread. _currentThreadIsProcessingItems = true; try { - // Process all available items in the queue. + // Process all available items in the queue. while (true) { Task item; lock (_tasks) { - // When there are no more items to be processed, - // note that we're done processing, and get out. + // When there are no more items to be processed, + // note that we're done processing, and get out. if (_tasks.Count == 0) { --_delegatesQueuedOrRunning; @@ -77,57 +84,79 @@ private void NotifyThreadPoolOfPendingWork() _tasks.RemoveFirst(); } - // Execute the task we pulled out of the queue - base.TryExecuteTask(item); + // Execute the task we pulled out of the queue + TryExecuteTask(item); } } - // We're done processing items on the current thread - finally { _currentThreadIsProcessingItems = false; } + + // We're done processing items on the current thread + finally + { + _currentThreadIsProcessingItems = false; + } }, null); } - /// Attempts to execute the specified task on the current thread. + /// Attempts to execute the specified task on the current thread. /// The task to be executed. /// - /// Whether the task could be executed on the current thread. + /// Whether the task could be executed on the current thread. protected sealed override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued) { - // If this thread isn't already processing a task, we don't support inlining - if (!_currentThreadIsProcessingItems) return false; + // If this thread isn't already processing a task, we don't support inlining + if (!_currentThreadIsProcessingItems) + { + return false; + } - // If the task was previously queued, remove it from the queue - if (taskWasPreviouslyQueued) TryDequeue(task); + // If the task was previously queued, remove it from the queue + if (taskWasPreviouslyQueued) + { + TryDequeue(task); + } - // Try to run the task. - return base.TryExecuteTask(task); + // Try to run the task. + return TryExecuteTask(task); } - /// Attempts to remove a previously scheduled task from the scheduler. + /// Attempts to remove a previously scheduled task from the scheduler. /// The task to be removed. - /// Whether the task could be found and removed. + /// Whether the task could be found and removed. protected sealed override bool TryDequeue(Task task) { - lock (_tasks) return _tasks.Remove(task); + lock (_tasks) + { + return _tasks.Remove(task); + } } - /// Gets the maximum concurrency level supported by this scheduler. + /// Gets the maximum concurrency level supported by this scheduler. public sealed override int MaximumConcurrencyLevel => _maxDegreeOfParallelism; - /// Gets an enumerable of the tasks currently scheduled on this scheduler. - /// An enumerable of the tasks currently scheduled. + /// Gets an enumerable of the tasks currently scheduled on this scheduler. + /// An enumerable of the tasks currently scheduled. protected sealed override IEnumerable GetScheduledTasks() { bool lockTaken = false; try { Monitor.TryEnter(_tasks, ref lockTaken); - if (lockTaken) return _tasks.ToArray(); - else throw new NotSupportedException(); + if (lockTaken) + { + return _tasks.ToArray(); + } + else + { + throw new NotSupportedException(); + } } finally { - if (lockTaken) Monitor.Exit(_tasks); + if (lockTaken) + { + Monitor.Exit(_tasks); + } } } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common/TinyIoC.cs b/src/NzbDrone.Common/TinyIoC.cs index 7f5910a80..97ebe1600 100644 --- a/src/NzbDrone.Common/TinyIoC.cs +++ b/src/NzbDrone.Common/TinyIoC.cs @@ -13,6 +13,8 @@ // FITNESS FOR A PARTICULAR PURPOSE. //=============================================================================== +#pragma warning disable SX1101, SA1108, SA1119, SA1124, SA1200, SA1208, SA1314, SA1403, SA1503, SA1514, SA1515, SA1519, SX1309 + #region Preprocessor Directives // Uncomment this line if you want the container to automatically // register the TinyMessenger messenger/event aggregator @@ -81,10 +83,10 @@ namespace TinyIoC #endif #if NETFX_CORE - using System.Threading.Tasks; - using Windows.Storage.Search; + using System.Threading.Tasks; + using Windows.Storage.Search; using Windows.Storage; - using Windows.UI.Xaml.Shapes; + using Windows.UI.Xaml.Shapes; #endif #region SafeDictionary @@ -278,7 +280,7 @@ where item is IDisposable GC.SuppressFinalize(this); } - #endregion + #endregion } #endif #endregion @@ -296,11 +298,11 @@ public static Type[] SafeGetTypes(this Assembly assembly) } catch (System.IO.FileNotFoundException) { - assemblies = new Type[] { }; + assemblies = Array.Empty(); } catch (NotSupportedException) { - assemblies = new Type[] { }; + assemblies = Array.Empty(); } #if !NETFX_CORE catch (ReflectionTypeLoadException e) @@ -322,32 +324,32 @@ static TypeExtensions() } //#if NETFX_CORE - // /// - // /// Gets a generic method from a type given the method name, generic types and parameter types - // /// - // /// Source type - // /// Name of the method - // /// Generic types to use to make the method generic - // /// Method parameters - // /// MethodInfo or null if no matches found - // /// - // /// - // public static MethodInfo GetGenericMethod(this Type sourceType, string methodName, Type[] genericTypes, Type[] parameterTypes) - // { - // MethodInfo method; - // var cacheKey = new GenericMethodCacheKey(sourceType, methodName, genericTypes, parameterTypes); + // /// + // /// Gets a generic method from a type given the method name, generic types and parameter types + // /// + // /// Source type + // /// Name of the method + // /// Generic types to use to make the method generic + // /// Method parameters + // /// MethodInfo or null if no matches found + // /// + // /// + // public static MethodInfo GetGenericMethod(this Type sourceType, string methodName, Type[] genericTypes, Type[] parameterTypes) + // { + // MethodInfo method; + // var cacheKey = new GenericMethodCacheKey(sourceType, methodName, genericTypes, parameterTypes); - // // Shouldn't need any additional locking - // // we don't care if we do the method info generation - // // more than once before it gets cached. - // if (!_genericMethodCache.TryGetValue(cacheKey, out method)) - // { - // method = GetMethod(sourceType, methodName, genericTypes, parameterTypes); - // _genericMethodCache[cacheKey] = method; - // } + // // Shouldn't need any additional locking + // // we don't care if we do the method info generation + // // more than once before it gets cached. + // if (!_genericMethodCache.TryGetValue(cacheKey, out method)) + // { + // method = GetMethod(sourceType, methodName, genericTypes, parameterTypes); + // _genericMethodCache[cacheKey] = method; + // } - // return method; - // } + // return method; + // } //#else /// /// Gets a generic method from a type given the method name, binding flags, generic types and parameter types @@ -376,6 +378,7 @@ public static MethodInfo GetGenericMethod(this Type sourceType, BindingFlags bin return method; } + //#endif #if NETFX_CORE @@ -509,19 +512,18 @@ private int GenerateHashCode() } } } - } // @mbrit - 2012-05-22 - shim for ForEach call on List... #if NETFX_CORE - internal static class ListExtender - { - internal static void ForEach(this List list, Action callback) - { - foreach (T obj in list) - callback(obj); - } - } + internal static class ListExtender + { + internal static void ForEach(this List list, Action callback) + { + foreach (T obj in list) + callback(obj); + } + } #endif #endregion @@ -676,7 +678,7 @@ public enum UnregisteredResolutionActions { /// /// Attempt to resolve type, even if the type isn't registered. - /// + /// /// Registered types/options will always take precedence. /// AttemptResolve, @@ -689,7 +691,7 @@ public enum UnregisteredResolutionActions /// /// Attempt to resolve unregistered type if requested type is generic /// and no registration exists for the specific generic parameters used. - /// + /// /// Registered types/options will always take precedence. /// GenericsOnly @@ -771,33 +773,33 @@ static AppDomain() CurrentDomain = new AppDomain(); } - // @mbrit - 2012-05-30 - in WinRT, this should be done async... + // @mbrit - 2012-05-30 - in WinRT, this should be done async... public async Task> GetAssembliesAsync() { var folder = Windows.ApplicationModel.Package.Current.InstalledLocation; List assemblies = new List(); - var files = await folder.GetFilesAsync(); + var files = await folder.GetFilesAsync(); foreach (StorageFile file in files) { if (file.FileType == ".dll" || file.FileType == ".exe") { AssemblyName name = new AssemblyName() { Name = System.IO.Path.GetFileNameWithoutExtension(file.Name) }; - try - { - var asm = Assembly.Load(name); - assemblies.Add(asm); - } - catch - { - // ignore exceptions here... - } + try + { + var asm = Assembly.Load(name); + assemblies.Add(asm); + } + catch + { + // ignore exceptions here... + } } } - return assemblies; + return assemblies; } } #endif @@ -904,7 +906,7 @@ public RegisterOptions UsingConstructor(Expression /// Switches to a custom lifetime manager factory if possible. - /// + /// /// Usually used for RegisterOptions "To*" extension methods such as the ASP.Net per-request one. /// /// RegisterOptions instance @@ -994,7 +996,7 @@ public TinyIoCContainer GetChildContainer() #region Registration /// /// Attempt to automatically register all non-generic classes and interfaces in the current app domain. - /// + /// /// If more than one class implements an interface then only one implementation will be registered /// although no error will be thrown. /// @@ -1010,7 +1012,7 @@ public void AutoRegister() /// /// Attempt to automatically register all non-generic classes and interfaces in the current app domain. /// Types will only be registered if they pass the supplied registration predicate. - /// + /// /// If more than one class implements an interface then only one implementation will be registered /// although no error will be thrown. /// @@ -1056,7 +1058,7 @@ public void AutoRegister(DuplicateImplementationActions duplicateAction, Func /// Attempt to automatically register all non-generic classes and interfaces in the specified assemblies - /// + /// /// If more than one class implements an interface then only one implementation will be registered /// although no error will be thrown. /// @@ -1069,7 +1071,7 @@ public void AutoRegister(IEnumerable assemblies) /// /// Attempt to automatically register all non-generic classes and interfaces in the specified assemblies /// Types will only be registered if they pass the supplied registration predicate. - /// + /// /// If more than one class implements an interface then only one implementation will be registered /// although no error will be thrown. /// @@ -1123,7 +1125,6 @@ public RegisterOptions Register(Type registerType) public RegisterOptions Register(Type registerType, string name) { return RegisterInternal(registerType, name, GetDefaultObjectFactory(registerType, registerType)); - } /// @@ -1361,7 +1362,7 @@ public RegisterOptions Register(Func /// Register multiple implementations of a type. - /// + /// /// Internally this registers each implementation using the full name of the class as its registration name. /// /// Type that each implementation implements @@ -1374,7 +1375,7 @@ public MultiRegisterOptions RegisterMultiple(IEnumerable imp /// /// Register multiple implementations of a type. - /// + /// /// Internally this registers each implementation using the full name of the class as its registration name. /// /// Type that each implementation implements @@ -1387,9 +1388,10 @@ public MultiRegisterOptions RegisterMultiple(Type registrationType, IEnumerable< foreach (var type in implementationTypes) //#if NETFX_CORE - // if (!registrationType.GetTypeInfo().IsAssignableFrom(type.GetTypeInfo())) + // if (!registrationType.GetTypeInfo().IsAssignableFrom(type.GetTypeInfo())) //#else if (!registrationType.IsAssignableFrom(type)) + //#endif throw new ArgumentException(string.Format("types: The type {0} is not assignable from {1}", registrationType.FullName, type.FullName)); @@ -1398,8 +1400,8 @@ public MultiRegisterOptions RegisterMultiple(Type registrationType, IEnumerable< var queryForDuplicatedTypes = from i in implementationTypes group i by i into j - where j.Count() > 1 - select j.Key.FullName; + where j.Count() > 1 + select j.Key.FullName; var fullNamesOfDuplicatedTypes = string.Join(",\n", queryForDuplicatedTypes.ToArray()); var multipleRegMessage = string.Format("types: The same implementation type cannot be specified multiple times for {0}\n\n{1}", registrationType.FullName, fullNamesOfDuplicatedTypes); @@ -1720,7 +1722,7 @@ public bool CanResolve(Type resolveType, string name, ResolveOptions options) /// /// Parameters are used in conjunction with normal container resolution to find the most suitable constructor (if one exists). /// All user supplied parameters must exist in at least one resolvable constructor of RegisterType or resolution will fail. - /// + /// /// Note: Resolution may still fail if user defined factory registations fail to construct objects when called. /// /// Type to resolve @@ -1736,7 +1738,7 @@ public bool CanResolve(Type resolveType, NamedParameterOverloads parameters) /// /// Parameters are used in conjunction with normal container resolution to find the most suitable constructor (if one exists). /// All user supplied parameters must exist in at least one resolvable constructor of RegisterType or resolution will fail. - /// + /// /// Note: Resolution may still fail if user defined factory registations fail to construct objects when called. /// /// Type to resolve @@ -1753,7 +1755,7 @@ public bool CanResolve(Type resolveType, string name, NamedParameterOverloads pa /// /// Parameters are used in conjunction with normal container resolution to find the most suitable constructor (if one exists). /// All user supplied parameters must exist in at least one resolvable constructor of RegisterType or resolution will fail. - /// + /// /// Note: Resolution may still fail if user defined factory registations fail to construct objects when called. /// /// Type to resolve @@ -1770,7 +1772,7 @@ public bool CanResolve(Type resolveType, NamedParameterOverloads parameters, Res /// /// Parameters are used in conjunction with normal container resolution to find the most suitable constructor (if one exists). /// All user supplied parameters must exist in at least one resolvable constructor of RegisterType or resolution will fail. - /// + /// /// Note: Resolution may still fail if user defined factory registations fail to construct objects when called. /// /// Type to resolve @@ -1845,7 +1847,7 @@ public bool CanResolve(string name, ResolveOptions options) /// /// Parameters are used in conjunction with normal container resolution to find the most suitable constructor (if one exists). /// All user supplied parameters must exist in at least one resolvable constructor of RegisterType or resolution will fail. - /// + /// /// Note: Resolution may still fail if user defined factory registations fail to construct objects when called. /// /// Type to resolve @@ -1862,7 +1864,7 @@ public bool CanResolve(NamedParameterOverloads parameters) /// /// Parameters are used in conjunction with normal container resolution to find the most suitable constructor (if one exists). /// All user supplied parameters must exist in at least one resolvable constructor of RegisterType or resolution will fail. - /// + /// /// Note: Resolution may still fail if user defined factory registations fail to construct objects when called. /// /// Type to resolve @@ -1880,7 +1882,7 @@ public bool CanResolve(string name, NamedParameterOverloads paramet /// /// Parameters are used in conjunction with normal container resolution to find the most suitable constructor (if one exists). /// All user supplied parameters must exist in at least one resolvable constructor of RegisterType or resolution will fail. - /// + /// /// Note: Resolution may still fail if user defined factory registations fail to construct objects when called. /// /// Type to resolve @@ -1898,7 +1900,7 @@ public bool CanResolve(NamedParameterOverloads parameters, ResolveO /// /// Parameters are used in conjunction with normal container resolution to find the most suitable constructor (if one exists). /// All user supplied parameters must exist in at least one resolvable constructor of RegisterType or resolution will fail. - /// + /// /// Note: Resolution may still fail if user defined factory registations fail to construct objects when called. /// /// Type to resolve @@ -2360,7 +2362,7 @@ private abstract class ObjectFactoryBase { /// /// Whether to assume this factory sucessfully constructs its objects - /// + /// /// Generally set to true for delegate style factories as CanResolve cannot delve /// into the delegates they contain. /// @@ -2446,11 +2448,12 @@ private class MultiInstanceFactory : ObjectFactoryBase public MultiInstanceFactory(Type registerType, Type registerImplementation) { //#if NETFX_CORE - // if (registerImplementation.GetTypeInfo().IsAbstract() || registerImplementation.GetTypeInfo().IsInterface()) - // throw new TinyIoCRegistrationTypeException(registerImplementation, "MultiInstanceFactory"); + // if (registerImplementation.GetTypeInfo().IsAbstract() || registerImplementation.GetTypeInfo().IsInterface()) + // throw new TinyIoCRegistrationTypeException(registerImplementation, "MultiInstanceFactory"); //#else if (registerImplementation.IsAbstract() || registerImplementation.IsInterface()) throw new TinyIoCRegistrationTypeException(registerImplementation, "MultiInstanceFactory"); + //#endif if (!IsValidAssignment(registerType, registerImplementation)) throw new TinyIoCRegistrationTypeException(registerImplementation, "MultiInstanceFactory"); @@ -2636,7 +2639,7 @@ public void Dispose() /// /// Stores an particular instance to return for a type - /// + /// /// Stores the instance with a weak reference /// private class WeakInstanceFactory : ObjectFactoryBase, IDisposable @@ -2709,9 +2712,10 @@ private class SingletonFactory : ObjectFactoryBase, IDisposable public SingletonFactory(Type registerType, Type registerImplementation) { //#if NETFX_CORE - // if (registerImplementation.GetTypeInfo().IsAbstract() || registerImplementation.GetTypeInfo().IsInterface()) + // if (registerImplementation.GetTypeInfo().IsAbstract() || registerImplementation.GetTypeInfo().IsInterface()) //#else if (registerImplementation.IsAbstract() || registerImplementation.IsInterface()) + //#endif throw new TinyIoCRegistrationTypeException(registerImplementation, "SingletonFactory"); @@ -2783,9 +2787,10 @@ public CustomObjectLifetimeFactory(Type registerType, Type registerImplementatio throw new TinyIoCRegistrationTypeException(registerImplementation, "SingletonFactory"); //#if NETFX_CORE - // if (registerImplementation.GetTypeInfo().IsAbstract() || registerImplementation.GetTypeInfo().IsInterface()) + // if (registerImplementation.GetTypeInfo().IsAbstract() || registerImplementation.GetTypeInfo().IsInterface()) //#else if (registerImplementation.IsAbstract() || registerImplementation.IsInterface()) + //#endif throw new TinyIoCRegistrationTypeException(registerImplementation, errorMessage); @@ -2909,6 +2914,7 @@ public override int GetHashCode() return _hashCode; } } + private readonly SafeDictionary _RegisteredTypes; #if USE_OBJECT_CONSTRUCTOR private delegate object ObjectConstructor(params object[] parameters); @@ -2924,7 +2930,7 @@ public TinyIoCContainer() RegisterDefaultTypes(); } - TinyIoCContainer _Parent; + private TinyIoCContainer _Parent; private TinyIoCContainer(TinyIoCContainer parent) : this() { @@ -3087,9 +3093,10 @@ private void RemoveRegistration(TypeRegistration typeRegistration) private ObjectFactoryBase GetDefaultObjectFactory(Type registerType, Type registerImplementation) { //#if NETFX_CORE - // if (registerType.GetTypeInfo().IsInterface() || registerType.GetTypeInfo().IsAbstract()) + // if (registerType.GetTypeInfo().IsInterface() || registerType.GetTypeInfo().IsAbstract()) //#else if (registerType.IsInterface() || registerType.IsAbstract()) + //#endif return new SingletonFactory(registerType, registerImplementation); @@ -3179,17 +3186,19 @@ private bool IsAutomaticLazyFactoryRequest(Type type) // 2 parameter func with string as first parameter (name) //#if NETFX_CORE - // if ((genericType == typeof(Func<,>) && type.GetTypeInfo().GenericTypeArguments[0] == typeof(string))) + // if ((genericType == typeof(Func<,>) && type.GetTypeInfo().GenericTypeArguments[0] == typeof(string))) //#else if ((genericType == typeof(Func<,>) && type.GetGenericArguments()[0] == typeof(string))) + //#endif return true; // 3 parameter func with string as first parameter (name) and IDictionary as second (parameters) //#if NETFX_CORE - // if ((genericType == typeof(Func<,,>) && type.GetTypeInfo().GenericTypeArguments[0] == typeof(string) && type.GetTypeInfo().GenericTypeArguments[1] == typeof(IDictionary))) + // if ((genericType == typeof(Func<,,>) && type.GetTypeInfo().GenericTypeArguments[0] == typeof(string) && type.GetTypeInfo().GenericTypeArguments[1] == typeof(IDictionary))) //#else if ((genericType == typeof(Func<,,>) && type.GetGenericArguments()[0] == typeof(string) && type.GetGenericArguments()[1] == typeof(IDictionary))) + //#endif return true; @@ -3325,7 +3334,7 @@ private object GetLazyAutomaticFactoryRequest(Type type) Type genericType = type.GetGenericTypeDefinition(); //#if NETFX_CORE - // Type[] genericArguments = type.GetTypeInfo().GenericTypeArguments.ToArray(); + // Type[] genericArguments = type.GetTypeInfo().GenericTypeArguments.ToArray(); //#else Type[] genericArguments = type.GetGenericArguments(); //#endif @@ -3336,9 +3345,10 @@ private object GetLazyAutomaticFactoryRequest(Type type) Type returnType = genericArguments[0]; //#if NETFX_CORE - // MethodInfo resolveMethod = typeof(TinyIoCContainer).GetTypeInfo().GetDeclaredMethods("Resolve").First(mi => !mi.GetParameters().Any()); + // MethodInfo resolveMethod = typeof(TinyIoCContainer).GetTypeInfo().GetDeclaredMethods("Resolve").First(mi => !mi.GetParameters().Any()); //#else - MethodInfo resolveMethod = typeof(TinyIoCContainer).GetMethod("Resolve", new Type[] { }); + MethodInfo resolveMethod = typeof(TinyIoCContainer).GetMethod("Resolve", Array.Empty()); + //#endif resolveMethod = resolveMethod.MakeGenericMethod(returnType); @@ -3355,7 +3365,7 @@ private object GetLazyAutomaticFactoryRequest(Type type) Type returnType = genericArguments[1]; //#if NETFX_CORE - // MethodInfo resolveMethod = typeof(TinyIoCContainer).GetTypeInfo().GetDeclaredMethods("Resolve").First(mi => mi.GetParameters().Length == 1 && mi.GetParameters()[0].GetType() == typeof(String)); + // MethodInfo resolveMethod = typeof(TinyIoCContainer).GetTypeInfo().GetDeclaredMethods("Resolve").First(mi => mi.GetParameters().Length == 1 && mi.GetParameters()[0].GetType() == typeof(String)); //#else MethodInfo resolveMethod = typeof(TinyIoCContainer).GetMethod("Resolve", new Type[] { typeof(string) }); //#endif @@ -3371,7 +3381,7 @@ private object GetLazyAutomaticFactoryRequest(Type type) // 3 parameter func with string as first parameter (name) and IDictionary as second (parameters) //#if NETFX_CORE - // if ((genericType == typeof(Func<,,>) && type.GenericTypeArguments[0] == typeof(string) && type.GenericTypeArguments[1] == typeof(IDictionary))) + // if ((genericType == typeof(Func<,,>) && type.GenericTypeArguments[0] == typeof(string) && type.GenericTypeArguments[1] == typeof(IDictionary))) //#else if ((genericType == typeof(Func<,,>) && type.GetGenericArguments()[0] == typeof(string) && type.GetGenericArguments()[1] == typeof(IDictionary))) //#endif @@ -3382,7 +3392,7 @@ private object GetLazyAutomaticFactoryRequest(Type type) var parameters = Expression.Parameter(typeof(IDictionary), "parameters"); //#if NETFX_CORE - // MethodInfo resolveMethod = typeof(TinyIoCContainer).GetTypeInfo().GetDeclaredMethods("Resolve").First(mi => mi.GetParameters().Length == 2 && mi.GetParameters()[0].GetType() == typeof(String) && mi.GetParameters()[1].GetType() == typeof(NamedParameterOverloads)); + // MethodInfo resolveMethod = typeof(TinyIoCContainer).GetTypeInfo().GetDeclaredMethods("Resolve").First(mi => mi.GetParameters().Length == 2 && mi.GetParameters()[0].GetType() == typeof(String) && mi.GetParameters()[1].GetType() == typeof(NamedParameterOverloads)); //#else MethodInfo resolveMethod = typeof(TinyIoCContainer).GetMethod("Resolve", new Type[] { typeof(string), typeof(NamedParameterOverloads) }); //#endif @@ -3401,7 +3411,7 @@ private object GetLazyAutomaticFactoryRequest(Type type) private object GetIEnumerableRequest(Type type) { //#if NETFX_CORE - // var genericResolveAllMethod = this.GetType().GetGenericMethod("ResolveAll", type.GenericTypeArguments, new[] { typeof(bool) }); + // var genericResolveAllMethod = this.GetType().GetGenericMethod("ResolveAll", type.GenericTypeArguments, new[] { typeof(bool) }); //#else var genericResolveAllMethod = this.GetType().GetGenericMethod(BindingFlags.Public | BindingFlags.Instance, "ResolveAll", type.GetGenericArguments(), new[] { typeof(bool) }); //#endif @@ -3421,10 +3431,11 @@ private bool CanConstruct(ConstructorInfo ctor, NamedParameterOverloads paramete var isParameterOverload = parameters.ContainsKey(parameter.Name); - //#if NETFX_CORE - // if (parameter.ParameterType.GetTypeInfo().IsPrimitive && !isParameterOverload) + //#if NETFX_CORE + // if (parameter.ParameterType.GetTypeInfo().IsPrimitive && !isParameterOverload) //#else if (parameter.ParameterType.IsPrimitive() && !isParameterOverload) + //#endif return false; @@ -3441,9 +3452,10 @@ private ConstructorInfo GetBestConstructor(Type type, NamedParameterOverloads pa throw new ArgumentNullException("parameters"); //#if NETFX_CORE - // if (type.GetTypeInfo().IsValueType) + // if (type.GetTypeInfo().IsValueType) //#else if (type.IsValueType()) + //#endif return null; @@ -3463,9 +3475,10 @@ private ConstructorInfo GetBestConstructor(Type type, NamedParameterOverloads pa private IEnumerable GetTypeConstructors(Type type) { //#if NETFX_CORE - // return type.GetTypeInfo().DeclaredConstructors.OrderByDescending(ctor => ctor.GetParameters().Count()); + // return type.GetTypeInfo().DeclaredConstructors.OrderByDescending(ctor => ctor.GetParameters().Count()); //#else - return type.GetConstructors().OrderByDescending(ctor => ctor.GetParameters().Count()); + return type.GetConstructors().OrderByDescending(ctor => ctor.GetParameters().Length); + //#endif } @@ -3510,23 +3523,20 @@ private object ConstructType(Type requestedType, Type implementationType, Constr throw new TinyIoCResolutionException(typeToConstruct); var ctorParams = constructor.GetParameters(); - object[] args = new object[ctorParams.Count()]; + object[] args = new object[ctorParams.Length]; - for (int parameterIndex = 0; parameterIndex < ctorParams.Count(); parameterIndex++) + for (int parameterIndex = 0; parameterIndex < ctorParams.Length; parameterIndex++) { var currentParam = ctorParams[parameterIndex]; try { - if (ctorParams[parameterIndex].ParameterType == typeof(Logger)) { args[parameterIndex] = LogManager.GetLogger(implementationType.Name); } else { - - args[parameterIndex] = parameters.ContainsKey(currentParam.Name) ? parameters[currentParam.Name] : ResolveInternal( @@ -3572,7 +3582,7 @@ private static ObjectConstructor CreateObjectConstructionDelegateWithCache(Const // We could lock the cache here, but there's no real side // effect to two threads creating the same ObjectConstructor - // at the same time, compared to the cost of a lock for + // at the same time, compared to the cost of a lock for // every creation. var constructorParams = constructor.GetParameters(); var lambdaParams = Expression.Parameter(typeof(object[]), "parameters"); @@ -3599,9 +3609,9 @@ private static ObjectConstructor CreateObjectConstructionDelegateWithCache(Const private void BuildUpInternal(object input, ResolveOptions resolveOptions) { //#if NETFX_CORE - // var properties = from property in input.GetType().GetTypeInfo().DeclaredProperties - // where (property.GetMethod != null) && (property.SetMethod != null) && !property.PropertyType.GetTypeInfo().IsValueType - // select property; + // var properties = from property in input.GetType().GetTypeInfo().DeclaredProperties + // where (property.GetMethod != null) && (property.SetMethod != null) && !property.PropertyType.GetTypeInfo().IsValueType + // select property; //#else var properties = from property in input.GetType().GetProperties() where (property.GetGetMethod() != null) && (property.GetSetMethod() != null) && !property.PropertyType.IsValueType() @@ -3627,7 +3637,7 @@ private void BuildUpInternal(object input, ResolveOptions resolveOptions) private IEnumerable GetParentRegistrationsForType(Type resolveType) { if (_Parent == null) - return new TypeRegistration[] { }; + return Array.Empty(); var registrations = _Parent._RegisteredTypes.Keys.Where(tr => tr.Type == resolveType); @@ -3639,7 +3649,7 @@ private IEnumerable ResolveAllInternal(Type resolveType, bool includeUnn var registrations = _RegisteredTypes.Keys.Where(tr => tr.Type == resolveType).Concat(GetParentRegistrationsForType(resolveType)); if (!includeUnnamed) - registrations = registrations.Where(tr => tr.Name != string.Empty); + registrations = registrations.Where(tr => !string.IsNullOrEmpty(tr.Name)); return registrations.Select(registration => this.ResolveInternal(registration, NamedParameterOverloads.Default, ResolveOptions.Default)); } @@ -3647,26 +3657,26 @@ private IEnumerable ResolveAllInternal(Type resolveType, bool includeUnn private static bool IsValidAssignment(Type registerType, Type registerImplementation) { //#if NETFX_CORE - // var registerTypeDef = registerType.GetTypeInfo(); - // var registerImplementationDef = registerImplementation.GetTypeInfo(); + // var registerTypeDef = registerType.GetTypeInfo(); + // var registerImplementationDef = registerImplementation.GetTypeInfo(); - // if (!registerTypeDef.IsGenericTypeDefinition) - // { - // if (!registerTypeDef.IsAssignableFrom(registerImplementationDef)) - // return false; - // } - // else - // { - // if (registerTypeDef.IsInterface()) - // { - // if (!registerImplementationDef.ImplementedInterfaces.Any(t => t.GetTypeInfo().Name == registerTypeDef.Name)) - // return false; - // } - // else if (registerTypeDef.IsAbstract() && registerImplementationDef.BaseType() != registerType) - // { - // return false; - // } - // } + // if (!registerTypeDef.IsGenericTypeDefinition) + // { + // if (!registerTypeDef.IsAssignableFrom(registerImplementationDef)) + // return false; + // } + // else + // { + // if (registerTypeDef.IsInterface()) + // { + // if (!registerImplementationDef.ImplementedInterfaces.Any(t => t.GetTypeInfo().Name == registerTypeDef.Name)) + // return false; + // } + // else if (registerTypeDef.IsAbstract() && registerImplementationDef.BaseType() != registerType) + // { + // return false; + // } + // } //#else if (!registerType.IsGenericTypeDefinition()) { @@ -3685,6 +3695,7 @@ private static bool IsValidAssignment(Type registerType, Type registerImplementa return false; } } + //#endif return true; } @@ -3692,7 +3703,7 @@ private static bool IsValidAssignment(Type registerType, Type registerImplementa #endregion #region IDisposable Members - bool disposed = false; + private bool disposed = false; public void Dispose() { if (!disposed) @@ -3707,7 +3718,6 @@ public void Dispose() #endregion } - } // reverse shim for WinRT SR changes... @@ -3767,4 +3777,4 @@ public static Assembly Assembly(this Type type) } } } -#endif \ No newline at end of file +#endif diff --git a/src/NzbDrone.Console/ConsoleAlerts.cs b/src/NzbDrone.Console/ConsoleAlerts.cs index 4d623fc8e..04893b18a 100644 --- a/src/NzbDrone.Console/ConsoleAlerts.cs +++ b/src/NzbDrone.Console/ConsoleAlerts.cs @@ -12,4 +12,4 @@ public void Alert(string message) System.Console.ReadLine(); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Console/ConsoleApp.cs b/src/NzbDrone.Console/ConsoleApp.cs index 0aa758aea..5730710df 100644 --- a/src/NzbDrone.Console/ConsoleApp.cs +++ b/src/NzbDrone.Console/ConsoleApp.cs @@ -39,6 +39,7 @@ public static void Main(string[] args) System.Console.WriteLine("NLog Exception: " + ex.ToString()); throw; } + Bootstrap.Start(startupArgs, new ConsoleAlerts()); } catch (SonarrStartupException ex) @@ -70,7 +71,7 @@ public static void Main(string[] args) System.Console.WriteLine("EPIC FAIL! " + ex.ToString()); Exit(ExitCodes.UnknownFailure, startupArgs); } - + Logger.Info("Exiting main."); Exit(ExitCodes.Normal, startupArgs); @@ -88,8 +89,6 @@ private static void Exit(ExitCodes exitCode, StartupContext startupArgs) if (exitCode == ExitCodes.NonRecoverableFailure) { - - if (startupArgs?.ExitImmediately == true) { System.Console.WriteLine("Non-recoverable failure, but set to exit immediately"); @@ -102,7 +101,10 @@ private static void Exit(ExitCodes exitCode, StartupContext startupArgs) { System.Threading.Thread.Sleep(1000); - if (System.Console.KeyAvailable) break; + if (System.Console.KeyAvailable) + { + break; + } } } diff --git a/src/NzbDrone.Core.Test/Blocklisting/BlocklistServiceFixture.cs b/src/NzbDrone.Core.Test/Blocklisting/BlocklistServiceFixture.cs index ef92a62cd..202ca3d78 100644 --- a/src/NzbDrone.Core.Test/Blocklisting/BlocklistServiceFixture.cs +++ b/src/NzbDrone.Core.Test/Blocklisting/BlocklistServiceFixture.cs @@ -20,7 +20,7 @@ public void Setup() _event = new DownloadFailedEvent { SeriesId = 12345, - EpisodeIds = new List {1}, + EpisodeIds = new List { 1 }, Quality = new QualityModel(Quality.Bluray720p), SourceTitle = "series.title.s01e01", DownloadClient = "SabnzbdClient", diff --git a/src/NzbDrone.Core.Test/Configuration/ConfigCachingFixture.cs b/src/NzbDrone.Core.Test/Configuration/ConfigCachingFixture.cs index 087a854d7..c903cb839 100644 --- a/src/NzbDrone.Core.Test/Configuration/ConfigCachingFixture.cs +++ b/src/NzbDrone.Core.Test/Configuration/ConfigCachingFixture.cs @@ -5,7 +5,6 @@ using NzbDrone.Core.Configuration; using NzbDrone.Core.Test.Framework; - namespace NzbDrone.Core.Test.Configuration { [TestFixture] @@ -16,7 +15,6 @@ public void Setup() { Mocker.GetMock().Setup(c => c.All()) .Returns(new List { new Config { Key = "key1", Value = "Value1" } }); - } [Test] @@ -28,6 +26,5 @@ public void getting_value_more_than_once_should_hit_db_once() Mocker.GetMock().Verify(c => c.All(), Times.Once()); } - } } diff --git a/src/NzbDrone.Core.Test/Configuration/ConfigServiceFixture.cs b/src/NzbDrone.Core.Test/Configuration/ConfigServiceFixture.cs index 8ad51f1e7..346a2c956 100644 --- a/src/NzbDrone.Core.Test/Configuration/ConfigServiceFixture.cs +++ b/src/NzbDrone.Core.Test/Configuration/ConfigServiceFixture.cs @@ -28,7 +28,6 @@ public void Add_new_value_to_database() AssertUpsert(key, value); } - [Test] public void Get_value_should_return_default_when_no_value() { diff --git a/src/NzbDrone.Core.Test/DataAugmentation/DailySeries/DailySeriesDataProxyFixture.cs b/src/NzbDrone.Core.Test/DataAugmentation/DailySeries/DailySeriesDataProxyFixture.cs index b429e24b2..0ebdf1ebe 100644 --- a/src/NzbDrone.Core.Test/DataAugmentation/DailySeries/DailySeriesDataProxyFixture.cs +++ b/src/NzbDrone.Core.Test/DataAugmentation/DailySeries/DailySeriesDataProxyFixture.cs @@ -24,4 +24,4 @@ public void should_get_list_of_daily_series() list.Should().OnlyHaveUniqueItems(); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core.Test/DataAugmentation/Scene/SceneMappingProxyFixture.cs b/src/NzbDrone.Core.Test/DataAugmentation/Scene/SceneMappingProxyFixture.cs index 699b6d5ab..0711b2072 100644 --- a/src/NzbDrone.Core.Test/DataAugmentation/Scene/SceneMappingProxyFixture.cs +++ b/src/NzbDrone.Core.Test/DataAugmentation/Scene/SceneMappingProxyFixture.cs @@ -29,6 +29,5 @@ public void fetch_should_return_list_of_mappings() mappings.Should().NotContain(c => c.Title.IsNullOrWhiteSpace()); mappings.Should().Contain(c => c.SeasonNumber > 0); } - } } diff --git a/src/NzbDrone.Core.Test/DataAugmentation/Scene/SceneMappingServiceFixture.cs b/src/NzbDrone.Core.Test/DataAugmentation/Scene/SceneMappingServiceFixture.cs index 754e43068..e4671f91b 100644 --- a/src/NzbDrone.Core.Test/DataAugmentation/Scene/SceneMappingServiceFixture.cs +++ b/src/NzbDrone.Core.Test/DataAugmentation/Scene/SceneMappingServiceFixture.cs @@ -2,13 +2,13 @@ using System.Linq; using System.Net; using FizzWare.NBuilder; +using FluentAssertions; using Moq; using NUnit.Framework; +using NzbDrone.Common.Extensions; using NzbDrone.Core.DataAugmentation.Scene; using NzbDrone.Core.Test.Framework; using NzbDrone.Test.Common; -using FluentAssertions; -using NzbDrone.Common.Extensions; namespace NzbDrone.Core.Test.DataAugmentation.Scene { @@ -56,7 +56,7 @@ private void GivenProviders(IEnumerable> providers) [Test] public void should_purge_existing_mapping_and_add_new_ones() { - GivenProviders(new [] { _provider1 }); + GivenProviders(new[] { _provider1 }); Mocker.GetMock().Setup(c => c.All()).Returns(_fakeMappings); @@ -124,7 +124,6 @@ public void should_not_refresh_cache_if_cache_is_not_empty_when_looking_for_tvdb .Setup(s => s.All()) .Returns(Builder.CreateListOfSize(1).Build()); - Subject.Execute(new UpdateSceneMappingCommand()); Mocker.GetMock() @@ -174,11 +173,10 @@ public void should_not_add_mapping_with_blank_search_title() Subject.Execute(new UpdateSceneMappingCommand()); - Mocker.GetMock().Verify(c => c.InsertMany(It.Is>(m => !m.Any(s => s. SearchTerm.IsNullOrWhiteSpace()))), Times.Once()); + Mocker.GetMock().Verify(c => c.InsertMany(It.Is>(m => !m.Any(s => s.SearchTerm.IsNullOrWhiteSpace()))), Times.Once()); ExceptionVerification.ExpectedWarns(1); } - [TestCase("Working!!", "Working!!", 1)] [TestCase("Working`!!", "Working`!!", 2)] [TestCase("Working!!!", "Working!!!", 3)] @@ -323,7 +321,7 @@ public void should_filter_by_regex() var mappings = new List { new SceneMapping { Title = "Amareto", ParseTerm = "amareto", SearchTerm = "Amareto", TvdbId = 100 }, - new SceneMapping { Title = "Amareto", ParseTerm = "amareto", SearchTerm = "Amareto", TvdbId = 101, FilterRegex="-Viva$" } + new SceneMapping { Title = "Amareto", ParseTerm = "amareto", SearchTerm = "Amareto", TvdbId = 101, FilterRegex = "-Viva$" } }; Mocker.GetMock().Setup(c => c.All()).Returns(mappings); diff --git a/src/NzbDrone.Core.Test/Datastore/BasicRepositoryFixture.cs b/src/NzbDrone.Core.Test/Datastore/BasicRepositoryFixture.cs index e4775e037..68f7d9fb5 100644 --- a/src/NzbDrone.Core.Test/Datastore/BasicRepositoryFixture.cs +++ b/src/NzbDrone.Core.Test/Datastore/BasicRepositoryFixture.cs @@ -9,14 +9,12 @@ namespace NzbDrone.Core.Test.Datastore { - [TestFixture] public class BasicRepositoryFixture : DbTest, ScheduledTask> { private ScheduledTask _basicType; - [SetUp] public void Setup() { @@ -44,10 +42,8 @@ public void purge_should_delete_all() Subject.Purge(); AllStoredModels.Should().BeEmpty(); - } - [Test] public void should_be_able_to_delete_model() { @@ -64,7 +60,7 @@ public void should_be_able_to_find_by_id() Subject.Insert(_basicType); var storeObject = Subject.Get(_basicType.Id); - storeObject.Should().BeEquivalentTo(_basicType, o=>o.IncludingAllRuntimeProperties()); + storeObject.Should().BeEquivalentTo(_basicType, o => o.IncludingAllRuntimeProperties()); } [Test] @@ -86,19 +82,16 @@ public void getting_model_with_invalid_id_should_throw() Assert.Throws(() => Subject.Get(12)); } - [Test] public void get_all_with_empty_db_should_return_empty_list() { Subject.All().Should().BeEmpty(); } - [Test] public void should_be_able_to_call_ToList_on_empty_quariable() { Subject.All().ToList().Should().BeEmpty(); - } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core.Test/Datastore/Converters/BooleanIntConverterFixture.cs b/src/NzbDrone.Core.Test/Datastore/Converters/BooleanIntConverterFixture.cs index 649a7303e..23e50b812 100644 --- a/src/NzbDrone.Core.Test/Datastore/Converters/BooleanIntConverterFixture.cs +++ b/src/NzbDrone.Core.Test/Datastore/Converters/BooleanIntConverterFixture.cs @@ -50,7 +50,7 @@ public void should_throw_for_non_boolean_equivalent_number_value_when_getting_fr { var context = new ConverterContext { - DbValue = (long)2 + DbValue = 2L }; Assert.Throws(() => Subject.FromDB(context)); diff --git a/src/NzbDrone.Core.Test/Datastore/Converters/ProviderSettingConverterFixture.cs b/src/NzbDrone.Core.Test/Datastore/Converters/ProviderSettingConverterFixture.cs index 9aafbee73..3ea61eb84 100644 --- a/src/NzbDrone.Core.Test/Datastore/Converters/ProviderSettingConverterFixture.cs +++ b/src/NzbDrone.Core.Test/Datastore/Converters/ProviderSettingConverterFixture.cs @@ -19,7 +19,6 @@ public void should_return_null_config_if_config_is_null() DbValue = DBNull.Value }); - result.Should().Be(NullConfig.Instance); } @@ -32,8 +31,7 @@ public void should_return_null_config_if_config_is_empty(object dbValue) DbValue = dbValue }); - result.Should().Be(NullConfig.Instance); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core.Test/Datastore/Converters/UtcConverterFixture.cs b/src/NzbDrone.Core.Test/Datastore/Converters/UtcConverterFixture.cs index 904f653d3..5746a7d9d 100644 --- a/src/NzbDrone.Core.Test/Datastore/Converters/UtcConverterFixture.cs +++ b/src/NzbDrone.Core.Test/Datastore/Converters/UtcConverterFixture.cs @@ -32,7 +32,7 @@ public void should_return_time_span_when_getting_time_span_from_db() var context = new ConverterContext { DbValue = dateTime - }; + }; Subject.FromDB(context).Should().Be(dateTime); } diff --git a/src/NzbDrone.Core.Test/Datastore/DatabaseFixture.cs b/src/NzbDrone.Core.Test/Datastore/DatabaseFixture.cs index e1942d6c3..da8d7335a 100644 --- a/src/NzbDrone.Core.Test/Datastore/DatabaseFixture.cs +++ b/src/NzbDrone.Core.Test/Datastore/DatabaseFixture.cs @@ -20,7 +20,6 @@ public void SingleOrDefault_should_return_null_on_empty_db() .BeNull(); } - [Test] public void vaccume() { @@ -33,4 +32,4 @@ public void get_version() Mocker.Resolve().Version.Should().BeGreaterThan(new Version("3.0.0")); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core.Test/Datastore/DatabaseRelationshipFixture.cs b/src/NzbDrone.Core.Test/Datastore/DatabaseRelationshipFixture.cs index bed951e0d..bcf9c406e 100644 --- a/src/NzbDrone.Core.Test/Datastore/DatabaseRelationshipFixture.cs +++ b/src/NzbDrone.Core.Test/Datastore/DatabaseRelationshipFixture.cs @@ -3,11 +3,11 @@ using FluentAssertions; using NUnit.Framework; using NzbDrone.Core.History; +using NzbDrone.Core.Languages; using NzbDrone.Core.MediaFiles; using NzbDrone.Core.Qualities; using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Tv; -using NzbDrone.Core.Languages; namespace NzbDrone.Core.Test.Datastore { @@ -54,11 +54,10 @@ public void one_to_one_should_not_query_db_if_foreign_key_is_zero() Db.Single().EpisodeFile.Value.Should().BeNull(); } - [Test] public void embedded_document_as_json() { - var quality = new QualityModel { Quality = Quality.Bluray720p, Revision = new Revision(version: 2 )}; + var quality = new QualityModel { Quality = Quality.Bluray720p, Revision = new Revision(version: 2) }; var history = Builder.CreateNew() .With(c => c.Id = 0) @@ -81,7 +80,6 @@ public void embedded_list_of_document_with_json() history[0].Quality = new QualityModel(Quality.HDTV1080p, new Revision(version: 2)); history[1].Quality = new QualityModel(Quality.Bluray720p, new Revision(version: 2)); - Db.InsertMany(history); var returnedHistory = Db.All(); diff --git a/src/NzbDrone.Core.Test/Datastore/MappingExtentionFixture.cs b/src/NzbDrone.Core.Test/Datastore/MappingExtentionFixture.cs index 76558e6f1..bc0e8f2c4 100644 --- a/src/NzbDrone.Core.Test/Datastore/MappingExtentionFixture.cs +++ b/src/NzbDrone.Core.Test/Datastore/MappingExtentionFixture.cs @@ -12,10 +12,8 @@ namespace NzbDrone.Core.Test.Datastore [TestFixture] public class MappingExtensionFixture { - public class EmbeddedType : IEmbeddedDocument { - } public class TypeWithAllMappableProperties @@ -42,10 +40,8 @@ public void Setup() MapRepository.Instance.RegisterTypeConverter(typeof(List), new EmbeddedDocumentConverter()); MapRepository.Instance.RegisterTypeConverter(typeof(EmbeddedType), new EmbeddedDocumentConverter()); MapRepository.Instance.RegisterTypeConverter(typeof(int), new Int32Converter()); - } - [Test] public void test_mappable_types() { @@ -62,4 +58,4 @@ public void test_un_mappable_types() properties.Should().NotContain(c => MappingExtensions.IsMappableProperty(c)); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core.Test/Datastore/MarrDataLazyLoadingFixture.cs b/src/NzbDrone.Core.Test/Datastore/MarrDataLazyLoadingFixture.cs index 0459c9794..d643a0029 100644 --- a/src/NzbDrone.Core.Test/Datastore/MarrDataLazyLoadingFixture.cs +++ b/src/NzbDrone.Core.Test/Datastore/MarrDataLazyLoadingFixture.cs @@ -1,19 +1,18 @@ -using FizzWare.NBuilder; -using NUnit.Framework; using System.Linq; +using FizzWare.NBuilder; +using NUnit.Framework; using NzbDrone.Core.Datastore; -using NzbDrone.Core.Profiles.Qualities; -using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Tv; -using NzbDrone.Core.Qualities; -using NzbDrone.Core.MediaFiles; using NzbDrone.Core.Languages; +using NzbDrone.Core.MediaFiles; using NzbDrone.Core.Profiles.Languages; +using NzbDrone.Core.Profiles.Qualities; +using NzbDrone.Core.Qualities; +using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Test.Languages; +using NzbDrone.Core.Tv; namespace NzbDrone.Core.Test.Datastore { - [TestFixture] public class MarrDataLazyLoadingFixture : DbTest { @@ -67,9 +66,9 @@ public void Setup() public void should_lazy_load_profile_if_not_joined() { var db = Mocker.Resolve(); - var DataMapper = db.GetDataMapper(); + var dataMapper = db.GetDataMapper(); - var episodes = DataMapper.Query() + var episodes = dataMapper.Query() .Join(Marr.Data.QGen.JoinType.Inner, v => v.Series, (l, r) => l.SeriesId == r.Id) .ToList(); @@ -85,9 +84,9 @@ public void should_lazy_load_profile_if_not_joined() public void should_explicit_load_episodefile_if_joined() { var db = Mocker.Resolve(); - var DataMapper = db.GetDataMapper(); + var dataMapper = db.GetDataMapper(); - var episodes = DataMapper.Query() + var episodes = dataMapper.Query() .Join(Marr.Data.QGen.JoinType.Inner, v => v.EpisodeFile, (l, r) => l.EpisodeFileId == r.Id) .ToList(); @@ -102,9 +101,9 @@ public void should_explicit_load_episodefile_if_joined() public void should_explicit_load_profile_if_joined() { var db = Mocker.Resolve(); - var DataMapper = db.GetDataMapper(); + var dataMapper = db.GetDataMapper(); - var episodes = DataMapper.Query() + var episodes = dataMapper.Query() .Join(Marr.Data.QGen.JoinType.Inner, v => v.Series, (l, r) => l.SeriesId == r.Id) .Join(Marr.Data.QGen.JoinType.Inner, v => v.QualityProfile, (l, r) => l.QualityProfileId == r.Id) .ToList(); @@ -121,9 +120,9 @@ public void should_explicit_load_profile_if_joined() public void should_explicit_load_languageprofile_if_joined() { var db = Mocker.Resolve(); - var DataMapper = db.GetDataMapper(); + var dataMapper = db.GetDataMapper(); - var episodes = DataMapper.Query() + var episodes = dataMapper.Query() .Join(Marr.Data.QGen.JoinType.Inner, v => v.Series, (l, r) => l.SeriesId == r.Id) .Join(Marr.Data.QGen.JoinType.Inner, v => v.LanguageProfile, (l, r) => l.QualityProfileId == r.Id) .ToList(); @@ -136,4 +135,4 @@ public void should_explicit_load_languageprofile_if_joined() } } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core.Test/Datastore/Migration/072_history_downloadIdFixture.cs b/src/NzbDrone.Core.Test/Datastore/Migration/072_history_downloadIdFixture.cs index 4798b931a..363a6a180 100644 --- a/src/NzbDrone.Core.Test/Datastore/Migration/072_history_downloadIdFixture.cs +++ b/src/NzbDrone.Core.Test/Datastore/Migration/072_history_downloadIdFixture.cs @@ -20,16 +20,15 @@ public void should_move_grab_id_from_date_to_columns() { InsertHistory(c, new Dictionary { - {"indexer","test"}, - {"downloadClientId","123"} + { "indexer", "test" }, + { "downloadClientId", "123" } }); InsertHistory(c, new Dictionary { - {"indexer","test"}, - {"downloadClientId","abc"} + { "indexer", "test" }, + { "downloadClientId", "abc" } }); - }); var history = db.Query("SELECT DownloadId, Data FROM History"); @@ -40,7 +39,6 @@ public void should_move_grab_id_from_date_to_columns() history.Should().Contain(c => c.DownloadId == "abc"); } - [Test] public void should_leave_items_with_no_grabid() { @@ -48,15 +46,14 @@ public void should_leave_items_with_no_grabid() { InsertHistory(c, new Dictionary { - {"indexer","test"}, - {"downloadClientId","123"} + { "indexer", "test" }, + { "downloadClientId", "123" } }); InsertHistory(c, new Dictionary { - {"indexer","test"} + { "indexer", "test" } }); - }); var history = db.Query("SELECT DownloadId, Data FROM History"); @@ -74,9 +71,9 @@ public void should_leave_other_data() { InsertHistory(c, new Dictionary { - {"indexer","test"}, - {"group","test2"}, - {"downloadClientId","123"} + { "indexer", "test" }, + { "group", "test2" }, + { "downloadClientId", "123" } }); }); diff --git a/src/NzbDrone.Core.Test/Datastore/Migration/075_force_lib_updateFixture.cs b/src/NzbDrone.Core.Test/Datastore/Migration/075_force_lib_updateFixture.cs index c6b2b3cc7..a7ce2fe45 100644 --- a/src/NzbDrone.Core.Test/Datastore/Migration/075_force_lib_updateFixture.cs +++ b/src/NzbDrone.Core.Test/Datastore/Migration/075_force_lib_updateFixture.cs @@ -1,8 +1,8 @@ using System.Linq; using FluentAssertions; using NUnit.Framework; -using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Datastore.Migration; +using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.Datastore.Migration { @@ -18,7 +18,6 @@ public void should_not_fail_on_empty_db() db.Query("SELECT * FROM Series").Should().BeEmpty(); } - [Test] public void should_reset_job_last_execution_time() { @@ -105,4 +104,4 @@ public void should_reset_series_last_sync_time() series.Should().OnlyContain(c => c.LastInfoSync.Value.Year == 2014); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core.Test/Datastore/Migration/079_dedupe_tagsFixture.cs b/src/NzbDrone.Core.Test/Datastore/Migration/079_dedupe_tagsFixture.cs index cdee33a8d..1c24643aa 100644 --- a/src/NzbDrone.Core.Test/Datastore/Migration/079_dedupe_tagsFixture.cs +++ b/src/NzbDrone.Core.Test/Datastore/Migration/079_dedupe_tagsFixture.cs @@ -42,7 +42,7 @@ public void should_not_fail_if_series_tags_are_null() c.Insert.IntoTable("Tags").Row(new { - Label = "test" + Label = "test" }); }); diff --git a/src/NzbDrone.Core.Test/Datastore/Migration/081_move_dot_prefix_to_transmission_categoryFixture.cs b/src/NzbDrone.Core.Test/Datastore/Migration/081_move_dot_prefix_to_transmission_categoryFixture.cs index 7aae7010e..afd2aab45 100644 --- a/src/NzbDrone.Core.Test/Datastore/Migration/081_move_dot_prefix_to_transmission_categoryFixture.cs +++ b/src/NzbDrone.Core.Test/Datastore/Migration/081_move_dot_prefix_to_transmission_categoryFixture.cs @@ -2,8 +2,8 @@ using FluentAssertions; using NUnit.Framework; using NzbDrone.Common.Serializer; -using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Datastore.Migration; +using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.Datastore.Migration { diff --git a/src/NzbDrone.Core.Test/Datastore/Migration/085_expand_transmission_urlbaseFixture.cs b/src/NzbDrone.Core.Test/Datastore/Migration/085_expand_transmission_urlbaseFixture.cs index 0b1f7460d..655b717ee 100644 --- a/src/NzbDrone.Core.Test/Datastore/Migration/085_expand_transmission_urlbaseFixture.cs +++ b/src/NzbDrone.Core.Test/Datastore/Migration/085_expand_transmission_urlbaseFixture.cs @@ -15,7 +15,7 @@ public void should_not_fail_if_no_transmission() { var db = WithMigrationTestDb(c => { - c.Insert.IntoTable("DownloadClients").Row(new + c.Insert.IntoTable("DownloadClients").Row(new { Enable = 1, Name = "Deluge", diff --git a/src/NzbDrone.Core.Test/Datastore/Migration/086_pushbullet_device_idsFixture.cs b/src/NzbDrone.Core.Test/Datastore/Migration/086_pushbullet_device_idsFixture.cs index 20a8e063a..a478ef5d4 100644 --- a/src/NzbDrone.Core.Test/Datastore/Migration/086_pushbullet_device_idsFixture.cs +++ b/src/NzbDrone.Core.Test/Datastore/Migration/086_pushbullet_device_idsFixture.cs @@ -15,7 +15,7 @@ public void should_not_fail_if_no_pushbullet() { var db = WithMigrationTestDb(c => { - c.Insert.IntoTable("Notifications").Row(new + c.Insert.IntoTable("Notifications").Row(new { OnGrab = false, OnDownload = false, @@ -71,7 +71,7 @@ public void should_add_deviceIds_setting_matching_deviceId() OnUpgrade = false, Name = "PushBullet", Implementation = "PushBullet", - Settings = new + Settings = new { ApiKey = "my_api_key", DeviceId = deviceId diff --git a/src/NzbDrone.Core.Test/Datastore/Migration/090_update_kickass_urlFixture.cs b/src/NzbDrone.Core.Test/Datastore/Migration/090_update_kickass_urlFixture.cs index 292344127..9a73fb50c 100644 --- a/src/NzbDrone.Core.Test/Datastore/Migration/090_update_kickass_urlFixture.cs +++ b/src/NzbDrone.Core.Test/Datastore/Migration/090_update_kickass_urlFixture.cs @@ -15,12 +15,13 @@ public class update_kickass_url_migration_fixture : MigrationTest { - c.Insert.IntoTable("Indexers").Row(new + c.Insert.IntoTable("Indexers").Row(new { Name = "Kickass_wrong_url", Implementation = "KickassTorrents", diff --git a/src/NzbDrone.Core.Test/Datastore/Migration/108_fix_metadata_file_extensionsFixture.cs b/src/NzbDrone.Core.Test/Datastore/Migration/108_fix_metadata_file_extensionsFixture.cs index 8254c3a6c..c3413d707 100644 --- a/src/NzbDrone.Core.Test/Datastore/Migration/108_fix_metadata_file_extensionsFixture.cs +++ b/src/NzbDrone.Core.Test/Datastore/Migration/108_fix_metadata_file_extensionsFixture.cs @@ -80,5 +80,4 @@ public void should_fix_extension_missing_a_leading_period() items.First()["Extension"].Should().Be(".nfo-orig"); } } - } diff --git a/src/NzbDrone.Core.Test/Datastore/Migration/110_fix_extra_files_configFixture.cs b/src/NzbDrone.Core.Test/Datastore/Migration/110_fix_extra_files_configFixture.cs index 1a38efc1c..95182d31d 100644 --- a/src/NzbDrone.Core.Test/Datastore/Migration/110_fix_extra_files_configFixture.cs +++ b/src/NzbDrone.Core.Test/Datastore/Migration/110_fix_extra_files_configFixture.cs @@ -31,7 +31,6 @@ public void should_fix_importextrafiles_if_wrong() }); }); - var itemEnabled = db.QueryScalar("SELECT Value FROM Config WHERE Key = 'importextrafiles'"); itemEnabled.Should().Be("True"); } diff --git a/src/NzbDrone.Core.Test/Datastore/Migration/121_update_animetosho_urlFixture.cs b/src/NzbDrone.Core.Test/Datastore/Migration/121_update_animetosho_urlFixture.cs index ac2cf94e3..35418167a 100644 --- a/src/NzbDrone.Core.Test/Datastore/Migration/121_update_animetosho_urlFixture.cs +++ b/src/NzbDrone.Core.Test/Datastore/Migration/121_update_animetosho_urlFixture.cs @@ -26,7 +26,6 @@ public void should_replace_old_url(string impl, string baseUrl) { BaseUrl = baseUrl, ApiPath = "/feed/nabapi" - }.ToJson(), ConfigContract = impl + "Settings", EnableInteractiveSearch = false diff --git a/src/NzbDrone.Core.Test/Datastore/Migration/122_add_remux_qualities_in_profileFixture.cs b/src/NzbDrone.Core.Test/Datastore/Migration/122_add_remux_qualities_in_profileFixture.cs index afa35e630..dbee94cda 100644 --- a/src/NzbDrone.Core.Test/Datastore/Migration/122_add_remux_qualities_in_profileFixture.cs +++ b/src/NzbDrone.Core.Test/Datastore/Migration/122_add_remux_qualities_in_profileFixture.cs @@ -43,7 +43,7 @@ public void should_add_remux_to_old_profile_with_groups() Name = "Bluray", Cutoff = 7, Items = "[ { \"id\": 1001, \"name\": \"Why?!\", \"allowed\": true, \"items\": [{ \"quality\": 8, \"allowed\": true }, { \"quality\": 7, \"allowed\": true }] }, { \"quality\": 19, \"allowed\": true } ]" - }); + }); }); var profiles = db.Query("SELECT Items FROM Profiles LIMIT 1"); diff --git a/src/NzbDrone.Core.Test/Datastore/ObjectDatabaseFixture.cs b/src/NzbDrone.Core.Test/Datastore/ObjectDatabaseFixture.cs index 84037c050..41e30bff6 100644 --- a/src/NzbDrone.Core.Test/Datastore/ObjectDatabaseFixture.cs +++ b/src/NzbDrone.Core.Test/Datastore/ObjectDatabaseFixture.cs @@ -22,7 +22,6 @@ public void SetUp() .CreateNew() .With(s => s.Id = 0) .Build(); - } [Test] @@ -72,13 +71,12 @@ public void new_object_should_get_new_id() _sampleType.Id.Should().Be(1); } - [Test] public void should_read_and_write_in_utc() { var storedTime = DateTime.UtcNow; - _sampleType.LastExecution =storedTime; + _sampleType.LastExecution = storedTime; Subject.Insert(_sampleType); @@ -122,7 +120,6 @@ public void should_be_able_to_find_object_by_id() item.Id.Should().Be(_sampleType.Id); } - [Test] public void set_fields_should_only_update_selected_filed() { @@ -143,6 +140,4 @@ public void set_fields_should_only_update_selected_filed() Db.All().Single().Interval.Should().Be(12); } } - } - diff --git a/src/NzbDrone.Core.Test/Datastore/PagingSpecExtensionsTests/PagingOffsetFixture.cs b/src/NzbDrone.Core.Test/Datastore/PagingSpecExtensionsTests/PagingOffsetFixture.cs index 5ece0f8a4..195388579 100644 --- a/src/NzbDrone.Core.Test/Datastore/PagingSpecExtensionsTests/PagingOffsetFixture.cs +++ b/src/NzbDrone.Core.Test/Datastore/PagingSpecExtensionsTests/PagingOffsetFixture.cs @@ -24,6 +24,5 @@ public void should_calcuate_expected_offset(int page, int pageSize, int expected pagingSpec.PagingOffset().Should().Be(expected); } - } } diff --git a/src/NzbDrone.Core.Test/Datastore/ReflectionStrategyFixture/Benchmarks.cs b/src/NzbDrone.Core.Test/Datastore/ReflectionStrategyFixture/Benchmarks.cs index 48a1a3639..f65d9ed29 100644 --- a/src/NzbDrone.Core.Test/Datastore/ReflectionStrategyFixture/Benchmarks.cs +++ b/src/NzbDrone.Core.Test/Datastore/ReflectionStrategyFixture/Benchmarks.cs @@ -35,6 +35,5 @@ private void SetField() }*/ - } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core.Test/Datastore/SqliteSchemaDumperTests/SqliteSchemaDumperFixture.cs b/src/NzbDrone.Core.Test/Datastore/SqliteSchemaDumperTests/SqliteSchemaDumperFixture.cs index 9fb7be2b8..aef2b264f 100644 --- a/src/NzbDrone.Core.Test/Datastore/SqliteSchemaDumperTests/SqliteSchemaDumperFixture.cs +++ b/src/NzbDrone.Core.Test/Datastore/SqliteSchemaDumperTests/SqliteSchemaDumperFixture.cs @@ -66,7 +66,7 @@ public void should_parse_column_attributes(string sql) result.Columns.First().Name.Should().Be("MyId"); result.Columns.First().Type.Should().BeNull(); } - + [Test] public void should_ignore_unknown_symbols() { @@ -78,7 +78,6 @@ public void should_ignore_unknown_symbols() result.Columns.First().Type.Should().Be(DbType.Int64); result.Columns.Last().Name.Should().Be("MyCol"); result.Columns.Last().Type.Should().Be(DbType.Int64); - } } } diff --git a/src/NzbDrone.Core.Test/DecisionEngineTests/AcceptableSizeSpecificationFixture.cs b/src/NzbDrone.Core.Test/DecisionEngineTests/AcceptableSizeSpecificationFixture.cs index be4447f95..f8c986b9b 100644 --- a/src/NzbDrone.Core.Test/DecisionEngineTests/AcceptableSizeSpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/DecisionEngineTests/AcceptableSizeSpecificationFixture.cs @@ -1,4 +1,4 @@ -using System.Collections.Generic; +using System.Collections.Generic; using System.Linq; using FizzWare.NBuilder; using FluentAssertions; @@ -16,70 +16,70 @@ namespace NzbDrone.Core.Test.DecisionEngineTests public class AcceptableSizeSpecificationFixture : CoreTest { - private RemoteEpisode parseResultMultiSet; - private RemoteEpisode parseResultMulti; - private RemoteEpisode parseResultSingle; - private Series series; - private List episodes; - private QualityDefinition qualityType; + private RemoteEpisode _parseResultMultiSet; + private RemoteEpisode _parseResultMulti; + private RemoteEpisode _parseResultSingle; + private Series _series; + private List _episodes; + private QualityDefinition _qualityType; [SetUp] public void Setup() { - series = Builder.CreateNew() + _series = Builder.CreateNew() .With(s => s.Seasons = Builder.CreateListOfSize(2).Build().ToList()) .Build(); - episodes = Builder.CreateListOfSize(10) + _episodes = Builder.CreateListOfSize(10) .All() .With(s => s.SeasonNumber = 1) .BuildList(); - parseResultMultiSet = new RemoteEpisode + _parseResultMultiSet = new RemoteEpisode { - Series = series, + Series = _series, Release = new ReleaseInfo(), ParsedEpisodeInfo = new ParsedEpisodeInfo { Quality = new QualityModel(Quality.SDTV, new Revision(version: 2)) }, Episodes = Builder.CreateListOfSize(6).All().With(s => s.SeasonNumber = 1).BuildList() - }; + }; - parseResultMulti = new RemoteEpisode + _parseResultMulti = new RemoteEpisode { - Series = series, + Series = _series, Release = new ReleaseInfo(), ParsedEpisodeInfo = new ParsedEpisodeInfo { Quality = new QualityModel(Quality.SDTV, new Revision(version: 2)) }, Episodes = Builder.CreateListOfSize(2).All().With(s => s.SeasonNumber = 1).BuildList() - }; + }; - parseResultSingle = new RemoteEpisode + _parseResultSingle = new RemoteEpisode { - Series = series, + Series = _series, Release = new ReleaseInfo(), ParsedEpisodeInfo = new ParsedEpisodeInfo { Quality = new QualityModel(Quality.SDTV, new Revision(version: 2)) }, - Episodes = new List { + Episodes = new List + { Builder.CreateNew() .With(s => s.SeasonNumber = 1) .With(s => s.EpisodeNumber = 1) .Build() } - - }; + }; Mocker.GetMock() .Setup(v => v.Get(It.IsAny())) .Returns(v => Quality.DefaultQualityDefinitions.First(c => c.Quality == v)); - qualityType = Builder.CreateNew() + _qualityType = Builder.CreateNew() .With(q => q.MinSize = 2) .With(q => q.MaxSize = 10) .With(q => q.Quality = Quality.SDTV) .Build(); - Mocker.GetMock().Setup(s => s.Get(Quality.SDTV)).Returns(qualityType); + Mocker.GetMock().Setup(s => s.Get(Quality.SDTV)).Returns(_qualityType); Mocker.GetMock().Setup( s => s.GetEpisodesBySeason(It.IsAny(), It.IsAny())) - .Returns(episodes); + .Returns(_episodes); } [TestCase(30, 50, false)] @@ -89,13 +89,13 @@ public void Setup() [TestCase(60, 500, true)] [TestCase(60, 1000, false)] public void single_episode(int runtime, int sizeInMegaBytes, bool expectedResult) - { - series.Runtime = runtime; - parseResultSingle.Series = series; - parseResultSingle.Release.Size = sizeInMegaBytes.Megabytes(); - parseResultSingle.Episodes.First().Id = 5; + { + _series.Runtime = runtime; + _parseResultSingle.Series = _series; + _parseResultSingle.Release.Size = sizeInMegaBytes.Megabytes(); + _parseResultSingle.Episodes.First().Id = 5; - Subject.IsSatisfiedBy(parseResultSingle, null).Accepted.Should().Be(expectedResult); + Subject.IsSatisfiedBy(_parseResultSingle, null).Accepted.Should().Be(expectedResult); } [TestCase(30, 500, true)] @@ -104,12 +104,12 @@ public void single_episode(int runtime, int sizeInMegaBytes, bool expectedResult [TestCase(60, 2000, false)] public void should_return_expected_result_for_first_episode_of_season(int runtime, int sizeInMegaBytes, bool expectedResult) { - series.Runtime = runtime; - parseResultSingle.Series = series; - parseResultSingle.Release.Size = sizeInMegaBytes.Megabytes(); - parseResultSingle.Episodes.First().Id = episodes.First().Id; + _series.Runtime = runtime; + _parseResultSingle.Series = _series; + _parseResultSingle.Release.Size = sizeInMegaBytes.Megabytes(); + _parseResultSingle.Episodes.First().Id = _episodes.First().Id; - Subject.IsSatisfiedBy(parseResultSingle, null).Accepted.Should().Be(expectedResult); + Subject.IsSatisfiedBy(_parseResultSingle, null).Accepted.Should().Be(expectedResult); } [TestCase(30, 500, true)] @@ -118,12 +118,12 @@ public void should_return_expected_result_for_first_episode_of_season(int runtim [TestCase(60, 2000, false)] public void should_return_expected_result_for_last_episode_of_season(int runtime, int sizeInMegaBytes, bool expectedResult) { - series.Runtime = runtime; - parseResultSingle.Series = series; - parseResultSingle.Release.Size = sizeInMegaBytes.Megabytes(); - parseResultSingle.Episodes.First().Id = episodes.Last().Id; + _series.Runtime = runtime; + _parseResultSingle.Series = _series; + _parseResultSingle.Release.Size = sizeInMegaBytes.Megabytes(); + _parseResultSingle.Episodes.First().Id = _episodes.Last().Id; - Subject.IsSatisfiedBy(parseResultSingle, null).Accepted.Should().Be(expectedResult); + Subject.IsSatisfiedBy(_parseResultSingle, null).Accepted.Should().Be(expectedResult); } [TestCase(30, 50 * 2, false)] @@ -134,11 +134,11 @@ public void should_return_expected_result_for_last_episode_of_season(int runtime [TestCase(60, 1000 * 2, false)] public void multi_episode(int runtime, int sizeInMegaBytes, bool expectedResult) { - series.Runtime = runtime; - parseResultMulti.Series = series; - parseResultMulti.Release.Size = sizeInMegaBytes.Megabytes(); + _series.Runtime = runtime; + _parseResultMulti.Series = _series; + _parseResultMulti.Release.Size = sizeInMegaBytes.Megabytes(); - Subject.IsSatisfiedBy(parseResultMulti, null).Accepted.Should().Be(expectedResult); + Subject.IsSatisfiedBy(_parseResultMulti, null).Accepted.Should().Be(expectedResult); } [TestCase(30, 50 * 6, false)] @@ -149,168 +149,168 @@ public void multi_episode(int runtime, int sizeInMegaBytes, bool expectedResult) [TestCase(60, 1000 * 6, false)] public void multiset_episode(int runtime, int sizeInMegaBytes, bool expectedResult) { - series.Runtime = runtime; - parseResultMultiSet.Series = series; - parseResultMultiSet.Release.Size = sizeInMegaBytes.Megabytes(); + _series.Runtime = runtime; + _parseResultMultiSet.Series = _series; + _parseResultMultiSet.Release.Size = sizeInMegaBytes.Megabytes(); - Subject.IsSatisfiedBy(parseResultMultiSet, null).Accepted.Should().Be(expectedResult); + Subject.IsSatisfiedBy(_parseResultMultiSet, null).Accepted.Should().Be(expectedResult); } [Test] public void should_return_true_if_size_is_zero() { - series.Runtime = 30; - parseResultSingle.Series = series; - parseResultSingle.Release.Size = 0; - qualityType.MinSize = 10; - qualityType.MaxSize = 20; + _series.Runtime = 30; + _parseResultSingle.Series = _series; + _parseResultSingle.Release.Size = 0; + _qualityType.MinSize = 10; + _qualityType.MaxSize = 20; - Subject.IsSatisfiedBy(parseResultSingle, null).Accepted.Should().BeTrue(); + Subject.IsSatisfiedBy(_parseResultSingle, null).Accepted.Should().BeTrue(); } [Test] public void should_return_true_if_unlimited_30_minute() { - series.Runtime = 30; - parseResultSingle.Series = series; - parseResultSingle.Release.Size = 18457280000; - qualityType.MaxSize = null; + _series.Runtime = 30; + _parseResultSingle.Series = _series; + _parseResultSingle.Release.Size = 18457280000; + _qualityType.MaxSize = null; - Subject.IsSatisfiedBy(parseResultSingle, null).Accepted.Should().BeTrue(); + Subject.IsSatisfiedBy(_parseResultSingle, null).Accepted.Should().BeTrue(); } - + [Test] public void should_return_true_if_unlimited_60_minute() { - series.Runtime = 60; - parseResultSingle.Series = series; - parseResultSingle.Release.Size = 36857280000; - qualityType.MaxSize = null; + _series.Runtime = 60; + _parseResultSingle.Series = _series; + _parseResultSingle.Release.Size = 36857280000; + _qualityType.MaxSize = null; - Subject.IsSatisfiedBy(parseResultSingle, null).Accepted.Should().BeTrue(); + Subject.IsSatisfiedBy(_parseResultSingle, null).Accepted.Should().BeTrue(); } [Test] public void should_treat_daily_series_as_single_episode() { - series.Runtime = 60; - parseResultSingle.Series = series; - parseResultSingle.Series.SeriesType = SeriesTypes.Daily; - parseResultSingle.Release.Size = 300.Megabytes(); + _series.Runtime = 60; + _parseResultSingle.Series = _series; + _parseResultSingle.Series.SeriesType = SeriesTypes.Daily; + _parseResultSingle.Release.Size = 300.Megabytes(); - qualityType.MaxSize = 10; + _qualityType.MaxSize = 10; - Subject.IsSatisfiedBy(parseResultSingle, null).Accepted.Should().BeTrue(); + Subject.IsSatisfiedBy(_parseResultSingle, null).Accepted.Should().BeTrue(); } [Test] public void should_return_true_if_RAWHD() { - parseResultSingle.ParsedEpisodeInfo.Quality = new QualityModel(Quality.RAWHD); - - series.Runtime = 45; - parseResultSingle.Series = series; - parseResultSingle.Series.SeriesType = SeriesTypes.Daily; - parseResultSingle.Release.Size = 8000.Megabytes(); + _parseResultSingle.ParsedEpisodeInfo.Quality = new QualityModel(Quality.RAWHD); - Subject.IsSatisfiedBy(parseResultSingle, null).Accepted.Should().BeTrue(); + _series.Runtime = 45; + _parseResultSingle.Series = _series; + _parseResultSingle.Series.SeriesType = SeriesTypes.Daily; + _parseResultSingle.Release.Size = 8000.Megabytes(); + + Subject.IsSatisfiedBy(_parseResultSingle, null).Accepted.Should().BeTrue(); } [Test] public void should_return_true_for_special() { - parseResultSingle.ParsedEpisodeInfo.Special = true; + _parseResultSingle.ParsedEpisodeInfo.Special = true; - Subject.IsSatisfiedBy(parseResultSingle, null).Accepted.Should().BeTrue(); + Subject.IsSatisfiedBy(_parseResultSingle, null).Accepted.Should().BeTrue(); } [Test] public void should_return_false_if_series_runtime_is_zero_and_single_episode_is_not_from_first_season() { - series.Runtime = 0; - parseResultSingle.Series = series; - parseResultSingle.Episodes.First().Id = 5; - parseResultSingle.Release.Size = 200.Megabytes(); - parseResultSingle.Episodes.First().SeasonNumber = 2; + _series.Runtime = 0; + _parseResultSingle.Series = _series; + _parseResultSingle.Episodes.First().Id = 5; + _parseResultSingle.Release.Size = 200.Megabytes(); + _parseResultSingle.Episodes.First().SeasonNumber = 2; - Subject.IsSatisfiedBy(parseResultSingle, null).Accepted.Should().Be(false); + Subject.IsSatisfiedBy(_parseResultSingle, null).Accepted.Should().Be(false); } [Test] public void should_return_false_if_series_runtime_is_zero_and_single_episode_aired_more_than_24_hours_after_first_aired_episode() { - series.Runtime = 0; + _series.Runtime = 0; - parseResultSingle.Series = series; - parseResultSingle.Release.Size = 200.Megabytes(); - parseResultSingle.Episodes.First().Id = 5; - parseResultSingle.Episodes.First().SeasonNumber = 1; - parseResultSingle.Episodes.First().EpisodeNumber = 2; - parseResultSingle.Episodes.First().AirDateUtc = episodes.First().AirDateUtc.Value.AddDays(7); + _parseResultSingle.Series = _series; + _parseResultSingle.Release.Size = 200.Megabytes(); + _parseResultSingle.Episodes.First().Id = 5; + _parseResultSingle.Episodes.First().SeasonNumber = 1; + _parseResultSingle.Episodes.First().EpisodeNumber = 2; + _parseResultSingle.Episodes.First().AirDateUtc = _episodes.First().AirDateUtc.Value.AddDays(7); - Subject.IsSatisfiedBy(parseResultSingle, null).Accepted.Should().Be(false); + Subject.IsSatisfiedBy(_parseResultSingle, null).Accepted.Should().Be(false); } [Test] public void should_return_true_if_series_runtime_is_zero_and_single_episode_aired_less_than_24_hours_after_first_aired_episode() { - series.Runtime = 0; + _series.Runtime = 0; - parseResultSingle.Series = series; - parseResultSingle.Release.Size = 200.Megabytes(); - parseResultSingle.Episodes.First().Id = 5; - parseResultSingle.Episodes.First().SeasonNumber = 1; - parseResultSingle.Episodes.First().EpisodeNumber = 2; - parseResultSingle.Episodes.First().AirDateUtc = episodes.First().AirDateUtc.Value.AddHours(1); + _parseResultSingle.Series = _series; + _parseResultSingle.Release.Size = 200.Megabytes(); + _parseResultSingle.Episodes.First().Id = 5; + _parseResultSingle.Episodes.First().SeasonNumber = 1; + _parseResultSingle.Episodes.First().EpisodeNumber = 2; + _parseResultSingle.Episodes.First().AirDateUtc = _episodes.First().AirDateUtc.Value.AddHours(1); - Subject.IsSatisfiedBy(parseResultSingle, null).Accepted.Should().Be(true); + Subject.IsSatisfiedBy(_parseResultSingle, null).Accepted.Should().Be(true); } [Test] public void should_return_false_if_series_runtime_is_zero_and_multi_episode_is_not_from_first_season() { - series.Runtime = 0; - parseResultMulti.Series = series; - parseResultMulti.Release.Size = 200.Megabytes(); - parseResultMulti.Episodes.ForEach(e => e.SeasonNumber = 2); + _series.Runtime = 0; + _parseResultMulti.Series = _series; + _parseResultMulti.Release.Size = 200.Megabytes(); + _parseResultMulti.Episodes.ForEach(e => e.SeasonNumber = 2); - Subject.IsSatisfiedBy(parseResultMulti, null).Accepted.Should().Be(false); + Subject.IsSatisfiedBy(_parseResultMulti, null).Accepted.Should().Be(false); } [Test] public void should_return_false_if_series_runtime_is_zero_and_multi_episode_aired_more_than_24_hours_after_first_aired_episode() { - var airDateUtc = episodes.First().AirDateUtc.Value.AddDays(7); + var airDateUtc = _episodes.First().AirDateUtc.Value.AddDays(7); - series.Runtime = 0; + _series.Runtime = 0; - parseResultMulti.Series = series; - parseResultMulti.Release.Size = 200.Megabytes(); - parseResultMulti.Episodes.ForEach(e => + _parseResultMulti.Series = _series; + _parseResultMulti.Release.Size = 200.Megabytes(); + _parseResultMulti.Episodes.ForEach(e => { e.SeasonNumber = 1; e.AirDateUtc = airDateUtc; }); - Subject.IsSatisfiedBy(parseResultMulti, null).Accepted.Should().Be(false); + Subject.IsSatisfiedBy(_parseResultMulti, null).Accepted.Should().Be(false); } [Test] public void should_return_true_if_series_runtime_is_zero_and_multi_episode_aired_less_than_24_hours_after_first_aired_episode() { - var airDateUtc = episodes.First().AirDateUtc.Value.AddHours(1); - - series.Runtime = 0; + var airDateUtc = _episodes.First().AirDateUtc.Value.AddHours(1); - parseResultMulti.Series = series; - parseResultMulti.Release.Size = 200.Megabytes(); - parseResultMulti.Episodes.ForEach(e => + _series.Runtime = 0; + + _parseResultMulti.Series = _series; + _parseResultMulti.Release.Size = 200.Megabytes(); + _parseResultMulti.Episodes.ForEach(e => { e.SeasonNumber = 1; e.AirDateUtc = airDateUtc; }); - Subject.IsSatisfiedBy(parseResultMulti, null).Accepted.Should().Be(true); + Subject.IsSatisfiedBy(_parseResultMulti, null).Accepted.Should().Be(true); } } } diff --git a/src/NzbDrone.Core.Test/DecisionEngineTests/AlreadyImportedSpecificationFixture.cs b/src/NzbDrone.Core.Test/DecisionEngineTests/AlreadyImportedSpecificationFixture.cs index 4ea248175..7d6464ff6 100644 --- a/src/NzbDrone.Core.Test/DecisionEngineTests/AlreadyImportedSpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/DecisionEngineTests/AlreadyImportedSpecificationFixture.cs @@ -6,13 +6,13 @@ using Moq; using NUnit.Framework; using NzbDrone.Core.Configuration; +using NzbDrone.Core.DecisionEngine.Specifications; using NzbDrone.Core.History; +using NzbDrone.Core.Indexers; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Qualities; -using NzbDrone.Core.Tv; -using NzbDrone.Core.DecisionEngine.Specifications; -using NzbDrone.Core.Indexers; using NzbDrone.Core.Test.Framework; +using NzbDrone.Core.Tv; namespace NzbDrone.Core.Test.DecisionEngineTests { diff --git a/src/NzbDrone.Core.Test/DecisionEngineTests/AnimeVersionUpgradeSpecificationFixture.cs b/src/NzbDrone.Core.Test/DecisionEngineTests/AnimeVersionUpgradeSpecificationFixture.cs index 0b69b5252..a37d694b1 100644 --- a/src/NzbDrone.Core.Test/DecisionEngineTests/AnimeVersionUpgradeSpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/DecisionEngineTests/AnimeVersionUpgradeSpecificationFixture.cs @@ -7,8 +7,8 @@ using NzbDrone.Core.MediaFiles; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Qualities; -using NzbDrone.Core.Tv; using NzbDrone.Core.Test.Framework; +using NzbDrone.Core.Tv; namespace NzbDrone.Core.Test.DecisionEngineTests { @@ -106,4 +106,4 @@ public void should_be_false_when_release_group_does_not_match() _subject.IsSatisfiedBy(_remoteEpisode, null).Accepted.Should().BeFalse(); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core.Test/DecisionEngineTests/CutoffSpecificationFixture.cs b/src/NzbDrone.Core.Test/DecisionEngineTests/CutoffSpecificationFixture.cs index c2ad7adab..41f7b4ebd 100644 --- a/src/NzbDrone.Core.Test/DecisionEngineTests/CutoffSpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/DecisionEngineTests/CutoffSpecificationFixture.cs @@ -1,11 +1,11 @@ using FluentAssertions; using NUnit.Framework; -using NzbDrone.Core.Profiles.Qualities; -using NzbDrone.Core.Qualities; using NzbDrone.Core.DecisionEngine.Specifications; -using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Languages; using NzbDrone.Core.Profiles.Languages; +using NzbDrone.Core.Profiles.Qualities; +using NzbDrone.Core.Qualities; +using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Test.Languages; namespace NzbDrone.Core.Test.DecisionEngineTests @@ -19,9 +19,9 @@ public class CutoffSpecificationFixture : CoreTest public void should_return_true_if_current_episode_is_less_than_cutoff() { Subject.CutoffNotMet( - new QualityProfile - { - Cutoff = Quality.Bluray1080p.Id, + new QualityProfile + { + Cutoff = Quality.Bluray1080p.Id, Items = Qualities.QualityFixture.GetDefaultQualities(), UpgradeAllowed = true }, @@ -42,7 +42,7 @@ public void should_return_false_if_current_episode_is_equal_to_cutoff() Subject.CutoffNotMet( new QualityProfile { - Cutoff = Quality.HDTV720p.Id, + Cutoff = Quality.HDTV720p.Id, Items = Qualities.QualityFixture.GetDefaultQualities(), UpgradeAllowed = true }, @@ -61,9 +61,9 @@ public void should_return_false_if_current_episode_is_equal_to_cutoff() public void should_return_false_if_current_episode_is_greater_than_cutoff() { Subject.CutoffNotMet( - new QualityProfile - { - Cutoff = Quality.HDTV720p.Id, + new QualityProfile + { + Cutoff = Quality.HDTV720p.Id, Items = Qualities.QualityFixture.GetDefaultQualities(), UpgradeAllowed = true }, @@ -82,9 +82,9 @@ public void should_return_false_if_current_episode_is_greater_than_cutoff() public void should_return_true_when_new_episode_is_proper_but_existing_is_not() { Subject.CutoffNotMet( - new QualityProfile - { - Cutoff = Quality.HDTV720p.Id, + new QualityProfile + { + Cutoff = Quality.HDTV720p.Id, Items = Qualities.QualityFixture.GetDefaultQualities(), UpgradeAllowed = true }, @@ -105,9 +105,9 @@ public void should_return_true_when_new_episode_is_proper_but_existing_is_not() public void should_return_false_if_cutoff_is_met_and_quality_is_higher() { Subject.CutoffNotMet( - new QualityProfile + new QualityProfile { - Cutoff = Quality.HDTV720p.Id, + Cutoff = Quality.HDTV720p.Id, Items = Qualities.QualityFixture.GetDefaultQualities(), UpgradeAllowed = true }, @@ -127,40 +127,40 @@ public void should_return_false_if_cutoff_is_met_and_quality_is_higher() [Test] public void should_return_true_if_quality_cutoff_is_met_and_quality_is_higher_but_language_is_not_met() { - QualityProfile _profile = new QualityProfile - { - Cutoff = Quality.HDTV720p.Id, - Items = Qualities.QualityFixture.GetDefaultQualities(), - UpgradeAllowed = true - }; - - LanguageProfile _langProfile = new LanguageProfile - { - Cutoff = Language.Spanish, - Languages = LanguageFixture.GetDefaultLanguages(), - UpgradeAllowed = true - }; - - Subject.CutoffNotMet(_profile, - _langProfile, - new QualityModel(Quality.HDTV720p, new Revision(version: 2)), - Language.English, - NoPreferredWordScore, - new QualityModel(Quality.Bluray1080p, new Revision(version: 2)), - NoPreferredWordScore).Should().BeTrue(); - } - - [Test] - public void should_return_false_if_cutoff_is_met_and_quality_is_higher_and_language_is_met() - { - QualityProfile _profile = new QualityProfile + QualityProfile profile = new QualityProfile { Cutoff = Quality.HDTV720p.Id, Items = Qualities.QualityFixture.GetDefaultQualities(), UpgradeAllowed = true }; - LanguageProfile _langProfile = new LanguageProfile + LanguageProfile langProfile = new LanguageProfile + { + Cutoff = Language.Spanish, + Languages = LanguageFixture.GetDefaultLanguages(), + UpgradeAllowed = true + }; + + Subject.CutoffNotMet(profile, + langProfile, + new QualityModel(Quality.HDTV720p, new Revision(version: 2)), + Language.English, + NoPreferredWordScore, + new QualityModel(Quality.Bluray1080p, new Revision(version: 2)), + NoPreferredWordScore).Should().BeTrue(); + } + + [Test] + public void should_return_false_if_cutoff_is_met_and_quality_is_higher_and_language_is_met() + { + QualityProfile profile = new QualityProfile + { + Cutoff = Quality.HDTV720p.Id, + Items = Qualities.QualityFixture.GetDefaultQualities(), + UpgradeAllowed = true + }; + + LanguageProfile langProfile = new LanguageProfile { Cutoff = Language.Spanish, Languages = LanguageFixture.GetDefaultLanguages(), @@ -168,8 +168,8 @@ public void should_return_false_if_cutoff_is_met_and_quality_is_higher_and_langu }; Subject.CutoffNotMet( - _profile, - _langProfile, + profile, + langProfile, new QualityModel(Quality.HDTV720p, new Revision(version: 2)), Language.Spanish, NoPreferredWordScore, @@ -180,14 +180,14 @@ public void should_return_false_if_cutoff_is_met_and_quality_is_higher_and_langu [Test] public void should_return_false_if_cutoff_is_met_and_quality_is_higher_and_language_is_higher() { - QualityProfile _profile = new QualityProfile + QualityProfile profile = new QualityProfile { Cutoff = Quality.HDTV720p.Id, Items = Qualities.QualityFixture.GetDefaultQualities(), UpgradeAllowed = true }; - LanguageProfile _langProfile = new LanguageProfile + LanguageProfile langProfile = new LanguageProfile { Cutoff = Language.Spanish, Languages = LanguageFixture.GetDefaultLanguages(), @@ -195,8 +195,8 @@ public void should_return_false_if_cutoff_is_met_and_quality_is_higher_and_langu }; Subject.CutoffNotMet( - _profile, - _langProfile, + profile, + langProfile, new QualityModel(Quality.HDTV720p, new Revision(version: 2)), Language.French, NoPreferredWordScore, @@ -207,14 +207,14 @@ public void should_return_false_if_cutoff_is_met_and_quality_is_higher_and_langu [Test] public void should_return_true_if_cutoff_is_not_met_and_new_quality_is_higher_and_language_is_higher() { - QualityProfile _profile = new QualityProfile + QualityProfile profile = new QualityProfile { Cutoff = Quality.HDTV720p.Id, Items = Qualities.QualityFixture.GetDefaultQualities(), UpgradeAllowed = true }; - LanguageProfile _langProfile = new LanguageProfile + LanguageProfile langProfile = new LanguageProfile { Cutoff = Language.Spanish, Languages = LanguageFixture.GetDefaultLanguages(), @@ -222,8 +222,8 @@ public void should_return_true_if_cutoff_is_not_met_and_new_quality_is_higher_an }; Subject.CutoffNotMet( - _profile, - _langProfile, + profile, + langProfile, new QualityModel(Quality.SDTV, new Revision(version: 2)), Language.French, NoPreferredWordScore, @@ -234,14 +234,14 @@ public void should_return_true_if_cutoff_is_not_met_and_new_quality_is_higher_an [Test] public void should_return_true_if_cutoff_is_not_met_and_language_is_higher() { - QualityProfile _profile = new QualityProfile + QualityProfile profile = new QualityProfile { Cutoff = Quality.HDTV720p.Id, Items = Qualities.QualityFixture.GetDefaultQualities(), UpgradeAllowed = true }; - LanguageProfile _langProfile = new LanguageProfile + LanguageProfile langProfile = new LanguageProfile { Cutoff = Language.Spanish, Languages = LanguageFixture.GetDefaultLanguages(), @@ -249,8 +249,8 @@ public void should_return_true_if_cutoff_is_not_met_and_language_is_higher() }; Subject.CutoffNotMet( - _profile, - _langProfile, + profile, + langProfile, new QualityModel(Quality.SDTV, new Revision(version: 2)), Language.French, NoPreferredWordScore).Should().BeTrue(); @@ -259,23 +259,23 @@ public void should_return_true_if_cutoff_is_not_met_and_language_is_higher() [Test] public void should_return_true_if_cutoffs_are_met_and_score_is_higher() { - QualityProfile _profile = new QualityProfile - { - Cutoff = Quality.HDTV720p.Id, - Items = Qualities.QualityFixture.GetDefaultQualities(), - UpgradeAllowed = true + QualityProfile profile = new QualityProfile + { + Cutoff = Quality.HDTV720p.Id, + Items = Qualities.QualityFixture.GetDefaultQualities(), + UpgradeAllowed = true }; - LanguageProfile _langProfile = new LanguageProfile - { - Cutoff = Language.Spanish, - Languages = LanguageFixture.GetDefaultLanguages(), - UpgradeAllowed = true + LanguageProfile langProfile = new LanguageProfile + { + Cutoff = Language.Spanish, + Languages = LanguageFixture.GetDefaultLanguages(), + UpgradeAllowed = true }; Subject.CutoffNotMet( - _profile, - _langProfile, + profile, + langProfile, new QualityModel(Quality.HDTV720p, new Revision(version: 2)), Language.Spanish, NoPreferredWordScore, @@ -286,23 +286,23 @@ public void should_return_true_if_cutoffs_are_met_and_score_is_higher() [Test] public void should_return_true_if_cutoffs_are_met_but_is_a_revision_upgrade() { - QualityProfile _profile = new QualityProfile - { - Cutoff = Quality.HDTV1080p.Id, - Items = Qualities.QualityFixture.GetDefaultQualities(), - UpgradeAllowed = true + QualityProfile profile = new QualityProfile + { + Cutoff = Quality.HDTV1080p.Id, + Items = Qualities.QualityFixture.GetDefaultQualities(), + UpgradeAllowed = true }; - LanguageProfile _langProfile = new LanguageProfile - { - Cutoff = Language.English, - Languages = LanguageFixture.GetDefaultLanguages(), - UpgradeAllowed = true + LanguageProfile langProfile = new LanguageProfile + { + Cutoff = Language.English, + Languages = LanguageFixture.GetDefaultLanguages(), + UpgradeAllowed = true }; Subject.CutoffNotMet( - _profile, - _langProfile, + profile, + langProfile, new QualityModel(Quality.WEBDL1080p, new Revision(version: 1)), Language.English, NoPreferredWordScore, @@ -313,23 +313,23 @@ public void should_return_true_if_cutoffs_are_met_but_is_a_revision_upgrade() [Test] public void should_return_false_if_language_profile_does_not_allow_upgrades_but_cutoff_is_set_to_highest_language_and_quality_cutoff_is_met() { - QualityProfile _profile = new QualityProfile - { - Cutoff = Quality.WEBDL1080p.Id, - Items = Qualities.QualityFixture.GetDefaultQualities(), - UpgradeAllowed = true - }; + QualityProfile profile = new QualityProfile + { + Cutoff = Quality.WEBDL1080p.Id, + Items = Qualities.QualityFixture.GetDefaultQualities(), + UpgradeAllowed = true + }; - LanguageProfile _langProfile = new LanguageProfile - { - Cutoff = Language.Arabic, - Languages = LanguageFixture.GetDefaultLanguages(Language.Spanish, Language.English, Language.Arabic), - UpgradeAllowed = false - }; + LanguageProfile langProfile = new LanguageProfile + { + Cutoff = Language.Arabic, + Languages = LanguageFixture.GetDefaultLanguages(Language.Spanish, Language.English, Language.Arabic), + UpgradeAllowed = false + }; Subject.CutoffNotMet( - _profile, - _langProfile, + profile, + langProfile, new QualityModel(Quality.WEBDL1080p), Language.English, NoPreferredWordScore, @@ -340,23 +340,23 @@ public void should_return_false_if_language_profile_does_not_allow_upgrades_but_ [Test] public void should_return_false_if_quality_profile_does_not_allow_upgrades_but_cutoff_is_set_to_highest_quality_and_language_cutoff_is_met() { - QualityProfile _profile = new QualityProfile - { - Cutoff = Quality.WEBDL1080p.Id, - Items = Qualities.QualityFixture.GetDefaultQualities(), - UpgradeAllowed = false - }; + QualityProfile profile = new QualityProfile + { + Cutoff = Quality.WEBDL1080p.Id, + Items = Qualities.QualityFixture.GetDefaultQualities(), + UpgradeAllowed = false + }; - LanguageProfile _langProfile = new LanguageProfile - { - Cutoff = Language.English, - Languages = LanguageFixture.GetDefaultLanguages(Language.Spanish, Language.English, Language.Arabic), - UpgradeAllowed = true + LanguageProfile langProfile = new LanguageProfile + { + Cutoff = Language.English, + Languages = LanguageFixture.GetDefaultLanguages(Language.Spanish, Language.English, Language.Arabic), + UpgradeAllowed = true }; Subject.CutoffNotMet( - _profile, - _langProfile, + profile, + langProfile, new QualityModel(Quality.WEBDL1080p), Language.English, NoPreferredWordScore, diff --git a/src/NzbDrone.Core.Test/DecisionEngineTests/DownloadDecisionMakerFixture.cs b/src/NzbDrone.Core.Test/DecisionEngineTests/DownloadDecisionMakerFixture.cs index cab95e3a0..dcef16654 100644 --- a/src/NzbDrone.Core.Test/DecisionEngineTests/DownloadDecisionMakerFixture.cs +++ b/src/NzbDrone.Core.Test/DecisionEngineTests/DownloadDecisionMakerFixture.cs @@ -1,18 +1,18 @@ using System.Collections.Generic; using System.Linq; +using FizzWare.NBuilder; using FluentAssertions; using Moq; using NUnit.Framework; +using NzbDrone.Core.DataAugmentation.Scene; using NzbDrone.Core.DecisionEngine; +using NzbDrone.Core.DecisionEngine.Specifications; using NzbDrone.Core.IndexerSearch.Definitions; using NzbDrone.Core.Parser; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Tv; using NzbDrone.Test.Common; -using FizzWare.NBuilder; -using NzbDrone.Core.DataAugmentation.Scene; -using NzbDrone.Core.DecisionEngine.Specifications; namespace NzbDrone.Core.Test.DecisionEngineTests { @@ -57,7 +57,8 @@ public void Setup() _failDelayed1.SetupGet(c => c.Priority).Returns(SpecificationPriority.Disk); _reports = new List { new ReleaseInfo { Title = "The.Office.S03E115.DVDRip.XviD-OSiTV" } }; - _remoteEpisode = new RemoteEpisode { + _remoteEpisode = new RemoteEpisode + { Series = new Series(), Episodes = new List { new Episode() } }; @@ -216,9 +217,9 @@ public void broken_report_shouldnt_blowup_the_process() _reports = new List { - new ReleaseInfo{Title = "The.Office.S03E115.DVDRip.XviD-OSiTV"}, - new ReleaseInfo{Title = "The.Office.S03E115.DVDRip.XviD-OSiTV"}, - new ReleaseInfo{Title = "The.Office.S03E115.DVDRip.XviD-OSiTV"} + new ReleaseInfo { Title = "The.Office.S03E115.DVDRip.XviD-OSiTV" }, + new ReleaseInfo { Title = "The.Office.S03E115.DVDRip.XviD-OSiTV" }, + new ReleaseInfo { Title = "The.Office.S03E115.DVDRip.XviD-OSiTV" } }; Subject.GetRssDecision(_reports); @@ -263,7 +264,7 @@ public void should_only_include_reports_for_requested_episodes() Mocker.GetMock() .Setup(v => v.Map(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) - .Returns((p,tvdbid,tvrageid,c) => + .Returns((p, tvdbid, tvrageid, c) => new RemoteEpisode { DownloadAllowed = true, @@ -322,7 +323,7 @@ public void should_return_a_decision_when_exception_is_caught() _reports = new List { - new ReleaseInfo{Title = "The.Office.S03E115.DVDRip.XviD-OSiTV"}, + new ReleaseInfo { Title = "The.Office.S03E115.DVDRip.XviD-OSiTV" }, }; Subject.GetRssDecision(_reports).Should().HaveCount(1); diff --git a/src/NzbDrone.Core.Test/DecisionEngineTests/FullSeasonSpecificationFixture.cs b/src/NzbDrone.Core.Test/DecisionEngineTests/FullSeasonSpecificationFixture.cs index a751d2a6a..0c1c77b08 100644 --- a/src/NzbDrone.Core.Test/DecisionEngineTests/FullSeasonSpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/DecisionEngineTests/FullSeasonSpecificationFixture.cs @@ -1,15 +1,14 @@ - -using System; +using System; +using System.Collections.Generic; +using System.Linq; +using FizzWare.NBuilder; +using FluentAssertions; +using Moq; using NUnit.Framework; using NzbDrone.Core.DecisionEngine.Specifications; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Test.Framework; -using FizzWare.NBuilder; -using System.Linq; -using FluentAssertions; using NzbDrone.Core.Tv; -using Moq; -using System.Collections.Generic; namespace NzbDrone.Core.Test.DecisionEngineTests { diff --git a/src/NzbDrone.Core.Test/DecisionEngineTests/LanguageSpecificationFixture.cs b/src/NzbDrone.Core.Test/DecisionEngineTests/LanguageSpecificationFixture.cs index 45f5c9c04..c94c547f1 100644 --- a/src/NzbDrone.Core.Test/DecisionEngineTests/LanguageSpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/DecisionEngineTests/LanguageSpecificationFixture.cs @@ -4,10 +4,10 @@ using NzbDrone.Core.DecisionEngine.Specifications; using NzbDrone.Core.Languages; using NzbDrone.Core.Parser.Model; -using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Tv; using NzbDrone.Core.Profiles.Languages; +using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Test.Languages; +using NzbDrone.Core.Tv; namespace NzbDrone.Core.Test.DecisionEngineTests { @@ -20,7 +20,7 @@ public class LanguageSpecificationFixture : CoreTest [SetUp] public void Setup() { - LanguageProfile _profile = new LazyLoaded (new LanguageProfile + LanguageProfile profile = new LazyLoaded(new LanguageProfile { Languages = LanguageFixture.GetDefaultLanguages(Language.English, Language.Spanish), Cutoff = Language.Spanish @@ -34,7 +34,7 @@ public void Setup() }, Series = new Series { - LanguageProfile = _profile + LanguageProfile = profile } }; } @@ -56,7 +56,7 @@ private void WithFrenchRelease() private void WithGermanRelease() { - _remoteEpisode.ParsedEpisodeInfo.Language = Language.German; + _remoteEpisode.ParsedEpisodeInfo.Language = Language.German; } [Test] @@ -83,7 +83,6 @@ public void should_return_false_if_language_is_french() Mocker.Resolve().IsSatisfiedBy(_remoteEpisode, null).Accepted.Should().BeFalse(); } - [Test] public void should_return_true_if_language_is_spanish() { @@ -91,6 +90,5 @@ public void should_return_true_if_language_is_spanish() Mocker.Resolve().IsSatisfiedBy(_remoteEpisode, null).Accepted.Should().BeTrue(); } - } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core.Test/DecisionEngineTests/MinimumAgeSpecificationFixture.cs b/src/NzbDrone.Core.Test/DecisionEngineTests/MinimumAgeSpecificationFixture.cs index 745eb68d5..8ce7bc806 100644 --- a/src/NzbDrone.Core.Test/DecisionEngineTests/MinimumAgeSpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/DecisionEngineTests/MinimumAgeSpecificationFixture.cs @@ -61,4 +61,4 @@ public void should_return_false_when_age_is_less_than_minimum_age() Subject.IsSatisfiedBy(_remoteEpisode, null).Accepted.Should().BeFalse(); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core.Test/DecisionEngineTests/MonitoredEpisodeSpecificationFixture.cs b/src/NzbDrone.Core.Test/DecisionEngineTests/MonitoredEpisodeSpecificationFixture.cs index d81e67f27..3e19af87c 100644 --- a/src/NzbDrone.Core.Test/DecisionEngineTests/MonitoredEpisodeSpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/DecisionEngineTests/MonitoredEpisodeSpecificationFixture.cs @@ -34,7 +34,6 @@ public void Setup() _firstEpisode = new Episode { Monitored = true }; _secondEpisode = new Episode { Monitored = true }; - var singleEpisodeList = new List { _firstEpisode }; var doubleEpisodeList = new List { _firstEpisode, _secondEpisode }; @@ -121,7 +120,7 @@ public void should_return_true_if_episode_is_monitored_for_season_search() public void should_return_false_if_episode_is_not_monitored_for_season_search() { WithFirstEpisodeUnmonitored(); - _monitoredEpisodeSpecification.IsSatisfiedBy(_parseResultSingle, new SeasonSearchCriteria { MonitoredEpisodesOnly = true}).Accepted.Should().BeFalse(); + _monitoredEpisodeSpecification.IsSatisfiedBy(_parseResultSingle, new SeasonSearchCriteria { MonitoredEpisodesOnly = true }).Accepted.Should().BeFalse(); } [Test] @@ -135,7 +134,7 @@ public void should_return_true_if_episode_is_not_monitored_and_monitoredEpisodes public void should_return_false_if_episode_is_not_monitored_and_monitoredEpisodesOnly_flag_is_true() { WithFirstEpisodeUnmonitored(); - _monitoredEpisodeSpecification.IsSatisfiedBy(_parseResultSingle, new SingleEpisodeSearchCriteria{ MonitoredEpisodesOnly = true}).Accepted.Should().BeFalse(); + _monitoredEpisodeSpecification.IsSatisfiedBy(_parseResultSingle, new SingleEpisodeSearchCriteria { MonitoredEpisodesOnly = true }).Accepted.Should().BeFalse(); } [Test] @@ -150,4 +149,4 @@ public void should_return_false_if_all_episodes_are_not_monitored_for_season_pac _monitoredEpisodeSpecification.IsSatisfiedBy(_parseResultMulti, null).Accepted.Should().BeFalse(); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core.Test/DecisionEngineTests/MultiSeasonSpecificationFixture.cs b/src/NzbDrone.Core.Test/DecisionEngineTests/MultiSeasonSpecificationFixture.cs index dc499a3d6..8a853e387 100644 --- a/src/NzbDrone.Core.Test/DecisionEngineTests/MultiSeasonSpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/DecisionEngineTests/MultiSeasonSpecificationFixture.cs @@ -1,15 +1,14 @@ - -using System; +using System; +using System.Collections.Generic; +using System.Linq; +using FizzWare.NBuilder; +using FluentAssertions; +using Moq; using NUnit.Framework; using NzbDrone.Core.DecisionEngine.Specifications; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Test.Framework; -using FizzWare.NBuilder; -using System.Linq; -using FluentAssertions; using NzbDrone.Core.Tv; -using Moq; -using System.Collections.Generic; namespace NzbDrone.Core.Test.DecisionEngineTests { diff --git a/src/NzbDrone.Core.Test/DecisionEngineTests/PrioritizeDownloadDecisionFixture.cs b/src/NzbDrone.Core.Test/DecisionEngineTests/PrioritizeDownloadDecisionFixture.cs index 0b27f6160..890a0ceac 100644 --- a/src/NzbDrone.Core.Test/DecisionEngineTests/PrioritizeDownloadDecisionFixture.cs +++ b/src/NzbDrone.Core.Test/DecisionEngineTests/PrioritizeDownloadDecisionFixture.cs @@ -1,23 +1,23 @@ using System; using System.Collections.Generic; using System.Linq; -using Moq; -using NzbDrone.Core.Indexers; -using NzbDrone.Core.Profiles.Delay; -using NzbDrone.Core.Tv; -using NzbDrone.Core.Profiles.Qualities; -using NzbDrone.Core.Qualities; -using NzbDrone.Core.Parser.Model; -using NzbDrone.Core.DecisionEngine; -using NUnit.Framework; -using FluentAssertions; using FizzWare.NBuilder; +using FluentAssertions; +using Moq; +using NUnit.Framework; using NzbDrone.Common.Extensions; using NzbDrone.Core.Configuration; -using NzbDrone.Core.Test.Framework; +using NzbDrone.Core.DecisionEngine; +using NzbDrone.Core.Indexers; using NzbDrone.Core.Languages; +using NzbDrone.Core.Parser.Model; +using NzbDrone.Core.Profiles.Delay; using NzbDrone.Core.Profiles.Languages; +using NzbDrone.Core.Profiles.Qualities; +using NzbDrone.Core.Qualities; +using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Test.Languages; +using NzbDrone.Core.Tv; namespace NzbDrone.Core.Test.DecisionEngineTests { @@ -173,7 +173,6 @@ public void should_order_by_youngest() var remoteEpisode1 = GivenRemoteEpisode(new List { GivenEpisode(1) }, new QualityModel(Quality.HDTV720p), Language.English, age: 10); var remoteEpisode2 = GivenRemoteEpisode(new List { GivenEpisode(1) }, new QualityModel(Quality.HDTV720p), Language.English, age: 5); - var decisions = new List(); decisions.Add(new DownloadDecision(remoteEpisode1)); decisions.Add(new DownloadDecision(remoteEpisode2)); @@ -299,7 +298,7 @@ public void should_prefer_releases_with_more_seeders() decisions.Add(new DownloadDecision(remoteEpisode2)); var qualifiedReports = Subject.PrioritizeDecisions(decisions); - ((TorrentInfo) qualifiedReports.First().RemoteEpisode.Release).Seeders.Should().Be(torrentInfo2.Seeders); + ((TorrentInfo)qualifiedReports.First().RemoteEpisode.Release).Seeders.Should().Be(torrentInfo2.Seeders); } [Test] @@ -315,7 +314,6 @@ public void should_prefer_releases_with_more_peers_given_equal_number_of_seeds() torrentInfo1.Seeders = 10; torrentInfo1.Peers = 10; - var torrentInfo2 = torrentInfo1.JsonClone(); torrentInfo2.Peers = 100; @@ -343,7 +341,6 @@ public void should_prefer_releases_with_more_peers_no_seeds() torrentInfo1.Seeders = 0; torrentInfo1.Peers = 10; - var torrentInfo2 = torrentInfo1.JsonClone(); torrentInfo2.Seeders = 0; torrentInfo2.Peers = 100; @@ -385,7 +382,7 @@ public void should_prefer_first_release_if_peers_and_size_are_too_similar() decisions.Add(new DownloadDecision(remoteEpisode2)); var qualifiedReports = Subject.PrioritizeDecisions(decisions); - ((TorrentInfo) qualifiedReports.First().RemoteEpisode.Release).Should().Be(torrentInfo1); + ((TorrentInfo)qualifiedReports.First().RemoteEpisode.Release).Should().Be(torrentInfo1); } [Test] @@ -444,7 +441,6 @@ public void should_order_by_language() var remoteEpisode2 = GivenRemoteEpisode(new List { GivenEpisode(1) }, new QualityModel(Quality.HDTV720p), Language.French); var remoteEpisode3 = GivenRemoteEpisode(new List { GivenEpisode(1) }, new QualityModel(Quality.HDTV720p), Language.German); - var decisions = new List(); decisions.Add(new DownloadDecision(remoteEpisode1)); decisions.Add(new DownloadDecision(remoteEpisode2)); @@ -583,7 +579,7 @@ public void sort_download_decisions_based_on_indexer_priority() var remoteEpisode3 = GivenRemoteEpisode(new List { GivenEpisode(1) }, new QualityModel(Quality.WEBDL1080p, new Revision(1)), Language.English, indexerPriority: 1); var decisions = new List(); - decisions.AddRange(new [] { new DownloadDecision(remoteEpisode1), new DownloadDecision(remoteEpisode2), new DownloadDecision(remoteEpisode3) }); + decisions.AddRange(new[] { new DownloadDecision(remoteEpisode1), new DownloadDecision(remoteEpisode2), new DownloadDecision(remoteEpisode3) }); var qualifiedReports = Subject.PrioritizeDecisions(decisions); qualifiedReports.First().RemoteEpisode.Should().Be(remoteEpisode3); diff --git a/src/NzbDrone.Core.Test/DecisionEngineTests/ProtocolSpecificationFixture.cs b/src/NzbDrone.Core.Test/DecisionEngineTests/ProtocolSpecificationFixture.cs index 4bfaf34dc..a37399371 100644 --- a/src/NzbDrone.Core.Test/DecisionEngineTests/ProtocolSpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/DecisionEngineTests/ProtocolSpecificationFixture.cs @@ -23,7 +23,7 @@ public void Setup() _remoteEpisode = new RemoteEpisode(); _remoteEpisode.Release = new ReleaseInfo(); _remoteEpisode.Series = new Series(); - + _delayProfile = new DelayProfile(); Mocker.GetMock() @@ -72,4 +72,4 @@ public void should_be_false_if_torrent_and_torrent_is_disabled() Subject.IsSatisfiedBy(_remoteEpisode, null).Accepted.Should().Be(false); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core.Test/DecisionEngineTests/QualityAllowedByProfileSpecificationFixture.cs b/src/NzbDrone.Core.Test/DecisionEngineTests/QualityAllowedByProfileSpecificationFixture.cs index d45d58de5..f015b9fae 100644 --- a/src/NzbDrone.Core.Test/DecisionEngineTests/QualityAllowedByProfileSpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/DecisionEngineTests/QualityAllowedByProfileSpecificationFixture.cs @@ -1,4 +1,4 @@ -using FizzWare.NBuilder; +using FizzWare.NBuilder; using FluentAssertions; using Marr.Data; using NUnit.Framework; @@ -6,8 +6,8 @@ using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Profiles.Qualities; using NzbDrone.Core.Qualities; -using NzbDrone.Core.Tv; using NzbDrone.Core.Test.Framework; +using NzbDrone.Core.Tv; namespace NzbDrone.Core.Test.DecisionEngineTests { @@ -15,7 +15,7 @@ namespace NzbDrone.Core.Test.DecisionEngineTests public class QualityAllowedByProfileSpecificationFixture : CoreTest { - private RemoteEpisode remoteEpisode; + private RemoteEpisode _remoteEpisode; public static object[] AllowedTestCases = { @@ -38,29 +38,31 @@ public void Setup() .With(c => c.QualityProfile = (LazyLoaded)new QualityProfile { Cutoff = Quality.Bluray1080p.Id }) .Build(); - remoteEpisode = new RemoteEpisode + _remoteEpisode = new RemoteEpisode { Series = fakeSeries, ParsedEpisodeInfo = new ParsedEpisodeInfo { Quality = new QualityModel(Quality.DVD, new Revision(version: 2)) }, }; } - [Test, TestCaseSource(nameof(AllowedTestCases))] + [Test] + [TestCaseSource(nameof(AllowedTestCases))] public void should_allow_if_quality_is_defined_in_profile(Quality qualityType) { - remoteEpisode.ParsedEpisodeInfo.Quality.Quality = qualityType; - remoteEpisode.Series.QualityProfile.Value.Items = Qualities.QualityFixture.GetDefaultQualities(Quality.DVD, Quality.HDTV720p, Quality.Bluray1080p); + _remoteEpisode.ParsedEpisodeInfo.Quality.Quality = qualityType; + _remoteEpisode.Series.QualityProfile.Value.Items = Qualities.QualityFixture.GetDefaultQualities(Quality.DVD, Quality.HDTV720p, Quality.Bluray1080p); - Subject.IsSatisfiedBy(remoteEpisode, null).Accepted.Should().BeTrue(); + Subject.IsSatisfiedBy(_remoteEpisode, null).Accepted.Should().BeTrue(); } - [Test, TestCaseSource(nameof(DeniedTestCases))] + [Test] + [TestCaseSource(nameof(DeniedTestCases))] public void should_not_allow_if_quality_is_not_defined_in_profile(Quality qualityType) { - remoteEpisode.ParsedEpisodeInfo.Quality.Quality = qualityType; - remoteEpisode.Series.QualityProfile.Value.Items = Qualities.QualityFixture.GetDefaultQualities(Quality.DVD, Quality.HDTV720p, Quality.Bluray1080p); + _remoteEpisode.ParsedEpisodeInfo.Quality.Quality = qualityType; + _remoteEpisode.Series.QualityProfile.Value.Items = Qualities.QualityFixture.GetDefaultQualities(Quality.DVD, Quality.HDTV720p, Quality.Bluray1080p); - Subject.IsSatisfiedBy(remoteEpisode, null).Accepted.Should().BeFalse(); + Subject.IsSatisfiedBy(_remoteEpisode, null).Accepted.Should().BeFalse(); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core.Test/DecisionEngineTests/QueueSpecificationFixture.cs b/src/NzbDrone.Core.Test/DecisionEngineTests/QueueSpecificationFixture.cs index 94fd60f9e..63af2dbd9 100644 --- a/src/NzbDrone.Core.Test/DecisionEngineTests/QueueSpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/DecisionEngineTests/QueueSpecificationFixture.cs @@ -5,14 +5,14 @@ using NUnit.Framework; using NzbDrone.Core.DecisionEngine.Specifications; using NzbDrone.Core.Download.TrackedDownloads; -using NzbDrone.Core.Profiles.Languages; +using NzbDrone.Core.Languages; using NzbDrone.Core.Parser.Model; +using NzbDrone.Core.Profiles.Languages; using NzbDrone.Core.Profiles.Qualities; using NzbDrone.Core.Qualities; using NzbDrone.Core.Queue; -using NzbDrone.Core.Tv; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Languages; +using NzbDrone.Core.Tv; namespace NzbDrone.Core.Test.DecisionEngineTests { @@ -34,12 +34,12 @@ public void Setup() Mocker.Resolve(); _series = Builder.CreateNew() - .With(e => e.QualityProfile = new QualityProfile + .With(e => e.QualityProfile = new QualityProfile { UpgradeAllowed = true, Items = Qualities.QualityFixture.GetDefaultQualities() }) - .With(l => l.LanguageProfile = new LanguageProfile + .With(l => l.LanguageProfile = new LanguageProfile { Languages = Languages.LanguageFixture.GetDefaultLanguages(), UpgradeAllowed = true, @@ -68,7 +68,7 @@ public void Setup() _remoteEpisode = Builder.CreateNew() .With(r => r.Series = _series) .With(r => r.Episodes = new List { _episode }) - .With(r => r.ParsedEpisodeInfo = new ParsedEpisodeInfo { Quality = new QualityModel(Quality.DVD) , Language = Language.Spanish}) + .With(r => r.ParsedEpisodeInfo = new ParsedEpisodeInfo { Quality = new QualityModel(Quality.DVD), Language = Language.Spanish }) .With(r => r.PreferredWordScore = 0) .Build(); } @@ -359,7 +359,7 @@ public void should_return_false_if_multi_part_episode_has_two_episodes_in_queue( Quality = new QualityModel( Quality.HDTV720p), - Language = Language.English + Language = Language.English }) .With(r => r.Release = _releaseInfo) .TheFirst(1) @@ -452,7 +452,6 @@ public void should_return_true_if_everything_is_the_same_for_failed_pending() .Build(); GivenQueue(new List { remoteEpisode }, TrackedDownloadState.FailedPending); - Subject.IsSatisfiedBy(_remoteEpisode, null).Accepted.Should().BeTrue(); } diff --git a/src/NzbDrone.Core.Test/DecisionEngineTests/RawDiskSpecificationFixture.cs b/src/NzbDrone.Core.Test/DecisionEngineTests/RawDiskSpecificationFixture.cs index 014225692..a07f6dca9 100644 --- a/src/NzbDrone.Core.Test/DecisionEngineTests/RawDiskSpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/DecisionEngineTests/RawDiskSpecificationFixture.cs @@ -1,10 +1,9 @@ using FluentAssertions; using NUnit.Framework; using NzbDrone.Core.DecisionEngine.Specifications; -using NzbDrone.Core.Parser.Model; - -using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Indexers; +using NzbDrone.Core.Parser.Model; +using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.DecisionEngineTests { @@ -31,7 +30,7 @@ private void WithContainer(string container) { _remoteEpisode.Release.Container = container; } - + [Test] public void should_return_true_if_no_container_specified_and_does_not_match_disc_release_pattern() { @@ -84,4 +83,4 @@ public void should_return_false_if_matches_disc_format(string title) Subject.IsSatisfiedBy(_remoteEpisode, null).Accepted.Should().BeFalse(); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core.Test/DecisionEngineTests/RepackSpecificationFixture.cs b/src/NzbDrone.Core.Test/DecisionEngineTests/RepackSpecificationFixture.cs index 1fe7fff7d..43f365730 100644 --- a/src/NzbDrone.Core.Test/DecisionEngineTests/RepackSpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/DecisionEngineTests/RepackSpecificationFixture.cs @@ -4,11 +4,11 @@ using FluentAssertions; using Moq; using NUnit.Framework; -using NzbDrone.Core.Qualities; using NzbDrone.Core.DecisionEngine.Specifications; using NzbDrone.Core.MediaFiles; -using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Parser.Model; +using NzbDrone.Core.Qualities; +using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Tv; namespace NzbDrone.Core.Test.DecisionEngineTests diff --git a/src/NzbDrone.Core.Test/DecisionEngineTests/RetentionSpecificationFixture.cs b/src/NzbDrone.Core.Test/DecisionEngineTests/RetentionSpecificationFixture.cs index a9c8ace61..362d471b6 100644 --- a/src/NzbDrone.Core.Test/DecisionEngineTests/RetentionSpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/DecisionEngineTests/RetentionSpecificationFixture.cs @@ -90,4 +90,4 @@ public void should_return_true_when_release_is_not_usenet() Subject.IsSatisfiedBy(_remoteEpisode, null).Accepted.Should().BeTrue(); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core.Test/DecisionEngineTests/RssSync/DelaySpecificationFixture.cs b/src/NzbDrone.Core.Test/DecisionEngineTests/RssSync/DelaySpecificationFixture.cs index deb2d8ba2..35a3ea78e 100644 --- a/src/NzbDrone.Core.Test/DecisionEngineTests/RssSync/DelaySpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/DecisionEngineTests/RssSync/DelaySpecificationFixture.cs @@ -11,15 +11,15 @@ using NzbDrone.Core.Download.Pending; using NzbDrone.Core.Indexers; using NzbDrone.Core.IndexerSearch.Definitions; +using NzbDrone.Core.Languages; using NzbDrone.Core.MediaFiles; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Profiles.Delay; +using NzbDrone.Core.Profiles.Languages; +using NzbDrone.Core.Profiles.Qualities; using NzbDrone.Core.Qualities; using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Tv; -using NzbDrone.Core.Languages; -using NzbDrone.Core.Profiles.Qualities; -using NzbDrone.Core.Profiles.Languages; namespace NzbDrone.Core.Test.DecisionEngineTests.RssSync { diff --git a/src/NzbDrone.Core.Test/DecisionEngineTests/RssSync/DeletedEpisodeFileSpecificationFixture.cs b/src/NzbDrone.Core.Test/DecisionEngineTests/RssSync/DeletedEpisodeFileSpecificationFixture.cs index 22942ca92..1802794c1 100644 --- a/src/NzbDrone.Core.Test/DecisionEngineTests/RssSync/DeletedEpisodeFileSpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/DecisionEngineTests/RssSync/DeletedEpisodeFileSpecificationFixture.cs @@ -1,24 +1,23 @@ using System; using System.Collections.Generic; +using System.IO; using FizzWare.NBuilder; using FluentAssertions; +using Moq; using NUnit.Framework; +using NzbDrone.Common.Disk; using NzbDrone.Core.Configuration; +using NzbDrone.Core.DecisionEngine; using NzbDrone.Core.DecisionEngine.Specifications.RssSync; using NzbDrone.Core.IndexerSearch.Definitions; using NzbDrone.Core.MediaFiles; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Profiles; -using NzbDrone.Core.Qualities; -using NzbDrone.Core.Tv; -using NzbDrone.Core.DecisionEngine; - -using NzbDrone.Core.Test.Framework; -using NzbDrone.Common.Disk; -using Moq; -using NzbDrone.Test.Common; -using System.IO; using NzbDrone.Core.Profiles.Qualities; +using NzbDrone.Core.Qualities; +using NzbDrone.Core.Test.Framework; +using NzbDrone.Core.Tv; +using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.DecisionEngineTests.RssSync { @@ -49,7 +48,8 @@ public void Setup() }; var singleEpisodeList = new List { new Episode { EpisodeFile = _firstFile, EpisodeFileId = 1 } }; - var doubleEpisodeList = new List { + var doubleEpisodeList = new List + { new Episode { EpisodeFile = _firstFile, EpisodeFileId = 1 }, new Episode { EpisodeFile = _secondFile, EpisodeFileId = 2 } }; diff --git a/src/NzbDrone.Core.Test/DecisionEngineTests/RssSync/HistorySpecificationFixture.cs b/src/NzbDrone.Core.Test/DecisionEngineTests/RssSync/HistorySpecificationFixture.cs index 4bf22de35..04a380274 100644 --- a/src/NzbDrone.Core.Test/DecisionEngineTests/RssSync/HistorySpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/DecisionEngineTests/RssSync/HistorySpecificationFixture.cs @@ -5,24 +5,27 @@ using Moq; using NUnit.Framework; using NzbDrone.Core.Configuration; +using NzbDrone.Core.DecisionEngine.Specifications; using NzbDrone.Core.DecisionEngine.Specifications.RssSync; using NzbDrone.Core.History; using NzbDrone.Core.IndexerSearch.Definitions; -using NzbDrone.Core.Parser.Model; -using NzbDrone.Core.Qualities; -using NzbDrone.Core.Tv; -using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.DecisionEngine.Specifications; -using NzbDrone.Core.Profiles.Qualities; -using NzbDrone.Core.Profiles.Languages; using NzbDrone.Core.Languages; +using NzbDrone.Core.Parser.Model; +using NzbDrone.Core.Profiles.Languages; +using NzbDrone.Core.Profiles.Qualities; +using NzbDrone.Core.Qualities; +using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Test.Languages; +using NzbDrone.Core.Tv; namespace NzbDrone.Core.Test.DecisionEngineTests.RssSync { [TestFixture] public class HistorySpecificationFixture : CoreTest { + private const int FIRST_EPISODE_ID = 1; + private const int SECOND_EPISODE_ID = 2; + private HistorySpecification _upgradeHistory; private RemoteEpisode _parseResultMulti; @@ -30,8 +33,6 @@ public class HistorySpecificationFixture : CoreTest private Tuple _upgradableQuality; private Tuple _notupgradableQuality; private Series _fakeSeries; - private const int FIRST_EPISODE_ID = 1; - private const int SECOND_EPISODE_ID = 2; [SetUp] public void Setup() @@ -40,11 +41,12 @@ public void Setup() _upgradeHistory = Mocker.Resolve(); var singleEpisodeList = new List { new Episode { Id = FIRST_EPISODE_ID, SeasonNumber = 12, EpisodeNumber = 3 } }; - var doubleEpisodeList = new List { - new Episode {Id = FIRST_EPISODE_ID, SeasonNumber = 12, EpisodeNumber = 3 }, - new Episode {Id = SECOND_EPISODE_ID, SeasonNumber = 12, EpisodeNumber = 4 }, - new Episode {Id = 3, SeasonNumber = 12, EpisodeNumber = 5 } - }; + var doubleEpisodeList = new List + { + new Episode { Id = FIRST_EPISODE_ID, SeasonNumber = 12, EpisodeNumber = 3 }, + new Episode { Id = SECOND_EPISODE_ID, SeasonNumber = 12, EpisodeNumber = 4 }, + new Episode { Id = 3, SeasonNumber = 12, EpisodeNumber = 5 } + }; _fakeSeries = Builder.CreateNew() .With(c => c.QualityProfile = new QualityProfile @@ -75,9 +77,9 @@ public void Setup() Episodes = singleEpisodeList }; - _upgradableQuality = new Tuple (new QualityModel(Quality.SDTV, new Revision(version: 1)), Language.English); + _upgradableQuality = new Tuple(new QualityModel(Quality.SDTV, new Revision(version: 1)), Language.English); - _notupgradableQuality = new Tuple (new QualityModel(Quality.HDTV1080p, new Revision(version: 2)), Language.English); + _notupgradableQuality = new Tuple(new QualityModel(Quality.HDTV1080p, new Revision(version: 2)), Language.English); Mocker.GetMock() .SetupGet(s => s.EnableCompletedDownloadHandling) diff --git a/src/NzbDrone.Core.Test/DecisionEngineTests/RssSync/ProperSpecificationFixture.cs b/src/NzbDrone.Core.Test/DecisionEngineTests/RssSync/ProperSpecificationFixture.cs index 5204cf715..0a8d52aee 100644 --- a/src/NzbDrone.Core.Test/DecisionEngineTests/RssSync/ProperSpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/DecisionEngineTests/RssSync/ProperSpecificationFixture.cs @@ -4,15 +4,15 @@ using FluentAssertions; using NUnit.Framework; using NzbDrone.Core.Configuration; +using NzbDrone.Core.DecisionEngine.Specifications; using NzbDrone.Core.DecisionEngine.Specifications.RssSync; using NzbDrone.Core.IndexerSearch.Definitions; using NzbDrone.Core.MediaFiles; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Profiles.Qualities; using NzbDrone.Core.Qualities; -using NzbDrone.Core.Tv; -using NzbDrone.Core.DecisionEngine.Specifications; using NzbDrone.Core.Test.Framework; +using NzbDrone.Core.Tv; namespace NzbDrone.Core.Test.DecisionEngineTests.RssSync { @@ -146,4 +146,4 @@ public void should_return_true_when_propers_are_not_preferred() Subject.IsSatisfiedBy(_parseResultSingle, null).Accepted.Should().BeTrue(); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core.Test/DecisionEngineTests/SameEpisodesSpecificationFixture.cs b/src/NzbDrone.Core.Test/DecisionEngineTests/SameEpisodesSpecificationFixture.cs index 65c14997a..697800c5a 100644 --- a/src/NzbDrone.Core.Test/DecisionEngineTests/SameEpisodesSpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/DecisionEngineTests/SameEpisodesSpecificationFixture.cs @@ -5,9 +5,8 @@ using Moq; using NUnit.Framework; using NzbDrone.Core.DecisionEngine.Specifications; -using NzbDrone.Core.Tv; - using NzbDrone.Core.Test.Framework; +using NzbDrone.Core.Tv; namespace NzbDrone.Core.Test.DecisionEngineTests { diff --git a/src/NzbDrone.Core.Test/DecisionEngineTests/Search/SingleEpisodeSearchMatchSpecificationTests/StandardEpisodeSearch.cs b/src/NzbDrone.Core.Test/DecisionEngineTests/Search/SingleEpisodeSearchMatchSpecificationTests/StandardEpisodeSearch.cs index a2c02ff30..4e2a462c5 100644 --- a/src/NzbDrone.Core.Test/DecisionEngineTests/Search/SingleEpisodeSearchMatchSpecificationTests/StandardEpisodeSearch.cs +++ b/src/NzbDrone.Core.Test/DecisionEngineTests/Search/SingleEpisodeSearchMatchSpecificationTests/StandardEpisodeSearch.cs @@ -79,4 +79,4 @@ public void should_return_true_if_full_season_result_for_full_season_search() Subject.IsSatisfiedBy(_remoteEpisode, _searchCriteria).Accepted.Should().BeTrue(); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core.Test/DecisionEngineTests/Search/TorrentSeedingSpecificationFixture.cs b/src/NzbDrone.Core.Test/DecisionEngineTests/Search/TorrentSeedingSpecificationFixture.cs index 6dd6f2aec..dfb299b2d 100644 --- a/src/NzbDrone.Core.Test/DecisionEngineTests/Search/TorrentSeedingSpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/DecisionEngineTests/Search/TorrentSeedingSpecificationFixture.cs @@ -43,7 +43,6 @@ public void Setup() Mocker.GetMock() .Setup(v => v.Get(1)) .Returns(_indexerDefinition); - } private void GivenReleaseSeeders(int? seeders) diff --git a/src/NzbDrone.Core.Test/DecisionEngineTests/SingleEpisodeAgeDownloadDecisionFixture.cs b/src/NzbDrone.Core.Test/DecisionEngineTests/SingleEpisodeAgeDownloadDecisionFixture.cs index 826599393..135f6018c 100644 --- a/src/NzbDrone.Core.Test/DecisionEngineTests/SingleEpisodeAgeDownloadDecisionFixture.cs +++ b/src/NzbDrone.Core.Test/DecisionEngineTests/SingleEpisodeAgeDownloadDecisionFixture.cs @@ -1,69 +1,70 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; -using NzbDrone.Core.Tv; -using NzbDrone.Core.Qualities; -using NzbDrone.Core.Parser.Model; -using NUnit.Framework; -using FluentAssertions; using FizzWare.NBuilder; -using NzbDrone.Core.Test.Framework; +using FluentAssertions; +using NUnit.Framework; using NzbDrone.Core.DecisionEngine.Specifications; using NzbDrone.Core.IndexerSearch.Definitions; +using NzbDrone.Core.Parser.Model; +using NzbDrone.Core.Qualities; +using NzbDrone.Core.Test.Framework; +using NzbDrone.Core.Tv; namespace NzbDrone.Core.Test.DecisionEngineTests { [TestFixture] public class SingleEpisodeAgeDownloadDecisionFixture : CoreTest { - private RemoteEpisode parseResultMulti; - private RemoteEpisode parseResultSingle; - private Series series; - private List episodes; - private SeasonSearchCriteria multiSearch; + private RemoteEpisode _parseResultMulti; + private RemoteEpisode _parseResultSingle; + private Series _series; + private List _episodes; + private SeasonSearchCriteria _multiSearch; [SetUp] public void Setup() { - series = Builder.CreateNew() + _series = Builder.CreateNew() .With(s => s.Seasons = Builder.CreateListOfSize(1).Build().ToList()) .With(s => s.SeriesType = SeriesTypes.Standard) .Build(); - episodes = new List(); - episodes.Add(CreateEpisodeStub(1, 400)); - episodes.Add(CreateEpisodeStub(2, 370)); - episodes.Add(CreateEpisodeStub(3, 340)); - episodes.Add(CreateEpisodeStub(4, 310)); + _episodes = new List(); + _episodes.Add(CreateEpisodeStub(1, 400)); + _episodes.Add(CreateEpisodeStub(2, 370)); + _episodes.Add(CreateEpisodeStub(3, 340)); + _episodes.Add(CreateEpisodeStub(4, 310)); - multiSearch = new SeasonSearchCriteria(); - multiSearch.Episodes = episodes.ToList(); - multiSearch.SeasonNumber = 1; + _multiSearch = new SeasonSearchCriteria(); + _multiSearch.Episodes = _episodes.ToList(); + _multiSearch.SeasonNumber = 1; - parseResultMulti = new RemoteEpisode + _parseResultMulti = new RemoteEpisode { - Series = series, + Series = _series, Release = new ReleaseInfo(), ParsedEpisodeInfo = new ParsedEpisodeInfo { Quality = new QualityModel(Quality.SDTV, new Revision(version: 2)), FullSeason = true }, - Episodes = episodes.ToList() + Episodes = _episodes.ToList() }; - parseResultSingle = new RemoteEpisode + _parseResultSingle = new RemoteEpisode { - Series = series, + Series = _series, Release = new ReleaseInfo(), ParsedEpisodeInfo = new ParsedEpisodeInfo { Quality = new QualityModel(Quality.SDTV, new Revision(version: 2)) }, Episodes = new List() }; } - Episode CreateEpisodeStub(int number, int age) + private Episode CreateEpisodeStub(int number, int age) { - return new Episode() { - SeasonNumber = 1, - EpisodeNumber = number, - AirDateUtc = DateTime.UtcNow.AddDays(-age) - }; + return new Episode() + { + SeasonNumber = 1, + EpisodeNumber = number, + AirDateUtc = DateTime.UtcNow.AddDays(-age) + }; } [TestCase(1, 200, false)] @@ -72,13 +73,13 @@ Episode CreateEpisodeStub(int number, int age) [TestCase(1, 365, true)] [TestCase(4, 365, true)] [TestCase(1, 0, true)] - public void single_episode_release(int episode, int SeasonSearchMaximumSingleEpisodeAge, bool expectedResult) + public void single_episode_release(int episode, int seasonSearchMaximumSingleEpisodeAge, bool expectedResult) { - parseResultSingle.Release.SeasonSearchMaximumSingleEpisodeAge = SeasonSearchMaximumSingleEpisodeAge; - parseResultSingle.Episodes.Clear(); - parseResultSingle.Episodes.Add(episodes.Find(e => e.EpisodeNumber == episode)); + _parseResultSingle.Release.SeasonSearchMaximumSingleEpisodeAge = seasonSearchMaximumSingleEpisodeAge; + _parseResultSingle.Episodes.Clear(); + _parseResultSingle.Episodes.Add(_episodes.Find(e => e.EpisodeNumber == episode)); - Subject.IsSatisfiedBy(parseResultSingle, multiSearch).Accepted.Should().Be(expectedResult); + Subject.IsSatisfiedBy(_parseResultSingle, _multiSearch).Accepted.Should().Be(expectedResult); } // should always accept all season packs @@ -86,11 +87,11 @@ public void single_episode_release(int episode, int SeasonSearchMaximumSingleEpi [TestCase(600, true)] [TestCase(365, true)] [TestCase(0, true)] - public void multi_episode_release(int SeasonSearchMaximumSingleEpisodeAge, bool expectedResult) + public void multi_episode_release(int seasonSearchMaximumSingleEpisodeAge, bool expectedResult) { - parseResultMulti.Release.SeasonSearchMaximumSingleEpisodeAge = SeasonSearchMaximumSingleEpisodeAge; + _parseResultMulti.Release.SeasonSearchMaximumSingleEpisodeAge = seasonSearchMaximumSingleEpisodeAge; - Subject.IsSatisfiedBy(parseResultMulti, multiSearch).Accepted.Should().BeTrue(); + Subject.IsSatisfiedBy(_parseResultMulti, _multiSearch).Accepted.Should().BeTrue(); } } } diff --git a/src/NzbDrone.Core.Test/DecisionEngineTests/UpgradeAllowedSpecificationFixture .cs b/src/NzbDrone.Core.Test/DecisionEngineTests/UpgradeAllowedSpecificationFixture .cs index 403405cbf..aa98be479 100644 --- a/src/NzbDrone.Core.Test/DecisionEngineTests/UpgradeAllowedSpecificationFixture .cs +++ b/src/NzbDrone.Core.Test/DecisionEngineTests/UpgradeAllowedSpecificationFixture .cs @@ -1,11 +1,11 @@ using FluentAssertions; using NUnit.Framework; -using NzbDrone.Core.Profiles.Qualities; -using NzbDrone.Core.Qualities; using NzbDrone.Core.DecisionEngine.Specifications; -using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Languages; using NzbDrone.Core.Profiles.Languages; +using NzbDrone.Core.Profiles.Qualities; +using NzbDrone.Core.Qualities; +using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Test.Languages; namespace NzbDrone.Core.Test.DecisionEngineTests @@ -32,8 +32,8 @@ public void should_return_false_when_quality_are_the_same_language_is_better_and new QualityModel(Quality.DVD), Language.English, new QualityModel(Quality.DVD), - Language.French - ).Should().BeFalse(); + Language.French) + .Should().BeFalse(); } [Test] @@ -55,8 +55,8 @@ public void should_return_false_when_quality_is_better_languages_are_the_same_an new QualityModel(Quality.DVD), Language.English, new QualityModel(Quality.Bluray1080p), - Language.English - ).Should().BeFalse(); + Language.English) + .Should().BeFalse(); } [Test] @@ -78,8 +78,8 @@ public void should_return_true_for_language_upgrade_when_upgrading_is_allowed() new QualityModel(Quality.DVD), Language.English, new QualityModel(Quality.DVD), - Language.French - ).Should().BeTrue(); + Language.French) + .Should().BeTrue(); } [Test] @@ -101,8 +101,8 @@ public void should_return_true_for_same_language_when_upgrading_is_allowed() new QualityModel(Quality.DVD), Language.English, new QualityModel(Quality.DVD), - Language.English - ).Should().BeTrue(); + Language.English) + .Should().BeTrue(); } [Test] @@ -124,8 +124,8 @@ public void should_return_true_for_same_language_when_upgrading_is_not_allowed() new QualityModel(Quality.DVD), Language.English, new QualityModel(Quality.DVD), - Language.English - ).Should().BeTrue(); + Language.English) + .Should().BeTrue(); } [Test] @@ -147,8 +147,8 @@ public void should_return_true_for_lower_language_when_upgrading_is_allowed() new QualityModel(Quality.DVD), Language.French, new QualityModel(Quality.DVD), - Language.English - ).Should().BeTrue(); + Language.English) + .Should().BeTrue(); } [Test] @@ -170,8 +170,8 @@ public void should_return_true_for_lower_language_when_upgrading_is_not_allowed( new QualityModel(Quality.DVD), Language.French, new QualityModel(Quality.DVD), - Language.English - ).Should().BeTrue(); + Language.English) + .Should().BeTrue(); } [Test] @@ -193,8 +193,8 @@ public void should_return_true_for_quality_upgrade_when_upgrading_is_allowed() new QualityModel(Quality.DVD), Language.English, new QualityModel(Quality.Bluray1080p), - Language.English - ).Should().BeTrue(); + Language.English) + .Should().BeTrue(); } [Test] @@ -216,8 +216,8 @@ public void should_return_true_for_same_quality_when_upgrading_is_allowed() new QualityModel(Quality.DVD), Language.English, new QualityModel(Quality.DVD), - Language.English - ).Should().BeTrue(); + Language.English) + .Should().BeTrue(); } [Test] @@ -239,8 +239,8 @@ public void should_return_true_for_same_quality_when_upgrading_is_not_allowed() new QualityModel(Quality.DVD), Language.English, new QualityModel(Quality.DVD), - Language.English - ).Should().BeTrue(); + Language.English) + .Should().BeTrue(); } [Test] @@ -262,8 +262,8 @@ public void should_return_true_for_lower_quality_when_upgrading_is_allowed() new QualityModel(Quality.DVD), Language.English, new QualityModel(Quality.SDTV), - Language.English - ).Should().BeTrue(); + Language.English) + .Should().BeTrue(); } [Test] @@ -285,8 +285,8 @@ public void should_return_true_for_lower_quality_when_upgrading_is_not_allowed() new QualityModel(Quality.DVD), Language.English, new QualityModel(Quality.SDTV), - Language.English - ).Should().BeTrue(); + Language.English) + .Should().BeTrue(); } } } diff --git a/src/NzbDrone.Core.Test/DecisionEngineTests/UpgradeDiskSpecificationFixture.cs b/src/NzbDrone.Core.Test/DecisionEngineTests/UpgradeDiskSpecificationFixture.cs index fdb18989e..aed59f39e 100644 --- a/src/NzbDrone.Core.Test/DecisionEngineTests/UpgradeDiskSpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/DecisionEngineTests/UpgradeDiskSpecificationFixture.cs @@ -4,16 +4,16 @@ using FluentAssertions; using Moq; using NUnit.Framework; +using NzbDrone.Core.DecisionEngine; using NzbDrone.Core.DecisionEngine.Specifications; +using NzbDrone.Core.Languages; using NzbDrone.Core.MediaFiles; using NzbDrone.Core.Parser.Model; +using NzbDrone.Core.Profiles.Languages; using NzbDrone.Core.Profiles.Qualities; using NzbDrone.Core.Qualities; -using NzbDrone.Core.Tv; -using NzbDrone.Core.DecisionEngine; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Languages; -using NzbDrone.Core.Profiles.Languages; +using NzbDrone.Core.Tv; namespace NzbDrone.Core.Test.DecisionEngineTests { @@ -139,7 +139,7 @@ public void should_not_be_upgradable_if_qualities_are_the_same() _parseResultSingle.ParsedEpisodeInfo.Quality = new QualityModel(Quality.WEBDL1080p); _upgradeDisk.IsSatisfiedBy(_parseResultSingle, null).Accepted.Should().BeFalse(); } - + [Test] public void should_not_be_upgradable_if_revision_downgrade_and_preferred_word_upgrade_if_propers_are_preferred() { diff --git a/src/NzbDrone.Core.Test/DecisionEngineTests/UpgradeSpecificationFixture.cs b/src/NzbDrone.Core.Test/DecisionEngineTests/UpgradeSpecificationFixture.cs index 0ee7387ae..f73def46b 100644 --- a/src/NzbDrone.Core.Test/DecisionEngineTests/UpgradeSpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/DecisionEngineTests/UpgradeSpecificationFixture.cs @@ -1,18 +1,18 @@ using FluentAssertions; using NUnit.Framework; using NzbDrone.Core.Configuration; -using NzbDrone.Core.Profiles.Qualities; -using NzbDrone.Core.Qualities; using NzbDrone.Core.DecisionEngine.Specifications; -using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Languages; using NzbDrone.Core.Profiles.Languages; +using NzbDrone.Core.Profiles.Qualities; +using NzbDrone.Core.Qualities; +using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Test.Languages; namespace NzbDrone.Core.Test.DecisionEngineTests { [TestFixture] - + public class UpgradeSpecificationFixture : CoreTest { public static object[] IsUpgradeTestCases = @@ -45,12 +45,12 @@ private void GivenAutoDownloadPropers(ProperDownloadTypes type) .Returns(type); } - [Test, TestCaseSource(nameof(IsUpgradeTestCases))] + [Test] + [TestCaseSource(nameof(IsUpgradeTestCases))] public void IsUpgradeTest(Quality current, int currentVersion, Quality newQuality, int newVersion, Quality cutoff, bool expected) { GivenAutoDownloadPropers(ProperDownloadTypes.PreferAndUpgrade); - var profile = new QualityProfile { UpgradeAllowed = true, @@ -76,7 +76,8 @@ public void IsUpgradeTest(Quality current, int currentVersion, Quality newQualit .Should().Be(expected); } - [Test, TestCaseSource("IsUpgradeTestCasesLanguages")] + [Test] + [TestCaseSource("IsUpgradeTestCasesLanguages")] public void IsUpgradeTestLanguage(Quality current, int currentVersion, Language currentLanguage, Quality newQuality, int newVersion, Language newLanguage, Quality cutoff, Language languageCutoff, bool expected) { GivenAutoDownloadPropers(ProperDownloadTypes.PreferAndUpgrade); @@ -112,8 +113,8 @@ public void should_return_true_if_proper_and_download_propers_is_do_not_download { GivenAutoDownloadPropers(ProperDownloadTypes.DoNotUpgrade); - var profile = new QualityProfile - { + var profile = new QualityProfile + { Items = Qualities.QualityFixture.GetDefaultQualities(), }; @@ -123,7 +124,6 @@ public void should_return_true_if_proper_and_download_propers_is_do_not_download Cutoff = Language.English }; - Subject.IsUpgradable( profile, langProfile, @@ -152,7 +152,6 @@ public void should_return_false_if_proper_and_autoDownloadPropers_is_do_not_pref Cutoff = Language.English }; - Subject.IsUpgradable( profile, langProfile, diff --git a/src/NzbDrone.Core.Test/Download/CompletedDownloadServiceTests/ImportFixture.cs b/src/NzbDrone.Core.Test/Download/CompletedDownloadServiceTests/ImportFixture.cs index 04a44f337..3c6797324 100644 --- a/src/NzbDrone.Core.Test/Download/CompletedDownloadServiceTests/ImportFixture.cs +++ b/src/NzbDrone.Core.Test/Download/CompletedDownloadServiceTests/ImportFixture.cs @@ -1,4 +1,4 @@ -using System.Collections.Generic; +using System.Collections.Generic; using FizzWare.NBuilder; using FluentAssertions; using Moq; @@ -48,7 +48,6 @@ public void Setup() .With(c => c.RemoteEpisode = remoteEpisode) .Build(); - Mocker.GetMock() .SetupGet(c => c.Definition) .Returns(new DownloadClientDefinition { Id = 1, Name = "testClient" }); @@ -79,7 +78,8 @@ private RemoteEpisode BuildRemoteEpisode() return new RemoteEpisode { Series = new Series(), - Episodes = new List { + Episodes = new List + { _episode1 } }; @@ -118,11 +118,11 @@ public void should_not_mark_as_imported_if_all_files_were_rejected() { new ImportResult( new ImportDecision( - new LocalEpisode {Path = @"C:\TestPath\Droned.S01E01.mkv", Episodes = { _episode1 }}, new Rejection("Rejected!")), "Test Failure"), + new LocalEpisode { Path = @"C:\TestPath\Droned.S01E01.mkv", Episodes = { _episode1 } }, new Rejection("Rejected!")), "Test Failure"), - new ImportResult( + new ImportResult( new ImportDecision( - new LocalEpisode {Path = @"C:\TestPath\Droned.S01E02.mkv", Episodes = { _episode2 }},new Rejection("Rejected!")), "Test Failure") + new LocalEpisode { Path = @"C:\TestPath\Droned.S01E02.mkv", Episodes = { _episode2 } }, new Rejection("Rejected!")), "Test Failure") }); Subject.Import(_trackedDownload); @@ -142,11 +142,11 @@ public void should_not_mark_as_imported_if_no_episodes_were_parsed() { new ImportResult( new ImportDecision( - new LocalEpisode {Path = @"C:\TestPath\Droned.S01E01.mkv", Episodes = { _episode1 }}, new Rejection("Rejected!")), "Test Failure"), + new LocalEpisode { Path = @"C:\TestPath\Droned.S01E01.mkv", Episodes = { _episode1 } }, new Rejection("Rejected!")), "Test Failure"), - new ImportResult( + new ImportResult( new ImportDecision( - new LocalEpisode {Path = @"C:\TestPath\Droned.S01E02.mkv", Episodes = { _episode2 }},new Rejection("Rejected!")), "Test Failure") + new LocalEpisode { Path = @"C:\TestPath\Droned.S01E02.mkv", Episodes = { _episode2 } }, new Rejection("Rejected!")), "Test Failure") }); _trackedDownload.RemoteEpisode.Episodes.Clear(); @@ -163,11 +163,10 @@ public void should_not_mark_as_imported_if_all_files_were_skipped() .Setup(v => v.ProcessPath(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) .Returns(new List { - new ImportResult(new ImportDecision(new LocalEpisode {Path = @"C:\TestPath\Droned.S01E01.mkv", Episodes = { _episode1 }}),"Test Failure"), - new ImportResult(new ImportDecision(new LocalEpisode {Path = @"C:\TestPath\Droned.S01E02.mkv", Episodes = { _episode2 }}),"Test Failure") + new ImportResult(new ImportDecision(new LocalEpisode { Path = @"C:\TestPath\Droned.S01E01.mkv", Episodes = { _episode1 } }), "Test Failure"), + new ImportResult(new ImportDecision(new LocalEpisode { Path = @"C:\TestPath\Droned.S01E02.mkv", Episodes = { _episode2 } }), "Test Failure") }); - Subject.Import(_trackedDownload); AssertNotImported(); @@ -187,9 +186,9 @@ public void should_not_mark_as_imported_if_some_of_episodes_were_not_imported() .Setup(v => v.ProcessPath(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) .Returns(new List { - new ImportResult(new ImportDecision(new LocalEpisode {Path = @"C:\TestPath\Droned.S01E01.mkv"})), - new ImportResult(new ImportDecision(new LocalEpisode{Path = @"C:\TestPath\Droned.S01E01.mkv"}),"Test Failure"), - new ImportResult(new ImportDecision(new LocalEpisode{Path = @"C:\TestPath\Droned.S01E01.mkv"}),"Test Failure") + new ImportResult(new ImportDecision(new LocalEpisode { Path = @"C:\TestPath\Droned.S01E01.mkv" })), + new ImportResult(new ImportDecision(new LocalEpisode { Path = @"C:\TestPath\Droned.S01E01.mkv" }), "Test Failure"), + new ImportResult(new ImportDecision(new LocalEpisode { Path = @"C:\TestPath\Droned.S01E01.mkv" }), "Test Failure") }); Mocker.GetMock() @@ -215,9 +214,9 @@ public void should_not_mark_as_imported_if_some_of_episodes_were_not_imported_in .Setup(v => v.ProcessPath(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) .Returns(new List { - new ImportResult(new ImportDecision(new LocalEpisode {Path = @"C:\TestPath\Droned.S01E01.mkv"})), - new ImportResult(new ImportDecision(new LocalEpisode{Path = @"C:\TestPath\Droned.S01E01.mkv"}),"Test Failure"), - new ImportResult(new ImportDecision(new LocalEpisode{Path = @"C:\TestPath\Droned.S01E01.mkv"}),"Test Failure") + new ImportResult(new ImportDecision(new LocalEpisode { Path = @"C:\TestPath\Droned.S01E01.mkv" })), + new ImportResult(new ImportDecision(new LocalEpisode { Path = @"C:\TestPath\Droned.S01E01.mkv" }), "Test Failure"), + new ImportResult(new ImportDecision(new LocalEpisode { Path = @"C:\TestPath\Droned.S01E01.mkv" }), "Test Failure") }); var history = Builder.CreateListOfSize(2) @@ -239,8 +238,8 @@ public void should_not_mark_as_imported_if_some_of_episodes_were_not_imported_in [Test] public void should_mark_as_imported_if_all_episodes_were_imported() { - var episode1 = new Episode {Id = 1}; - var episode2 = new Episode {Id = 2}; + var episode1 = new Episode { Id = 1 }; + var episode2 = new Episode { Id = 2 }; _trackedDownload.RemoteEpisode.Episodes = new List { episode1, episode2 }; Mocker.GetMock() @@ -249,11 +248,11 @@ public void should_mark_as_imported_if_all_episodes_were_imported() { new ImportResult( new ImportDecision( - new LocalEpisode {Path = @"C:\TestPath\Droned.S01E01.mkv", Episodes = new List { episode1 } })), + new LocalEpisode { Path = @"C:\TestPath\Droned.S01E01.mkv", Episodes = new List { episode1 } })), new ImportResult( new ImportDecision( - new LocalEpisode {Path = @"C:\TestPath\Droned.S01E02.mkv", Episodes = new List { episode2 } })) + new LocalEpisode { Path = @"C:\TestPath\Droned.S01E02.mkv", Episodes = new List { episode2 } })) }); Subject.Import(_trackedDownload); @@ -274,11 +273,11 @@ public void should_mark_as_imported_if_all_episodes_were_imported_including_hist { new ImportResult( new ImportDecision( - new LocalEpisode {Path = @"C:\TestPath\Droned.S01E01.mkv", Episodes = new List { episode1 } })), + new LocalEpisode { Path = @"C:\TestPath\Droned.S01E01.mkv", Episodes = new List { episode1 } })), new ImportResult( new ImportDecision( - new LocalEpisode {Path = @"C:\TestPath\Droned.S01E02.mkv", Episodes = new List { episode2 } }),"Test Failure") + new LocalEpisode { Path = @"C:\TestPath\Droned.S01E02.mkv", Episodes = new List { episode2 } }), "Test Failure") }); var history = Builder.CreateListOfSize(2) @@ -310,7 +309,7 @@ public void should_mark_as_imported_if_double_episode_file_is_imported() { new ImportResult( new ImportDecision( - new LocalEpisode {Path = @"C:\TestPath\Droned.S01E01-E02.mkv", Episodes = new List { episode1, episode2 } })) + new LocalEpisode { Path = @"C:\TestPath\Droned.S01E01-E02.mkv", Episodes = new List { episode1, episode2 } })) }); Subject.Import(_trackedDownload); @@ -332,8 +331,8 @@ public void should_mark_as_imported_if_all_episodes_were_imported_but_extra_file .Setup(v => v.ProcessPath(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) .Returns(new List { - new ImportResult(new ImportDecision(new LocalEpisode {Path = @"C:\TestPath\Droned.S01E01.mkv", Episodes = _trackedDownload.RemoteEpisode.Episodes})), - new ImportResult(new ImportDecision(new LocalEpisode{Path = @"C:\TestPath\Droned.S01E01.mkv"}),"Test Failure") + new ImportResult(new ImportDecision(new LocalEpisode { Path = @"C:\TestPath\Droned.S01E01.mkv", Episodes = _trackedDownload.RemoteEpisode.Episodes })), + new ImportResult(new ImportDecision(new LocalEpisode { Path = @"C:\TestPath\Droned.S01E01.mkv" }), "Test Failure") }); Subject.Import(_trackedDownload); @@ -350,7 +349,7 @@ public void should_mark_as_imported_if_the_download_can_be_tracked_using_the_sou .Setup(v => v.ProcessPath(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) .Returns(new List { - new ImportResult(new ImportDecision(new LocalEpisode {Path = @"C:\TestPath\Droned.S01E01.mkv", Episodes = _trackedDownload.RemoteEpisode.Episodes})) + new ImportResult(new ImportDecision(new LocalEpisode { Path = @"C:\TestPath\Droned.S01E01.mkv", Episodes = _trackedDownload.RemoteEpisode.Episodes })) }); Mocker.GetMock() diff --git a/src/NzbDrone.Core.Test/Download/CompletedDownloadServiceTests/ProcessFixture.cs b/src/NzbDrone.Core.Test/Download/CompletedDownloadServiceTests/ProcessFixture.cs index 76990c995..b8025b6c1 100644 --- a/src/NzbDrone.Core.Test/Download/CompletedDownloadServiceTests/ProcessFixture.cs +++ b/src/NzbDrone.Core.Test/Download/CompletedDownloadServiceTests/ProcessFixture.cs @@ -41,7 +41,6 @@ public void Setup() .With(c => c.RemoteEpisode = remoteEpisode) .Build(); - Mocker.GetMock() .SetupGet(c => c.Definition) .Returns(new DownloadClientDefinition { Id = 1, Name = "testClient" }); @@ -61,7 +60,6 @@ public void Setup() Mocker.GetMock() .Setup(s => s.GetSeries("Drone.S01E01.HDTV")) .Returns(remoteEpisode.Series); - } private RemoteEpisode BuildRemoteEpisode() @@ -144,7 +142,7 @@ public void should_process_if_matching_history_is_not_found_but_category_specifi [Test] public void should_not_process_if_output_path_is_empty() { - _trackedDownload.DownloadItem.OutputPath = new OsPath(); + _trackedDownload.DownloadItem.OutputPath = default(OsPath); Subject.Check(_trackedDownload); @@ -160,7 +158,7 @@ public void should_not_process_if_the_download_cannot_be_tracked_using_the_sourc .Setup(v => v.ProcessPath(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) .Returns(new List { - new ImportResult(new ImportDecision(new LocalEpisode {Path = @"C:\TestPath\Droned.S01E01.mkv"})) + new ImportResult(new ImportDecision(new LocalEpisode { Path = @"C:\TestPath\Droned.S01E01.mkv" })) }); Mocker.GetMock() diff --git a/src/NzbDrone.Core.Test/Download/DownloadApprovedReportsTests/DownloadApprovedFixture.cs b/src/NzbDrone.Core.Test/Download/DownloadApprovedReportsTests/DownloadApprovedFixture.cs index 47f03c65c..2adc35fed 100644 --- a/src/NzbDrone.Core.Test/Download/DownloadApprovedReportsTests/DownloadApprovedFixture.cs +++ b/src/NzbDrone.Core.Test/Download/DownloadApprovedReportsTests/DownloadApprovedFixture.cs @@ -90,13 +90,11 @@ public void should_not_download_if_any_episode_was_already_downloaded() { var remoteEpisode1 = GetRemoteEpisode( new List { GetEpisode(1) }, - new QualityModel(Quality.HDTV720p) - ); + new QualityModel(Quality.HDTV720p)); var remoteEpisode2 = GetRemoteEpisode( new List { GetEpisode(1), GetEpisode(2) }, - new QualityModel(Quality.HDTV720p) - ); + new QualityModel(Quality.HDTV720p)); var decisions = new List(); decisions.Add(new DownloadDecision(remoteEpisode1)); @@ -123,13 +121,11 @@ public void should_return_all_downloaded_reports() { var remoteEpisode1 = GetRemoteEpisode( new List { GetEpisode(1) }, - new QualityModel(Quality.HDTV720p) - ); + new QualityModel(Quality.HDTV720p)); var remoteEpisode2 = GetRemoteEpisode( new List { GetEpisode(2) }, - new QualityModel(Quality.HDTV720p) - ); + new QualityModel(Quality.HDTV720p)); var decisions = new List(); decisions.Add(new DownloadDecision(remoteEpisode1)); @@ -143,18 +139,15 @@ public void should_only_return_downloaded_reports() { var remoteEpisode1 = GetRemoteEpisode( new List { GetEpisode(1) }, - new QualityModel(Quality.HDTV720p) - ); + new QualityModel(Quality.HDTV720p)); var remoteEpisode2 = GetRemoteEpisode( new List { GetEpisode(2) }, - new QualityModel(Quality.HDTV720p) - ); + new QualityModel(Quality.HDTV720p)); var remoteEpisode3 = GetRemoteEpisode( new List { GetEpisode(2) }, - new QualityModel(Quality.HDTV720p) - ); + new QualityModel(Quality.HDTV720p)); var decisions = new List(); decisions.Add(new DownloadDecision(remoteEpisode1)); diff --git a/src/NzbDrone.Core.Test/Download/DownloadClientTests/Blackhole/UsenetBlackholeFixture.cs b/src/NzbDrone.Core.Test/Download/DownloadClientTests/Blackhole/UsenetBlackholeFixture.cs index 05d87043e..26bef6406 100644 --- a/src/NzbDrone.Core.Test/Download/DownloadClientTests/Blackhole/UsenetBlackholeFixture.cs +++ b/src/NzbDrone.Core.Test/Download/DownloadClientTests/Blackhole/UsenetBlackholeFixture.cs @@ -1,4 +1,3 @@ - using System; using System.Collections.Generic; using System.IO; @@ -17,7 +16,6 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.Blackhole { - [TestFixture] public class UsenetBlackholeFixture : DownloadClientFixtureBase { @@ -105,7 +103,6 @@ public void partial_download_should_have_required_properties() VerifyPostprocessing(result); } - [Test] public void should_return_category() { diff --git a/src/NzbDrone.Core.Test/Download/DownloadClientTests/DelugeTests/DelugeFixture.cs b/src/NzbDrone.Core.Test/Download/DownloadClientTests/DelugeTests/DelugeFixture.cs index 0b090782e..52728b3da 100644 --- a/src/NzbDrone.Core.Test/Download/DownloadClientTests/DelugeTests/DelugeFixture.cs +++ b/src/NzbDrone.Core.Test/Download/DownloadClientTests/DelugeTests/DelugeFixture.cs @@ -1,13 +1,13 @@ using System; -using System.Linq; using System.Collections.Generic; +using System.Linq; using FluentAssertions; using Moq; using NUnit.Framework; using NzbDrone.Common.Http; -using NzbDrone.Core.MediaFiles.TorrentInfo; using NzbDrone.Core.Download; using NzbDrone.Core.Download.Clients.Deluge; +using NzbDrone.Core.MediaFiles.TorrentInfo; using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.Download.DownloadClientTests.DelugeTests diff --git a/src/NzbDrone.Core.Test/Download/DownloadClientTests/DownloadClientFixtureBase.cs b/src/NzbDrone.Core.Test/Download/DownloadClientTests/DownloadClientFixtureBase.cs index 0f048b75d..81803566a 100644 --- a/src/NzbDrone.Core.Test/Download/DownloadClientTests/DownloadClientFixtureBase.cs +++ b/src/NzbDrone.Core.Test/Download/DownloadClientTests/DownloadClientFixtureBase.cs @@ -1,18 +1,18 @@ using System; using System.Collections.Generic; +using FluentAssertions; using Moq; using NUnit.Framework; -using FluentAssertions; -using NzbDrone.Common.Http; -using NzbDrone.Core.IndexerSearch.Definitions; -using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Parser.Model; -using NzbDrone.Core.Parser; -using NzbDrone.Core.Tv; -using NzbDrone.Core.Download; -using NzbDrone.Core.Configuration; -using NzbDrone.Core.RemotePathMappings; using NzbDrone.Common.Disk; +using NzbDrone.Common.Http; +using NzbDrone.Core.Configuration; +using NzbDrone.Core.Download; +using NzbDrone.Core.IndexerSearch.Definitions; +using NzbDrone.Core.Parser; +using NzbDrone.Core.Parser.Model; +using NzbDrone.Core.RemotePathMappings; +using NzbDrone.Core.Test.Framework; +using NzbDrone.Core.Tv; namespace NzbDrone.Core.Test.Download.DownloadClientTests { @@ -73,6 +73,7 @@ protected void VerifyQueued(DownloadClientItem downloadClientItem) { VerifyIdentifiable(downloadClientItem); downloadClientItem.RemainingSize.Should().NotBe(0); + //downloadClientItem.RemainingTime.Should().NotBe(TimeSpan.Zero); //downloadClientItem.OutputPath.Should().NotBeNullOrEmpty(); downloadClientItem.Status.Should().Be(DownloadItemStatus.Queued); @@ -83,6 +84,7 @@ protected void VerifyPaused(DownloadClientItem downloadClientItem) VerifyIdentifiable(downloadClientItem); downloadClientItem.RemainingSize.Should().NotBe(0); + //downloadClientItem.RemainingTime.Should().NotBe(TimeSpan.Zero); //downloadClientItem.OutputPath.Should().NotBeNullOrEmpty(); downloadClientItem.Status.Should().Be(DownloadItemStatus.Paused); @@ -93,6 +95,7 @@ protected void VerifyDownloading(DownloadClientItem downloadClientItem) VerifyIdentifiable(downloadClientItem); downloadClientItem.RemainingSize.Should().NotBe(0); + //downloadClientItem.RemainingTime.Should().NotBe(TimeSpan.Zero); //downloadClientItem.OutputPath.Should().NotBeNullOrEmpty(); downloadClientItem.Status.Should().Be(DownloadItemStatus.Downloading); @@ -114,6 +117,7 @@ protected void VerifyCompleted(DownloadClientItem downloadClientItem) downloadClientItem.Title.Should().NotBeNullOrEmpty(); downloadClientItem.RemainingSize.Should().Be(0); downloadClientItem.RemainingTime.Should().Be(TimeSpan.Zero); + //downloadClientItem.OutputPath.Should().NotBeNullOrEmpty(); downloadClientItem.Status.Should().Be(DownloadItemStatus.Completed); } diff --git a/src/NzbDrone.Core.Test/Download/DownloadClientTests/DownloadStationTests/TorrentDownloadStationFixture.cs b/src/NzbDrone.Core.Test/Download/DownloadClientTests/DownloadStationTests/TorrentDownloadStationFixture.cs index ce5cc13bd..609f4a97b 100644 --- a/src/NzbDrone.Core.Test/Download/DownloadClientTests/DownloadStationTests/TorrentDownloadStationFixture.cs +++ b/src/NzbDrone.Core.Test/Download/DownloadClientTests/DownloadStationTests/TorrentDownloadStationFixture.cs @@ -67,13 +67,13 @@ public void Setup() { Detail = new Dictionary { - { "destination","shared/folder" }, + { "destination", "shared/folder" }, { "uri", DownloadURL } }, Transfer = new Dictionary { - { "size_downloaded", "0"}, - { "size_uploaded", "0"}, + { "size_downloaded", "0" }, + { "size_uploaded", "0" }, { "speed_download", "0" } } } @@ -91,13 +91,13 @@ public void Setup() { Detail = new Dictionary { - { "destination","shared/folder" }, + { "destination", "shared/folder" }, { "uri", DownloadURL } }, Transfer = new Dictionary { - { "size_downloaded", "1000"}, - { "size_uploaded", "100"}, + { "size_downloaded", "1000" }, + { "size_uploaded", "100" }, { "speed_download", "0" } }, } @@ -115,13 +115,13 @@ public void Setup() { Detail = new Dictionary { - { "destination","shared/folder" }, + { "destination", "shared/folder" }, { "uri", DownloadURL } }, Transfer = new Dictionary { - { "size_downloaded", "1000"}, - { "size_uploaded", "100"}, + { "size_downloaded", "1000" }, + { "size_uploaded", "100" }, { "speed_download", "0" } } } @@ -139,13 +139,13 @@ public void Setup() { Detail = new Dictionary { - { "destination","shared/folder" }, + { "destination", "shared/folder" }, { "uri", DownloadURL } }, Transfer = new Dictionary { - { "size_downloaded", "100"}, - { "size_uploaded", "10"}, + { "size_downloaded", "100" }, + { "size_uploaded", "10" }, { "speed_download", "50" } } } @@ -163,13 +163,13 @@ public void Setup() { Detail = new Dictionary { - { "destination","shared/folder" }, + { "destination", "shared/folder" }, { "uri", DownloadURL } }, Transfer = new Dictionary { - { "size_downloaded", "10"}, - { "size_uploaded", "1"}, + { "size_downloaded", "10" }, + { "size_uploaded", "1" }, { "speed_download", "0" } } } @@ -187,13 +187,13 @@ public void Setup() { Detail = new Dictionary { - { "destination","shared/folder" }, + { "destination", "shared/folder" }, { "uri", DownloadURL } }, Transfer = new Dictionary { - { "size_downloaded", "1000"}, - { "size_uploaded", "100"}, + { "size_downloaded", "1000" }, + { "size_uploaded", "100" }, { "speed_download", "0" } } } @@ -211,13 +211,13 @@ public void Setup() { Detail = new Dictionary { - { "destination","shared/folder" }, + { "destination", "shared/folder" }, { "uri", DownloadURL } }, Transfer = new Dictionary { - { "size_downloaded", "1000"}, - { "size_uploaded", "100"}, + { "size_downloaded", "1000" }, + { "size_uploaded", "100" }, { "speed_download", "0" } } } @@ -235,13 +235,13 @@ public void Setup() { Detail = new Dictionary { - { "destination","shared/folder" }, + { "destination", "shared/folder" }, { "uri", DownloadURL } }, Transfer = new Dictionary { - { "size_downloaded", "1000"}, - { "size_uploaded", "100"}, + { "size_downloaded", "1000" }, + { "size_uploaded", "100" }, { "speed_download", "0" } } } @@ -259,13 +259,13 @@ public void Setup() { Detail = new Dictionary { - { "destination","shared/folder" }, + { "destination", "shared/folder" }, { "uri", DownloadURL } }, Transfer = new Dictionary { - { "size_downloaded", "1000"}, - { "size_uploaded", "100"}, + { "size_downloaded", "1000" }, + { "size_uploaded", "100" }, { "speed_download", "0" } } } diff --git a/src/NzbDrone.Core.Test/Download/DownloadClientTests/DownloadStationTests/UsenetDownloadStationFixture.cs b/src/NzbDrone.Core.Test/Download/DownloadClientTests/DownloadStationTests/UsenetDownloadStationFixture.cs index 9c934f9ad..f7e618bb0 100644 --- a/src/NzbDrone.Core.Test/Download/DownloadClientTests/DownloadStationTests/UsenetDownloadStationFixture.cs +++ b/src/NzbDrone.Core.Test/Download/DownloadClientTests/DownloadStationTests/UsenetDownloadStationFixture.cs @@ -10,9 +10,9 @@ using NzbDrone.Core.Download.Clients.DownloadStation; using NzbDrone.Core.Download.Clients.DownloadStation.Proxies; using NzbDrone.Core.MediaFiles.TorrentInfo; +using NzbDrone.Core.Organizer; using NzbDrone.Core.Parser.Model; using NzbDrone.Test.Common; -using NzbDrone.Core.Organizer; namespace NzbDrone.Core.Test.Download.DownloadClientTests.DownloadStationTests { @@ -65,12 +65,12 @@ public void Setup() { Detail = new Dictionary { - { "destination","shared/folder" }, + { "destination", "shared/folder" }, { "uri", FileNameBuilder.CleanFileName(_remoteEpisode.Release.Title) + ".nzb" } }, Transfer = new Dictionary { - { "size_downloaded", "0"}, + { "size_downloaded", "0" }, { "speed_download", "0" } } } @@ -88,12 +88,12 @@ public void Setup() { Detail = new Dictionary { - { "destination","shared/folder" }, + { "destination", "shared/folder" }, { "uri", FileNameBuilder.CleanFileName(_remoteEpisode.Release.Title) + ".nzb" } }, Transfer = new Dictionary { - { "size_downloaded", "1000"}, + { "size_downloaded", "1000" }, { "speed_download", "0" } }, } @@ -111,12 +111,12 @@ public void Setup() { Detail = new Dictionary { - { "destination","shared/folder" }, + { "destination", "shared/folder" }, { "uri", FileNameBuilder.CleanFileName(_remoteEpisode.Release.Title) + ".nzb" } }, Transfer = new Dictionary { - { "size_downloaded", "1000"}, + { "size_downloaded", "1000" }, { "speed_download", "0" } } } @@ -134,12 +134,12 @@ public void Setup() { Detail = new Dictionary { - { "destination","shared/folder" }, + { "destination", "shared/folder" }, { "uri", FileNameBuilder.CleanFileName(_remoteEpisode.Release.Title) + ".nzb" } }, Transfer = new Dictionary { - { "size_downloaded", "100"}, + { "size_downloaded", "100" }, { "speed_download", "50" } } } @@ -157,12 +157,12 @@ public void Setup() { Detail = new Dictionary { - { "destination","shared/folder" }, + { "destination", "shared/folder" }, { "uri", FileNameBuilder.CleanFileName(_remoteEpisode.Release.Title) + ".nzb" } }, Transfer = new Dictionary { - { "size_downloaded", "10"}, + { "size_downloaded", "10" }, { "speed_download", "0" } } } @@ -236,7 +236,6 @@ protected void GivenSuccessfulDownload() .Setup(s => s.Get(It.IsAny())) .Returns(r => new HttpResponse(r, new HttpHeader(), new byte[1000])); */ - Mocker.GetMock() .Setup(s => s.AddTaskFromData(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) .Callback(PrepareClientToReturnQueuedItem); diff --git a/src/NzbDrone.Core.Test/Download/DownloadClientTests/HadoukenTests/HadoukenFixture.cs b/src/NzbDrone.Core.Test/Download/DownloadClientTests/HadoukenTests/HadoukenFixture.cs index 5762fdf08..b7650b4cb 100644 --- a/src/NzbDrone.Core.Test/Download/DownloadClientTests/HadoukenTests/HadoukenFixture.cs +++ b/src/NzbDrone.Core.Test/Download/DownloadClientTests/HadoukenTests/HadoukenFixture.cs @@ -1,14 +1,14 @@ -using Moq; +using System; +using System.Collections.Generic; +using System.Linq; +using FluentAssertions; +using Moq; using NUnit.Framework; using NzbDrone.Common.Http; using NzbDrone.Core.Download; using NzbDrone.Core.Download.Clients.Hadouken; using NzbDrone.Core.Download.Clients.Hadouken.Models; using NzbDrone.Core.MediaFiles.TorrentInfo; -using System; -using System.Collections.Generic; -using System.Linq; -using FluentAssertions; using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.Download.DownloadClientTests.HadoukenTests @@ -81,7 +81,7 @@ public void Setup() }; Mocker.GetMock() - .Setup(s => s.GetHashFromTorrentFile(It.IsAny())) + .Setup(s => s.GetHashFromTorrentFile(It.IsAny())) .Returns("CBC2F069FE8BB2F544EAE707D75BCD3DE9DCF951"); Mocker.GetMock() @@ -210,7 +210,7 @@ public void Download_should_return_unique_id() [Test] public void should_return_status_with_outputdirs() { - var configItems = new Dictionary(); + var configItems = new Dictionary(); configItems.Add("bittorrent.defaultSavePath", @"C:\Downloads\Downloading\deluge".AsOsAgnostic()); diff --git a/src/NzbDrone.Core.Test/Download/DownloadClientTests/NzbVortexTests/NzbVortexFixture.cs b/src/NzbDrone.Core.Test/Download/DownloadClientTests/NzbVortexTests/NzbVortexFixture.cs index c18bb7b94..f33aa5e0c 100644 --- a/src/NzbDrone.Core.Test/Download/DownloadClientTests/NzbVortexTests/NzbVortexFixture.cs +++ b/src/NzbDrone.Core.Test/Download/DownloadClientTests/NzbVortexTests/NzbVortexFixture.cs @@ -1,18 +1,18 @@ using System; -using System.Linq; using System.Collections.Generic; +using System.Linq; using FluentAssertions; using Moq; using NUnit.Framework; -using NzbDrone.Core.Download; -using NzbDrone.Core.Download.Clients.Nzbget; -using NzbDrone.Test.Common; -using NzbDrone.Core.RemotePathMappings; using NzbDrone.Common.Disk; using NzbDrone.Common.Extensions; +using NzbDrone.Core.Download; using NzbDrone.Core.Download.Clients; +using NzbDrone.Core.Download.Clients.Nzbget; using NzbDrone.Core.Download.Clients.NzbVortex; using NzbDrone.Core.Download.Clients.NzbVortex.Responses; +using NzbDrone.Core.RemotePathMappings; +using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.Download.DownloadClientTests.NzbVortexTests { diff --git a/src/NzbDrone.Core.Test/Download/DownloadClientTests/NzbgetTests/NzbgetFixture.cs b/src/NzbDrone.Core.Test/Download/DownloadClientTests/NzbgetTests/NzbgetFixture.cs index be865de9f..3e2ef2c54 100644 --- a/src/NzbDrone.Core.Test/Download/DownloadClientTests/NzbgetTests/NzbgetFixture.cs +++ b/src/NzbDrone.Core.Test/Download/DownloadClientTests/NzbgetTests/NzbgetFixture.cs @@ -1,16 +1,16 @@ using System; -using System.Linq; using System.Collections.Generic; +using System.Linq; using FizzWare.NBuilder; using FluentAssertions; using Moq; using NUnit.Framework; +using NzbDrone.Common.Disk; using NzbDrone.Core.Download; using NzbDrone.Core.Download.Clients.Nzbget; -using NzbDrone.Test.Common; -using NzbDrone.Core.RemotePathMappings; -using NzbDrone.Common.Disk; using NzbDrone.Core.Exceptions; +using NzbDrone.Core.RemotePathMappings; +using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.Download.DownloadClientTests.NzbgetTests { @@ -89,7 +89,6 @@ public void Setup() DownloadRate = 7000000 }); - Mocker.GetMock() .Setup(v => v.GetVersion(It.IsAny())) .Returns("14.0"); diff --git a/src/NzbDrone.Core.Test/Download/DownloadClientTests/QBittorrentTests/QBittorrentFixture.cs b/src/NzbDrone.Core.Test/Download/DownloadClientTests/QBittorrentTests/QBittorrentFixture.cs index b2bb94a3b..88359e456 100644 --- a/src/NzbDrone.Core.Test/Download/DownloadClientTests/QBittorrentTests/QBittorrentFixture.cs +++ b/src/NzbDrone.Core.Test/Download/DownloadClientTests/QBittorrentTests/QBittorrentFixture.cs @@ -7,12 +7,12 @@ using NUnit.Framework; using NzbDrone.Common.Disk; using NzbDrone.Common.Http; -using NzbDrone.Core.MediaFiles.TorrentInfo; using NzbDrone.Core.Download; -using NzbDrone.Core.Download.Clients.QBittorrent; -using NzbDrone.Test.Common; -using NzbDrone.Core.Exceptions; using NzbDrone.Core.Download.Clients; +using NzbDrone.Core.Download.Clients.QBittorrent; +using NzbDrone.Core.Exceptions; +using NzbDrone.Core.MediaFiles.TorrentInfo; +using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.Download.DownloadClientTests.QBittorrentTests { @@ -33,12 +33,12 @@ public void Setup() }; Mocker.GetMock() - .Setup(s => s.GetHashFromTorrentFile(It.IsAny())) + .Setup(s => s.GetHashFromTorrentFile(It.IsAny())) .Returns("CBC2F069FE8BB2F544EAE707D75BCD3DE9DCF951"); Mocker.GetMock() .Setup(s => s.Get(It.IsAny())) - .Returns(r => new HttpResponse(r, new HttpHeader(), new Byte[0])); + .Returns(r => new HttpResponse(r, new HttpHeader(), new byte[0])); Mocker.GetMock() .Setup(s => s.GetConfig(It.IsAny())) @@ -56,7 +56,7 @@ protected void GivenRedirectToMagnet() Mocker.GetMock() .Setup(s => s.Get(It.IsAny())) - .Returns(r => new HttpResponse(r, httpHeader, new Byte[0], System.Net.HttpStatusCode.SeeOther)); + .Returns(r => new HttpResponse(r, httpHeader, new byte[0], System.Net.HttpStatusCode.SeeOther)); } protected void GivenRedirectToTorrent() @@ -66,7 +66,7 @@ protected void GivenRedirectToTorrent() Mocker.GetMock() .Setup(s => s.Get(It.Is(h => h.Url.FullUri == _downloadUrl))) - .Returns(r => new HttpResponse(r, httpHeader, new Byte[0], System.Net.HttpStatusCode.Found)); + .Returns(r => new HttpResponse(r, httpHeader, new byte[0], System.Net.HttpStatusCode.Found)); } protected void GivenFailedDownload() @@ -124,7 +124,9 @@ protected void GivenGlobalSeedLimits(float maxRatio, int maxSeedingTime = -1, QB protected virtual void GivenTorrents(List torrents) { if (torrents == null) + { torrents = new List(); + } Mocker.GetMock() .Setup(s => s.GetTorrents(It.IsAny())) @@ -603,8 +605,10 @@ public void should_not_be_removable_and_should_not_allow_move_files_if_max_ratio protected virtual QBittorrentTorrent GivenCompletedTorrent( string state = "pausedUP", - float ratio = 0.1f, float ratioLimit = -2, - int seedingTime = 1, int seedingTimeLimit = -2) + float ratio = 0.1f, + float ratioLimit = -2, + int seedingTime = 1, + int seedingTimeLimit = -2) { var torrent = new QBittorrentTorrent { @@ -689,7 +693,6 @@ public void should_not_be_removable_if_overridden_max_ratio_not_reached_and_paus item.CanMoveFiles.Should().BeFalse(); } - [Test] public void should_not_be_removable_and_should_not_allow_move_files_if_max_seedingtime_reached_and_not_paused() { @@ -754,7 +757,7 @@ public void should_not_fetch_details_twice() var item = Subject.GetItems().Single(); item.CanBeRemoved.Should().BeFalse(); item.CanMoveFiles.Should().BeFalse(); - + var item2 = Subject.GetItems().Single(); Mocker.GetMock() @@ -821,7 +824,6 @@ public void should_handle_eta_biginteger() var json = "{ \"eta\": 18446744073709335000 }"; var torrent = Newtonsoft.Json.JsonConvert.DeserializeObject(json); torrent.Eta.ToString().Should().Be("18446744073709335000"); - } [Test] diff --git a/src/NzbDrone.Core.Test/Download/DownloadClientTests/RTorrentTests/RTorrentFixture.cs b/src/NzbDrone.Core.Test/Download/DownloadClientTests/RTorrentTests/RTorrentFixture.cs index 1f5a2713e..257d1cdca 100644 --- a/src/NzbDrone.Core.Test/Download/DownloadClientTests/RTorrentTests/RTorrentFixture.cs +++ b/src/NzbDrone.Core.Test/Download/DownloadClientTests/RTorrentTests/RTorrentFixture.cs @@ -1,11 +1,11 @@ -using System.Linq; using System.Collections.Generic; +using System.Linq; using FluentAssertions; using Moq; using NUnit.Framework; -using NzbDrone.Core.MediaFiles.TorrentInfo; using NzbDrone.Core.Download; using NzbDrone.Core.Download.Clients.RTorrent; +using NzbDrone.Core.MediaFiles.TorrentInfo; namespace NzbDrone.Core.Test.Download.DownloadClientTests.RTorrentTests { @@ -61,7 +61,6 @@ protected void GivenSuccessfulDownload() .Setup(s => s.AddTorrentFromFile(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) .Callback(PrepareClientToReturnCompletedItem); - Mocker.GetMock() .Setup(s => s.HasHashTorrent(It.IsAny(), It.IsAny())) .Returns(true); diff --git a/src/NzbDrone.Core.Test/Download/DownloadClientTests/SabnzbdTests/JsonConvertersTests/SabnzbdQueueTimeConverterFixture.cs b/src/NzbDrone.Core.Test/Download/DownloadClientTests/SabnzbdTests/JsonConvertersTests/SabnzbdQueueTimeConverterFixture.cs index 1b9dc4bb6..0532dbff9 100644 --- a/src/NzbDrone.Core.Test/Download/DownloadClientTests/SabnzbdTests/JsonConvertersTests/SabnzbdQueueTimeConverterFixture.cs +++ b/src/NzbDrone.Core.Test/Download/DownloadClientTests/SabnzbdTests/JsonConvertersTests/SabnzbdQueueTimeConverterFixture.cs @@ -15,9 +15,9 @@ public class SabnzbdQueueTimeConverterFixture [TestCase("0:1:59", 119)] [TestCase("0:59:59", 3599)] [TestCase("1:0:0", 3600)] - [TestCase("1:0:0:1", 24 * 3600 + 1)] - [TestCase("40:12:14", 40 * 3600 + 12 * 60 + 14)] - [TestCase("1:16:12:14", 40 * 3600 + 12 * 60 + 14)] + [TestCase("1:0:0:1", (24 * 3600) + 1)] + [TestCase("40:12:14", (40 * 3600) + (12 * 60) + 14)] + [TestCase("1:16:12:14", (40 * 3600) + (12 * 60) + 14)] public void valid_time_formats_should_be_parsed_correctly(string time, int expectedSeconds) { var thing = string.Format(QUERY, time); diff --git a/src/NzbDrone.Core.Test/Download/DownloadClientTests/SabnzbdTests/SabnzbdFixture.cs b/src/NzbDrone.Core.Test/Download/DownloadClientTests/SabnzbdTests/SabnzbdFixture.cs index a3f699478..5761ab84d 100644 --- a/src/NzbDrone.Core.Test/Download/DownloadClientTests/SabnzbdTests/SabnzbdFixture.cs +++ b/src/NzbDrone.Core.Test/Download/DownloadClientTests/SabnzbdTests/SabnzbdFixture.cs @@ -1,19 +1,19 @@ using System; -using System.Linq; using System.Collections.Generic; using System.IO; +using System.Linq; using FizzWare.NBuilder; using FluentAssertions; using Moq; using NUnit.Framework; +using NzbDrone.Common.Disk; using NzbDrone.Core.Download; using NzbDrone.Core.Download.Clients.Sabnzbd; using NzbDrone.Core.Download.Clients.Sabnzbd.Responses; -using NzbDrone.Core.Tv; -using NzbDrone.Test.Common; using NzbDrone.Core.RemotePathMappings; -using NzbDrone.Common.Disk; +using NzbDrone.Core.Tv; using NzbDrone.Core.Validation; +using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.Download.DownloadClientTests.SabnzbdTests { @@ -171,7 +171,9 @@ protected virtual void GivenQueue(SabnzbdQueue queue) protected virtual void GivenHistory(SabnzbdHistory history) { if (history == null) + { history = new SabnzbdHistory() { Items = new List() }; + } Mocker.GetMock() .Setup(s => s.GetHistory(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) diff --git a/src/NzbDrone.Core.Test/Download/DownloadClientTests/TransmissionTests/TransmissionFixture.cs b/src/NzbDrone.Core.Test/Download/DownloadClientTests/TransmissionTests/TransmissionFixture.cs index 1cea84d48..497ee8ca3 100644 --- a/src/NzbDrone.Core.Test/Download/DownloadClientTests/TransmissionTests/TransmissionFixture.cs +++ b/src/NzbDrone.Core.Test/Download/DownloadClientTests/TransmissionTests/TransmissionFixture.cs @@ -284,7 +284,6 @@ public void should_ignore_negative_eta(int eta) item.RemainingTime.Should().NotHaveValue(); } - [Test] public void should_not_be_removable_and_should_not_allow_move_files_if_max_ratio_reached_and_not_stopped() { @@ -340,7 +339,6 @@ public void should_not_be_removable_if_overridden_max_ratio_not_reached_and_paus item.CanMoveFiles.Should().BeFalse(); } - [Test] public void should_not_be_removable_and_should_not_allow_move_files_if_max_idletime_reached_and_not_paused() { diff --git a/src/NzbDrone.Core.Test/Download/DownloadClientTests/TransmissionTests/TransmissionFixtureBase.cs b/src/NzbDrone.Core.Test/Download/DownloadClientTests/TransmissionTests/TransmissionFixtureBase.cs index 5dded73ea..a90b787f9 100644 --- a/src/NzbDrone.Core.Test/Download/DownloadClientTests/TransmissionTests/TransmissionFixtureBase.cs +++ b/src/NzbDrone.Core.Test/Download/DownloadClientTests/TransmissionTests/TransmissionFixtureBase.cs @@ -110,7 +110,6 @@ public void Setup() Mocker.GetMock() .Setup(v => v.GetConfig(It.IsAny())) .Returns(() => Json.Deserialize(_transmissionConfigItems.ToJson())); - } protected void GivenTvCategory() @@ -144,7 +143,7 @@ protected void GivenSuccessfulDownload() .Setup(s => s.AddTorrentFromData(It.IsAny(), It.IsAny(), It.IsAny())) .Callback(PrepareClientToReturnQueuedItem); } - + protected virtual void GivenTorrents(List torrents) { if (torrents == null) @@ -159,7 +158,7 @@ protected virtual void GivenTorrents(List torrents) protected void PrepareClientToReturnQueuedItem() { - GivenTorrents(new List + GivenTorrents(new List { _queued }); @@ -167,7 +166,7 @@ protected void PrepareClientToReturnQueuedItem() protected void PrepareClientToReturnDownloadingItem() { - GivenTorrents(new List + GivenTorrents(new List { _downloading }); @@ -175,7 +174,7 @@ protected void PrepareClientToReturnDownloadingItem() protected void PrepareClientToReturnFailedItem() { - GivenTorrents(new List + GivenTorrents(new List { _failed }); @@ -184,7 +183,10 @@ protected void PrepareClientToReturnFailedItem() protected void PrepareClientToReturnCompletedItem(bool stopped = false, double ratio = 0.9, int seedingTime = 60, double? ratioLimit = null, int? idleLimit = null) { if (stopped) + { _completed.Status = TransmissionTorrentStatus.Stopped; + } + _completed.UploadedEver = (int)(_completed.DownloadedEver * ratio); _completed.SecondsSeeding = seedingTime * 60; @@ -214,7 +216,6 @@ protected void PrepareClientToReturnCompletedItem(bool stopped = false, double r } } - GivenTorrents(new List { _completed @@ -244,4 +245,4 @@ protected void GivenGlobalSeedLimits(double? ratioLimit = null, int? idleLimit = } } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core.Test/Download/DownloadClientTests/UTorrentTests/UTorrentFixture.cs b/src/NzbDrone.Core.Test/Download/DownloadClientTests/UTorrentTests/UTorrentFixture.cs index e66ce42dc..97ce9ed0a 100644 --- a/src/NzbDrone.Core.Test/Download/DownloadClientTests/UTorrentTests/UTorrentFixture.cs +++ b/src/NzbDrone.Core.Test/Download/DownloadClientTests/UTorrentTests/UTorrentFixture.cs @@ -1,13 +1,13 @@ using System; -using System.Linq; using System.Collections.Generic; +using System.Linq; using FluentAssertions; using Moq; using NUnit.Framework; using NzbDrone.Common.Http; -using NzbDrone.Core.MediaFiles.TorrentInfo; using NzbDrone.Core.Download; using NzbDrone.Core.Download.Clients.UTorrent; +using NzbDrone.Core.MediaFiles.TorrentInfo; using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.Download.DownloadClientTests.UTorrentTests diff --git a/src/NzbDrone.Core.Test/Download/DownloadClientTests/VuzeTests/VuzeFixture.cs b/src/NzbDrone.Core.Test/Download/DownloadClientTests/VuzeTests/VuzeFixture.cs index 91f9e701a..eb354b1bb 100644 --- a/src/NzbDrone.Core.Test/Download/DownloadClientTests/VuzeTests/VuzeFixture.cs +++ b/src/NzbDrone.Core.Test/Download/DownloadClientTests/VuzeTests/VuzeFixture.cs @@ -341,6 +341,5 @@ public void should_have_correct_output_directory_for_singlefile_torrents() items.Should().HaveCount(1); items.First().OutputPath.Should().Be(@"C:\Downloads\" + fileName); } - } } diff --git a/src/NzbDrone.Core.Test/Download/DownloadServiceFixture.cs b/src/NzbDrone.Core.Test/Download/DownloadServiceFixture.cs index 2a5b2f15a..42319d4a2 100644 --- a/src/NzbDrone.Core.Test/Download/DownloadServiceFixture.cs +++ b/src/NzbDrone.Core.Test/Download/DownloadServiceFixture.cs @@ -117,7 +117,8 @@ public void Download_report_should_trigger_indexer_backoff_on_indexer_error() { var mock = WithUsenetClient(); mock.Setup(s => s.Download(It.IsAny())) - .Callback(v => { + .Callback(v => + { throw new ReleaseDownloadException(v.Release, "Error", new WebException()); }); @@ -136,7 +137,8 @@ public void Download_report_should_trigger_indexer_backoff_on_http429_with_long_ var mock = WithUsenetClient(); mock.Setup(s => s.Download(It.IsAny())) - .Callback(v => { + .Callback(v => + { throw new ReleaseDownloadException(v.Release, "Error", new TooManyRequestsException(request, response)); }); @@ -185,7 +187,8 @@ public void Download_report_should_not_trigger_indexer_backoff_on_indexer_404_er { var mock = WithUsenetClient(); mock.Setup(s => s.Download(It.IsAny())) - .Callback(v => { + .Callback(v => + { throw new ReleaseUnavailableException(v.Release, "Error", new WebException()); }); diff --git a/src/NzbDrone.Core.Test/Download/FailedDownloadServiceTests/ProcessFailedFixture.cs b/src/NzbDrone.Core.Test/Download/FailedDownloadServiceTests/ProcessFailedFixture.cs index 29e9c998e..65e37537a 100644 --- a/src/NzbDrone.Core.Test/Download/FailedDownloadServiceTests/ProcessFailedFixture.cs +++ b/src/NzbDrone.Core.Test/Download/FailedDownloadServiceTests/ProcessFailedFixture.cs @@ -44,11 +44,9 @@ public void Setup() .With(c => c.RemoteEpisode = remoteEpisode) .Build(); - Mocker.GetMock() .Setup(s => s.Find(_trackedDownload.DownloadItem.DownloadId, EpisodeHistoryEventType.Grabbed)) .Returns(_grabHistory); - } [Test] @@ -92,7 +90,6 @@ private void AssertDownloadNotFailed() _trackedDownload.State.Should().NotBe(TrackedDownloadState.Failed); } - private void AssertDownloadFailed() { Mocker.GetMock() diff --git a/src/NzbDrone.Core.Test/Download/FailedDownloadServiceTests/ProcessFixture.cs b/src/NzbDrone.Core.Test/Download/FailedDownloadServiceTests/ProcessFixture.cs index dc63d7b7e..83847a5dc 100644 --- a/src/NzbDrone.Core.Test/Download/FailedDownloadServiceTests/ProcessFixture.cs +++ b/src/NzbDrone.Core.Test/Download/FailedDownloadServiceTests/ProcessFixture.cs @@ -44,11 +44,9 @@ public void Setup() .With(c => c.RemoteEpisode = remoteEpisode) .Build(); - Mocker.GetMock() .Setup(s => s.Find(_trackedDownload.DownloadItem.DownloadId, EpisodeHistoryEventType.Grabbed)) .Returns(_grabHistory); - } private void GivenNoGrabbedHistory() @@ -98,7 +96,6 @@ private void AssertDownloadNotFailed() _trackedDownload.State.Should().NotBe(TrackedDownloadState.Failed); } - private void AssertDownloadFailed() { Mocker.GetMock() diff --git a/src/NzbDrone.Core.Test/Download/Pending/PendingReleaseServiceTests/AddFixture.cs b/src/NzbDrone.Core.Test/Download/Pending/PendingReleaseServiceTests/AddFixture.cs index 4070862dd..d81407a84 100644 --- a/src/NzbDrone.Core.Test/Download/Pending/PendingReleaseServiceTests/AddFixture.cs +++ b/src/NzbDrone.Core.Test/Download/Pending/PendingReleaseServiceTests/AddFixture.cs @@ -58,7 +58,7 @@ public void Setup() _parsedEpisodeInfo.Quality = new QualityModel(Quality.HDTV720p); _remoteEpisode = new RemoteEpisode(); - _remoteEpisode.Episodes = new List{ _episode }; + _remoteEpisode.Episodes = new List { _episode }; _remoteEpisode.Series = _series; _remoteEpisode.ParsedEpisodeInfo = _parsedEpisodeInfo; _remoteEpisode.Release = _release; @@ -85,7 +85,7 @@ public void Setup() Mocker.GetMock() .Setup(s => s.GetEpisodes(It.IsAny(), _series, true, null)) - .Returns(new List {_episode}); + .Returns(new List { _episode }); Mocker.GetMock() .Setup(s => s.PrioritizeDecisions(It.IsAny>())) @@ -98,7 +98,6 @@ private void GivenHeldRelease(string title, string indexer, DateTime publishDate release.Indexer = indexer; release.PublishDate = publishDate; - var heldReleases = Builder.CreateListOfSize(1) .All() .With(h => h.SeriesId = _series.Id) diff --git a/src/NzbDrone.Core.Test/Download/Pending/PendingReleaseServiceTests/PendingReleaseServiceFixture.cs b/src/NzbDrone.Core.Test/Download/Pending/PendingReleaseServiceTests/PendingReleaseServiceFixture.cs index 8ff0f0ea0..5933db2e4 100644 --- a/src/NzbDrone.Core.Test/Download/Pending/PendingReleaseServiceTests/PendingReleaseServiceFixture.cs +++ b/src/NzbDrone.Core.Test/Download/Pending/PendingReleaseServiceTests/PendingReleaseServiceFixture.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using FluentAssertions; using Moq; using NUnit.Framework; using NzbDrone.Core.DecisionEngine; @@ -7,7 +8,6 @@ using NzbDrone.Core.Indexers; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Test.Framework; -using FluentAssertions; namespace NzbDrone.Core.Test.Download.Pending.PendingReleaseServiceTests { @@ -18,9 +18,10 @@ private void GivenPendingRelease() { Mocker.GetMock() .Setup(v => v.All()) - .Returns(new List { + .Returns(new List + { new PendingRelease { Release = new ReleaseInfo { IndexerId = 1 } } - }); + }); } [Test] diff --git a/src/NzbDrone.Core.Test/Download/Pending/PendingReleaseServiceTests/RemoveGrabbedFixture.cs b/src/NzbDrone.Core.Test/Download/Pending/PendingReleaseServiceTests/RemoveGrabbedFixture.cs index e71537612..81faea376 100644 --- a/src/NzbDrone.Core.Test/Download/Pending/PendingReleaseServiceTests/RemoveGrabbedFixture.cs +++ b/src/NzbDrone.Core.Test/Download/Pending/PendingReleaseServiceTests/RemoveGrabbedFixture.cs @@ -60,7 +60,7 @@ public void Setup() .Build(); _remoteEpisode = new RemoteEpisode(); - _remoteEpisode.Episodes = new List{ _episode }; + _remoteEpisode.Episodes = new List { _episode }; _remoteEpisode.Series = _series; _remoteEpisode.ParsedEpisodeInfo = _parsedEpisodeInfo; _remoteEpisode.Release = _release; @@ -91,7 +91,7 @@ public void Setup() Mocker.GetMock() .Setup(s => s.GetEpisodes(It.IsAny(), _series, true, null)) - .Returns(new List {_episode}); + .Returns(new List { _episode }); Mocker.GetMock() .Setup(s => s.PrioritizeDecisions(It.IsAny>())) diff --git a/src/NzbDrone.Core.Test/Download/Pending/PendingReleaseServiceTests/RemovePendingFixture.cs b/src/NzbDrone.Core.Test/Download/Pending/PendingReleaseServiceTests/RemovePendingFixture.cs index d0629ad40..3a8714bbe 100644 --- a/src/NzbDrone.Core.Test/Download/Pending/PendingReleaseServiceTests/RemovePendingFixture.cs +++ b/src/NzbDrone.Core.Test/Download/Pending/PendingReleaseServiceTests/RemovePendingFixture.cs @@ -32,7 +32,7 @@ public void Setup() Mocker.GetMock() .Setup(s => s.All()) - .Returns( _pending); + .Returns(_pending); Mocker.GetMock() .Setup(s => s.GetSeries(It.IsAny())) @@ -48,7 +48,7 @@ public void Setup() Mocker.GetMock() .Setup(s => s.GetEpisodes(It.IsAny(), It.IsAny(), It.IsAny(), null)) - .Returns(new List{ _episode }); + .Returns(new List { _episode }); } private void AddPending(int id, int seasonNumber, int[] episodes) @@ -148,5 +148,4 @@ private void AssertRemoved(params int[] ids) Mocker.GetMock().Verify(c => c.DeleteMany(It.Is>(s => s.SequenceEqual(ids)))); } } - } diff --git a/src/NzbDrone.Core.Test/Download/Pending/PendingReleaseServiceTests/RemoveRejectedFixture.cs b/src/NzbDrone.Core.Test/Download/Pending/PendingReleaseServiceTests/RemoveRejectedFixture.cs index ed1d9ef2c..1711497dc 100644 --- a/src/NzbDrone.Core.Test/Download/Pending/PendingReleaseServiceTests/RemoveRejectedFixture.cs +++ b/src/NzbDrone.Core.Test/Download/Pending/PendingReleaseServiceTests/RemoveRejectedFixture.cs @@ -58,7 +58,7 @@ public void Setup() _parsedEpisodeInfo.Quality = new QualityModel(Quality.HDTV720p); _remoteEpisode = new RemoteEpisode(); - _remoteEpisode.Episodes = new List{ _episode }; + _remoteEpisode.Episodes = new List { _episode }; _remoteEpisode.Series = _series; _remoteEpisode.ParsedEpisodeInfo = _parsedEpisodeInfo; _remoteEpisode.Release = _release; @@ -83,7 +83,7 @@ public void Setup() Mocker.GetMock() .Setup(s => s.GetEpisodes(It.IsAny(), _series, true, null)) - .Returns(new List {_episode}); + .Returns(new List { _episode }); Mocker.GetMock() .Setup(s => s.PrioritizeDecisions(It.IsAny>())) @@ -96,7 +96,6 @@ private void GivenHeldRelease(string title, string indexer, DateTime publishDate release.Indexer = indexer; release.PublishDate = publishDate; - var heldReleases = Builder.CreateListOfSize(1) .All() .With(h => h.SeriesId = _series.Id) diff --git a/src/NzbDrone.Core.Test/Download/TrackedDownloads/TrackedDownloadAlreadyImportedFixture.cs b/src/NzbDrone.Core.Test/Download/TrackedDownloads/TrackedDownloadAlreadyImportedFixture.cs index 3993a5a53..03e756d5a 100644 --- a/src/NzbDrone.Core.Test/Download/TrackedDownloads/TrackedDownloadAlreadyImportedFixture.cs +++ b/src/NzbDrone.Core.Test/Download/TrackedDownloads/TrackedDownloadAlreadyImportedFixture.cs @@ -1,13 +1,13 @@ using System.Collections.Generic; +using FizzWare.NBuilder; using FluentAssertions; using NUnit.Framework; +using NzbDrone.Core.Download; using NzbDrone.Core.Download.TrackedDownloads; using NzbDrone.Core.History; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Tv; -using FizzWare.NBuilder; -using NzbDrone.Core.Download; namespace NzbDrone.Core.Test.Download.TrackedDownloads { @@ -52,8 +52,7 @@ public void GivenHistoryForEpisode(Episode episode, params EpisodeHistoryEventTy Builder.CreateNew() .With(h => h.EpisodeId = episode.Id) .With(h => h.EventType = eventType) - .Build() - ); + .Build()); } } diff --git a/src/NzbDrone.Core.Test/Download/TrackedDownloads/TrackedDownloadServiceFixture.cs b/src/NzbDrone.Core.Test/Download/TrackedDownloads/TrackedDownloadServiceFixture.cs index 7097ccb72..f3fb5ef20 100644 --- a/src/NzbDrone.Core.Test/Download/TrackedDownloads/TrackedDownloadServiceFixture.cs +++ b/src/NzbDrone.Core.Test/Download/TrackedDownloads/TrackedDownloadServiceFixture.cs @@ -1,16 +1,16 @@ using System.Collections.Generic; +using System.Linq; using FluentAssertions; using Moq; using NUnit.Framework; using NzbDrone.Core.Download; using NzbDrone.Core.Download.TrackedDownloads; using NzbDrone.Core.History; +using NzbDrone.Core.Indexers; using NzbDrone.Core.Parser; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Tv; -using NzbDrone.Core.Indexers; -using System.Linq; using NzbDrone.Core.Tv.Events; namespace NzbDrone.Core.Test.Download.TrackedDownloads @@ -22,13 +22,15 @@ private void GivenDownloadHistory() { Mocker.GetMock() .Setup(s => s.FindByDownloadId(It.Is(sr => sr == "35238"))) - .Returns(new List(){ - new EpisodeHistory(){ + .Returns(new List() + { + new EpisodeHistory() + { DownloadId = "35238", SourceTitle = "TV Series S01", SeriesId = 5, EpisodeId = 4 - } + } }); } @@ -93,20 +95,22 @@ public void should_parse_as_special_when_source_title_parsing_fails() { SeriesTitle = "TV Series", SeasonNumber = 0, - EpisodeNumbers = new []{ 1 } + EpisodeNumbers = new[] { 1 } }, MappedSeasonNumber = 0 }; Mocker.GetMock() .Setup(s => s.FindByDownloadId(It.Is(sr => sr == "35238"))) - .Returns(new List(){ - new EpisodeHistory(){ + .Returns(new List() + { + new EpisodeHistory() + { DownloadId = "35238", SourceTitle = "TV Series Special", SeriesId = 5, EpisodeId = 4 - } + } }); Mocker.GetMock() @@ -172,7 +176,6 @@ public void should_unmap_tracked_download_if_episode_deleted() .Setup(s => s.FindByDownloadId(It.IsAny())) .Returns(new List()); - var client = new DownloadClientDefinition() { Id = 1, @@ -232,7 +235,6 @@ public void should_not_throw_when_processing_deleted_episodes() .Setup(s => s.FindByDownloadId(It.IsAny())) .Returns(new List()); - var client = new DownloadClientDefinition() { Id = 1, @@ -292,7 +294,6 @@ public void should_not_throw_when_processing_deleted_series() .Setup(s => s.FindByDownloadId(It.IsAny())) .Returns(new List()); - var client = new DownloadClientDefinition() { Id = 1, diff --git a/src/NzbDrone.Core.Test/Extras/ExtraServiceFixture.cs b/src/NzbDrone.Core.Test/Extras/ExtraServiceFixture.cs index c8dafafd6..5d14f384b 100644 --- a/src/NzbDrone.Core.Test/Extras/ExtraServiceFixture.cs +++ b/src/NzbDrone.Core.Test/Extras/ExtraServiceFixture.cs @@ -46,7 +46,6 @@ public void Setup() .Build() .ToList(); - _episodeFile = Builder.CreateNew() .With(f => f.Path = Path.Combine(_series.Path, "Season 1", "Series Title - S01E01.mkv").AsOsAgnostic()) .With(f => f.RelativePath = @"Season 1\Series Title - S01E01.mkv".AsOsAgnostic()) @@ -70,7 +69,8 @@ public void Setup() _otherExtraService.Setup(s => s.CanImportFile(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) .Returns(true); - Mocker.SetConstant>(new[] { + Mocker.SetConstant>(new[] + { _subtitleService.Object, _otherExtraService.Object }); @@ -132,7 +132,8 @@ public void should_not_pass_file_if_import_disabled() var nfofile = Path.Combine(_episodeFolder, "Series.Title.S01E01.nfo").AsOsAgnostic(); - var files = new List { + var files = new List + { _localEpisode.Path, nfofile }; @@ -154,7 +155,8 @@ public void should_not_pass_unwanted_file(string filePath) var nfofile = Path.Combine(_episodeFolder, filePath).AsOsAgnostic(); - var files = new List { + var files = new List + { _localEpisode.Path, nfofile }; @@ -172,7 +174,8 @@ public void should_pass_subtitle_file_to_subtitle_service() { var subtitleFile = Path.Combine(_episodeFolder, "Series.Title.S01E01.en.srt").AsOsAgnostic(); - var files = new List { + var files = new List + { _localEpisode.Path, subtitleFile }; @@ -190,7 +193,8 @@ public void should_pass_nfo_file_to_other_service() { var nfofile = Path.Combine(_episodeFolder, "Series.Title.S01E01.nfo").AsOsAgnostic(); - var files = new List { + var files = new List + { _localEpisode.Path, nfofile }; @@ -210,10 +214,11 @@ public void should_search_subtitles_when_importing_from_job_folder() var subtitleFile = Path.Combine(_episodeFolder, "Series.Title.S01E01.en.srt").AsOsAgnostic(); - var files = new List { - _localEpisode.Path, - subtitleFile - }; + var files = new List + { + _localEpisode.Path, + subtitleFile + }; WithExistingFiles(files); @@ -230,10 +235,11 @@ public void should_not_search_subtitles_when_not_importing_from_job_folder() var subtitleFile = Path.Combine(_episodeFolder, "Series.Title.S01E01.en.srt").AsOsAgnostic(); - var files = new List { - _localEpisode.Path, - subtitleFile - }; + var files = new List + { + _localEpisode.Path, + subtitleFile + }; WithExistingFiles(files); diff --git a/src/NzbDrone.Core.Test/Extras/Others/OtherExtraServiceFixture.cs b/src/NzbDrone.Core.Test/Extras/Others/OtherExtraServiceFixture.cs index fc0fc8fb2..a79dd0f1f 100644 --- a/src/NzbDrone.Core.Test/Extras/Others/OtherExtraServiceFixture.cs +++ b/src/NzbDrone.Core.Test/Extras/Others/OtherExtraServiceFixture.cs @@ -1,8 +1,8 @@ using System.Collections.Generic; using System.IO; using System.Linq; -using FluentAssertions; using FizzWare.NBuilder; +using FluentAssertions; using NUnit.Framework; using NzbDrone.Common.Extensions; using NzbDrone.Core.Extras.Others; @@ -40,7 +40,6 @@ public void Setup() .Build() .ToList(); - _episodeFile = Builder.CreateNew() .With(f => f.Path = Path.Combine(_series.Path, "Season 1", "Series Title - S01E01.mkv").AsOsAgnostic()) .With(f => f.RelativePath = @"Season 1\Series Title - S01E01.mkv") @@ -69,7 +68,7 @@ public void Setup() public void should_import_matching_file(string filePath, string expectedOutputPath) { var files = new List { Path.Combine(_episodeFolder, filePath).AsOsAgnostic() }; - + var results = Subject.ImportFiles(_localEpisode, _episodeFile, files, true).ToList(); results.Count().Should().Be(1); diff --git a/src/NzbDrone.Core.Test/Extras/Subtitles/SubtitleServiceFixture.cs b/src/NzbDrone.Core.Test/Extras/Subtitles/SubtitleServiceFixture.cs index 2809005a3..bf788b38f 100644 --- a/src/NzbDrone.Core.Test/Extras/Subtitles/SubtitleServiceFixture.cs +++ b/src/NzbDrone.Core.Test/Extras/Subtitles/SubtitleServiceFixture.cs @@ -1,9 +1,11 @@ using System.Collections.Generic; using System.IO; using System.Linq; -using FluentAssertions; using FizzWare.NBuilder; +using FluentAssertions; +using Moq; using NUnit.Framework; +using NzbDrone.Common.Disk; using NzbDrone.Common.Extensions; using NzbDrone.Core.Extras.Subtitles; using NzbDrone.Core.MediaFiles; @@ -12,8 +14,6 @@ using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Tv; using NzbDrone.Test.Common; -using Moq; -using NzbDrone.Common.Disk; namespace NzbDrone.Core.Test.Extras.Subtitles { @@ -43,7 +43,6 @@ public void Setup() .Build() .ToList(); - _episodeFile = Builder.CreateNew() .With(f => f.Path = Path.Combine(_series.Path, "Season 1", "Series Title - S01E01.mkv").AsOsAgnostic()) .With(f => f.RelativePath = @"Season 1\Series Title - S01E01.mkv".AsOsAgnostic()) @@ -90,7 +89,7 @@ public void should_not_import_non_subtitle_file(string filePath) public void should_import_matching_subtitle_file(string filePath, string expectedOutputPath) { var files = new List { Path.Combine(_episodeFolder, filePath).AsOsAgnostic() }; - + var results = Subject.ImportFiles(_localEpisode, _episodeFile, files, true).ToList(); results.Count().Should().Be(1); @@ -126,7 +125,7 @@ public void should_import_multiple_subtitle_files_per_language() results[i].RelativePath.AsOsAgnostic().PathEquals(Path.Combine("Season 1", expectedOutputs[i]).AsOsAgnostic()).Should().Be(true); } } - + [Test] public void should_import_multiple_subtitle_files_per_language_with_tags() { diff --git a/src/NzbDrone.Core.Test/FluentTest.cs b/src/NzbDrone.Core.Test/FluentTest.cs index 752dff23f..a17f142e3 100644 --- a/src/NzbDrone.Core.Test/FluentTest.cs +++ b/src/NzbDrone.Core.Test/FluentTest.cs @@ -9,7 +9,7 @@ namespace NzbDrone.Core.Test { [TestFixture] - + public class FluentTest : CoreTest { [TestCase(null, "def", "def")] @@ -87,11 +87,7 @@ public void ToBestDateTime_Before_Yesterday() [Test] public void MaxOrDefault_should_return_zero_when_collection_is_empty() { - - - - - var result = (new List()).MaxOrDefault(); + var result = new List().MaxOrDefault(); //Resolve result.Should().Be(0); @@ -100,10 +96,8 @@ public void MaxOrDefault_should_return_zero_when_collection_is_empty() [Test] public void MaxOrDefault_should_return_max_when_collection_is_not_empty() { - var list = new List { 6, 4, 5, 3, 8, 10 }; - var result = list.MaxOrDefault(); //Resolve @@ -113,10 +107,8 @@ public void MaxOrDefault_should_return_max_when_collection_is_not_empty() [Test] public void MaxOrDefault_should_return_zero_when_collection_is_null() { - List list = null; - var result = list.MaxOrDefault(); //Resolve @@ -126,10 +118,8 @@ public void MaxOrDefault_should_return_zero_when_collection_is_null() [Test] public void Truncate_should_truncate_strings_to_max_specified_number_of_bytes() { - var str = ReadAllText("Files/LongOverview.txt"); - var resultString = str.Truncate(1000); //Resolve @@ -140,10 +130,8 @@ public void Truncate_should_truncate_strings_to_max_specified_number_of_bytes() [Test] public void Truncate_should_not_truncate_string_shorter_than_max_bytes() { - var str = "Hello World"; - var resultString = str.Truncate(1000); //Resolve @@ -154,11 +142,7 @@ public void Truncate_should_not_truncate_string_shorter_than_max_bytes() [Test] public void MinOrDefault_should_return_zero_when_collection_is_empty() { - - - - - var result = (new List()).MinOrDefault(); + var result = new List().MinOrDefault(); //Resolve result.Should().Be(0); @@ -167,10 +151,8 @@ public void MinOrDefault_should_return_zero_when_collection_is_empty() [Test] public void MinOrDefault_should_return_min_when_collection_is_not_empty() { - var list = new List { 6, 4, 5, 3, 8, 10 }; - var result = list.MinOrDefault(); //Resolve @@ -180,22 +162,19 @@ public void MinOrDefault_should_return_min_when_collection_is_not_empty() [Test] public void MinOrDefault_should_return_zero_when_collection_is_null() { - List list = null; - var result = list.MinOrDefault(); //Resolve result.Should().Be(0); } - - [TestCase(100,100,100)] - [TestCase(110,100,100)] - [TestCase(199,100,100)] - [TestCase(1000,100,1000)] - [TestCase(0,100,0)] + [TestCase(100, 100, 100)] + [TestCase(110, 100, 100)] + [TestCase(199, 100, 100)] + [TestCase(1000, 100, 1000)] + [TestCase(0, 100, 0)] public void round_to_level(long number, int level, int result) { number.Round(level).Should().Be(result); diff --git a/src/NzbDrone.Core.Test/Framework/CoreTest.cs b/src/NzbDrone.Core.Test/Framework/CoreTest.cs index ba4f3a03c..d97c666ff 100644 --- a/src/NzbDrone.Core.Test/Framework/CoreTest.cs +++ b/src/NzbDrone.Core.Test/Framework/CoreTest.cs @@ -5,11 +5,11 @@ using NzbDrone.Common.EnvironmentInfo; using NzbDrone.Common.Http; using NzbDrone.Common.Http.Dispatchers; -using NzbDrone.Common.TPL; -using NzbDrone.Test.Common; using NzbDrone.Common.Http.Proxy; -using NzbDrone.Core.Http; +using NzbDrone.Common.TPL; using NzbDrone.Core.Configuration; +using NzbDrone.Core.Http; +using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.Framework { @@ -18,8 +18,8 @@ public abstract class CoreTest : TestBase protected void UseRealHttp() { Mocker.GetMock().SetupGet(c => c.Version).Returns(new Version("3.0.0")); - Mocker.GetMock().SetupGet(c=>c.Version).Returns("1.0.0"); - Mocker.GetMock().SetupGet(c=>c.Name).Returns("TestOS"); + Mocker.GetMock().SetupGet(c => c.Version).Returns("1.0.0"); + Mocker.GetMock().SetupGet(c => c.Name).Returns("TestOS"); Mocker.SetConstant(new HttpProxySettingsProvider(Mocker.Resolve())); Mocker.SetConstant(new ManagedWebProxyFactory(Mocker.Resolve())); @@ -29,7 +29,8 @@ protected void UseRealHttp() } } - public abstract class CoreTest : CoreTest where TSubject : class + public abstract class CoreTest : CoreTest + where TSubject : class { private TSubject _subject; @@ -50,7 +51,6 @@ protected TSubject Subject return _subject; } - } } } diff --git a/src/NzbDrone.Core.Test/Framework/DbTest.cs b/src/NzbDrone.Core.Test/Framework/DbTest.cs index 773c8bb21..f548c2c41 100644 --- a/src/NzbDrone.Core.Test/Framework/DbTest.cs +++ b/src/NzbDrone.Core.Test/Framework/DbTest.cs @@ -41,7 +41,6 @@ protected TSubject Subject return _subject; } - } } @@ -57,7 +56,9 @@ protected ITestDatabase Db get { if (_db == null) + { throw new InvalidOperationException("Test object database doesn't exists. Make sure you call WithRealDb() if you intend to use an actual database."); + } return _db; } @@ -78,6 +79,7 @@ protected virtual ITestDatabase WithTestDb(MigrationContext migrationContext) Mocker.SetConstant(mainDb); break; } + case MigrationType.Log: { var logDb = new LogDatabase(database); @@ -85,6 +87,7 @@ protected virtual ITestDatabase WithTestDb(MigrationContext migrationContext) Mocker.SetConstant(logDb); break; } + default: { throw new ArgumentException("Invalid MigrationType"); @@ -100,6 +103,7 @@ protected virtual void SetupLogging() { Mocker.SetConstant(NullLoggerProvider.Instance); } + protected void SetupContainer() { WithTempAsAppPath(); @@ -125,11 +129,11 @@ public void TearDown() GC.Collect(); GC.WaitForPendingFinalizers(); SQLiteConnection.ClearAllPools(); - + if (TestFolderInfo != null) { DeleteTempFolder(TestFolderInfo.AppDataFolder); } } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core.Test/Framework/DirectDataMapper.cs b/src/NzbDrone.Core.Test/Framework/DirectDataMapper.cs index a75daf167..15ae1a4a9 100644 --- a/src/NzbDrone.Core.Test/Framework/DirectDataMapper.cs +++ b/src/NzbDrone.Core.Test/Framework/DirectDataMapper.cs @@ -11,7 +11,8 @@ namespace NzbDrone.Core.Test.Framework public interface IDirectDataMapper { List> Query(string sql); - List Query(string sql) where T : new(); + List Query(string sql) + where T : new(); T QueryScalar(string sql); } @@ -56,7 +57,8 @@ public List> Query(string sql) return dataTable.Rows.Cast().Select(MapToDictionary).ToList(); } - public List Query(string sql) where T : new() + public List Query(string sql) + where T : new() { var dataTable = GetDataTable(sql); @@ -94,7 +96,8 @@ protected Dictionary MapToDictionary(DataRow dataRow) return item; } - protected T MapToObject(DataRow dataRow) where T : new() + protected T MapToObject(DataRow dataRow) + where T : new() { var item = new T(); @@ -117,7 +120,6 @@ protected Dictionary MapToDictionary(DataRow dataRow) object value = MapValue(dataRow, i, propertyType); - propertyInfo.SetValue(item, value, null); } diff --git a/src/NzbDrone.Core.Test/Framework/MigrationTest.cs b/src/NzbDrone.Core.Test/Framework/MigrationTest.cs index 417c59673..21c1e78d7 100644 --- a/src/NzbDrone.Core.Test/Framework/MigrationTest.cs +++ b/src/NzbDrone.Core.Test/Framework/MigrationTest.cs @@ -8,7 +8,8 @@ namespace NzbDrone.Core.Test.Framework { [Category("DbMigrationTest")] [Category("DbTest")] - public abstract class MigrationTest : DbTest where TMigration : NzbDroneMigrationBase + public abstract class MigrationTest : DbTest + where TMigration : NzbDroneMigrationBase { protected long MigrationVersion { @@ -46,4 +47,4 @@ public override void SetupDb() SetupContainer(); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core.Test/Framework/NBuilderExtensions.cs b/src/NzbDrone.Core.Test/Framework/NBuilderExtensions.cs index 338e73302..9394ba74b 100644 --- a/src/NzbDrone.Core.Test/Framework/NBuilderExtensions.cs +++ b/src/NzbDrone.Core.Test/Framework/NBuilderExtensions.cs @@ -7,20 +7,22 @@ namespace NzbDrone.Core.Test.Framework { public static class NBuilderExtensions { - public static T BuildNew(this ISingleObjectBuilder builder) where T : ModelBase, new() + public static T BuildNew(this ISingleObjectBuilder builder) + where T : ModelBase, new() { return builder.With(c => c.Id = 0).Build(); } - public static List BuildList(this IListBuilder builder) where T : ModelBase, new() + public static List BuildList(this IListBuilder builder) + where T : ModelBase, new() { return builder.Build().ToList(); } - public static List BuildListOfNew(this IListBuilder builder) where T : ModelBase, new() + public static List BuildListOfNew(this IListBuilder builder) + where T : ModelBase, new() { return BuildList(builder.All().With(c => c.Id = 0)); } - } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core.Test/Framework/TestDatabase.cs b/src/NzbDrone.Core.Test/Framework/TestDatabase.cs index 30fb2be0c..4215a66c6 100644 --- a/src/NzbDrone.Core.Test/Framework/TestDatabase.cs +++ b/src/NzbDrone.Core.Test/Framework/TestDatabase.cs @@ -8,12 +8,18 @@ namespace NzbDrone.Core.Test.Framework { public interface ITestDatabase { - void InsertMany(IEnumerable items) where T : ModelBase, new(); - T Insert(T item) where T : ModelBase, new(); - List All() where T : ModelBase, new(); - T Single() where T : ModelBase, new(); - void Update(T childModel) where T : ModelBase, new(); - void Delete(T childModel) where T : ModelBase, new(); + void InsertMany(IEnumerable items) + where T : ModelBase, new(); + T Insert(T item) + where T : ModelBase, new(); + List All() + where T : ModelBase, new(); + T Single() + where T : ModelBase, new(); + void Update(T childModel) + where T : ModelBase, new(); + void Delete(T childModel) + where T : ModelBase, new(); IDirectDataMapper GetDirectDataMapper(); } @@ -28,32 +34,38 @@ public TestDatabase(IDatabase dbConnection) _dbConnection = dbConnection; } - public void InsertMany(IEnumerable items) where T : ModelBase, new() + public void InsertMany(IEnumerable items) + where T : ModelBase, new() { new BasicRepository(_dbConnection, _eventAggregator).InsertMany(items.ToList()); } - public T Insert(T item) where T : ModelBase, new() + public T Insert(T item) + where T : ModelBase, new() { return new BasicRepository(_dbConnection, _eventAggregator).Insert(item); } - public List All() where T : ModelBase, new() + public List All() + where T : ModelBase, new() { return new BasicRepository(_dbConnection, _eventAggregator).All().ToList(); } - public T Single() where T : ModelBase, new() + public T Single() + where T : ModelBase, new() { return All().SingleOrDefault(); } - public void Update(T childModel) where T : ModelBase, new() + public void Update(T childModel) + where T : ModelBase, new() { new BasicRepository(_dbConnection, _eventAggregator).Update(childModel); } - public void Delete(T childModel) where T : ModelBase, new() + public void Delete(T childModel) + where T : ModelBase, new() { new BasicRepository(_dbConnection, _eventAggregator).Delete(childModel); } diff --git a/src/NzbDrone.Core.Test/HealthCheck/Checks/DeleteBadMediaCovers.cs b/src/NzbDrone.Core.Test/HealthCheck/Checks/DeleteBadMediaCovers.cs index 5b454ae3c..62c058a56 100644 --- a/src/NzbDrone.Core.Test/HealthCheck/Checks/DeleteBadMediaCovers.cs +++ b/src/NzbDrone.Core.Test/HealthCheck/Checks/DeleteBadMediaCovers.cs @@ -30,7 +30,6 @@ public void Setup() .With(c => c.Path = "C:\\TV\\".AsOsAgnostic()) .Build().ToList(); - _metadata = Builder.CreateListOfSize(1) .Build().ToList(); @@ -38,16 +37,13 @@ public void Setup() .Setup(c => c.GetAllSeries()) .Returns(_series); - Mocker.GetMock() .Setup(c => c.GetFilesBySeries(_series.First().Id)) .Returns(_metadata); - Mocker.GetMock().SetupGet(c => c.CleanupMetadataImages).Returns(true); } - [Test] public void should_not_process_non_image_files() { @@ -57,7 +53,6 @@ public void should_not_process_non_image_files() Subject.Clean(); Mocker.GetMock().Verify(c => c.OpenReadStream(It.IsAny()), Times.Never()); - } [Test] @@ -70,8 +65,6 @@ public void should_not_process_images_before_tvdb_switch() Mocker.GetMock().Verify(c => c.OpenReadStream(It.IsAny()), Times.Never()); } - - [Test] public void should_not_run_if_flag_is_false() { @@ -85,7 +78,6 @@ public void should_not_run_if_flag_is_false() AssertImageWasNotRemoved(); } - [Test] public void should_set_clean_flag_to_false() { @@ -96,11 +88,9 @@ public void should_set_clean_flag_to_false() Mocker.GetMock().VerifySet(c => c.CleanupMetadataImages = false, Times.Once()); } - [Test] public void should_delete_html_images() { - var imagePath = "C:\\TV\\Season\\image.jpg".AsOsAgnostic(); _metadata.First().LastUpdated = new DateTime(2014, 12, 29); _metadata.First().RelativePath = "Season\\image.jpg".AsOsAgnostic(); @@ -110,19 +100,15 @@ public void should_delete_html_images() .Setup(c => c.OpenReadStream(imagePath)) .Returns(new FileStream(GetTestPath("Files/html_image.jpg"), FileMode.Open, FileAccess.Read)); - Subject.Clean(); - Mocker.GetMock().Verify(c => c.DeleteFile(imagePath), Times.Once()); Mocker.GetMock().Verify(c => c.Delete(_metadata.First().Id), Times.Once()); } - [Test] public void should_delete_empty_images() { - var imagePath = "C:\\TV\\Season\\image.jpg".AsOsAgnostic(); _metadata.First().LastUpdated = new DateTime(2014, 12, 29); _metadata.First().Type = MetadataType.SeasonImage; @@ -132,18 +118,15 @@ public void should_delete_empty_images() .Setup(c => c.OpenReadStream(imagePath)) .Returns(new FileStream(GetTestPath("Files/emptyfile.txt"), FileMode.Open, FileAccess.Read)); - Subject.Clean(); Mocker.GetMock().Verify(c => c.DeleteFile(imagePath), Times.Once()); Mocker.GetMock().Verify(c => c.Delete(_metadata.First().Id), Times.Once()); } - [Test] public void should_not_delete_non_html_files() { - var imagePath = "C:\\TV\\Season\\image.jpg".AsOsAgnostic(); _metadata.First().LastUpdated = new DateTime(2014, 12, 29); _metadata.First().RelativePath = "Season\\image.jpg".AsOsAgnostic(); @@ -152,7 +135,6 @@ public void should_not_delete_non_html_files() .Setup(c => c.OpenReadStream(imagePath)) .Returns(new FileStream(GetTestPath("Files/Queue.txt"), FileMode.Open, FileAccess.Read)); - Subject.Clean(); AssertImageWasNotRemoved(); } diff --git a/src/NzbDrone.Core.Test/HealthCheck/Checks/DownloadClientCheckFixture.cs b/src/NzbDrone.Core.Test/HealthCheck/Checks/DownloadClientCheckFixture.cs index 665038e32..b8ceaaba3 100644 --- a/src/NzbDrone.Core.Test/HealthCheck/Checks/DownloadClientCheckFixture.cs +++ b/src/NzbDrone.Core.Test/HealthCheck/Checks/DownloadClientCheckFixture.cs @@ -25,7 +25,7 @@ public void should_return_warning_when_download_client_has_not_been_configured() public void should_return_error_when_download_client_throws() { var downloadClient = Mocker.GetMock(); - downloadClient.Setup(s => s.Definition).Returns(new DownloadClientDefinition{Name = "Test"}); + downloadClient.Setup(s => s.Definition).Returns(new DownloadClientDefinition { Name = "Test" }); downloadClient.Setup(s => s.GetItems()) .Throws(); diff --git a/src/NzbDrone.Core.Test/HealthCheck/Checks/ImportListStatusCheckFixture.cs b/src/NzbDrone.Core.Test/HealthCheck/Checks/ImportListStatusCheckFixture.cs index 3316eb007..3adf09078 100644 --- a/src/NzbDrone.Core.Test/HealthCheck/Checks/ImportListStatusCheckFixture.cs +++ b/src/NzbDrone.Core.Test/HealthCheck/Checks/ImportListStatusCheckFixture.cs @@ -81,4 +81,4 @@ public void should_return_warning_if_few_import_lists_unavailable() Subject.Check().ShouldBeWarning(); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core.Test/HealthCheck/Checks/ImportMechanismCheckFixture.cs b/src/NzbDrone.Core.Test/HealthCheck/Checks/ImportMechanismCheckFixture.cs index e2704fc47..cb66bdf31 100644 --- a/src/NzbDrone.Core.Test/HealthCheck/Checks/ImportMechanismCheckFixture.cs +++ b/src/NzbDrone.Core.Test/HealthCheck/Checks/ImportMechanismCheckFixture.cs @@ -34,10 +34,10 @@ public void should_return_warning_when_completed_download_handling_not_configure public void should_return_warning_when_both_completeddownloadhandling_and_dronefactory_are_not_configured() { GivenCompletedDownloadHandling(false); - + Subject.Check().ShouldBeWarning(); } - + [Test] public void should_return_ok_when_no_issues_found() { diff --git a/src/NzbDrone.Core.Test/HealthCheck/Checks/IndexerJackettAllCheckFixture.cs b/src/NzbDrone.Core.Test/HealthCheck/Checks/IndexerJackettAllCheckFixture.cs index 6fcccdf1e..f1bd98a63 100644 --- a/src/NzbDrone.Core.Test/HealthCheck/Checks/IndexerJackettAllCheckFixture.cs +++ b/src/NzbDrone.Core.Test/HealthCheck/Checks/IndexerJackettAllCheckFixture.cs @@ -20,7 +20,6 @@ public void SetUp() Mocker.GetMock() .Setup(v => v.All()) .Returns(_indexers); - } private void GivenIndexer(string baseUrl, string apiPath) diff --git a/src/NzbDrone.Core.Test/HealthCheck/Checks/IndexerLongTermStatusCheckFixture.cs b/src/NzbDrone.Core.Test/HealthCheck/Checks/IndexerLongTermStatusCheckFixture.cs index f945a8d27..18a457747 100644 --- a/src/NzbDrone.Core.Test/HealthCheck/Checks/IndexerLongTermStatusCheckFixture.cs +++ b/src/NzbDrone.Core.Test/HealthCheck/Checks/IndexerLongTermStatusCheckFixture.cs @@ -49,7 +49,6 @@ private Mock GivenIndexer(int id, double backoffHours, double failureH return mockIndexer; } - [Test] public void should_not_return_error_when_no_indexers() { diff --git a/src/NzbDrone.Core.Test/HealthCheck/Checks/IndexerSearchCheckFixture.cs b/src/NzbDrone.Core.Test/HealthCheck/Checks/IndexerSearchCheckFixture.cs index 988d5d8e9..030d8a8db 100644 --- a/src/NzbDrone.Core.Test/HealthCheck/Checks/IndexerSearchCheckFixture.cs +++ b/src/NzbDrone.Core.Test/HealthCheck/Checks/IndexerSearchCheckFixture.cs @@ -114,7 +114,6 @@ public void should_return_warning_if_search_is_supported_but_disabled() Subject.Check().ShouldBeWarning(); } - [Test] public void should_return_filter_warning_if_search_is_enabled_but_filtered() { diff --git a/src/NzbDrone.Core.Test/HealthCheck/Checks/IndexerStatusCheckFixture.cs b/src/NzbDrone.Core.Test/HealthCheck/Checks/IndexerStatusCheckFixture.cs index c2e645858..15df6d175 100644 --- a/src/NzbDrone.Core.Test/HealthCheck/Checks/IndexerStatusCheckFixture.cs +++ b/src/NzbDrone.Core.Test/HealthCheck/Checks/IndexerStatusCheckFixture.cs @@ -49,7 +49,6 @@ private Mock GivenIndexer(int id, double backoffHours, double failureH return mockIndexer; } - [Test] public void should_not_return_error_when_no_indexers() { diff --git a/src/NzbDrone.Core.Test/HealthCheck/Checks/RemovedSeriesCheckFixture.cs b/src/NzbDrone.Core.Test/HealthCheck/Checks/RemovedSeriesCheckFixture.cs index 958c6ae5a..da8be0d0e 100644 --- a/src/NzbDrone.Core.Test/HealthCheck/Checks/RemovedSeriesCheckFixture.cs +++ b/src/NzbDrone.Core.Test/HealthCheck/Checks/RemovedSeriesCheckFixture.cs @@ -40,8 +40,6 @@ private void GivenSeries(int amount, int deleted) .Returns(series); } - - [Test] public void should_return_error_if_series_no_longer_on_tvdb() { diff --git a/src/NzbDrone.Core.Test/HealthCheck/Checks/SystemTimeCheckFixture.cs b/src/NzbDrone.Core.Test/HealthCheck/Checks/SystemTimeCheckFixture.cs index e4084e714..238dc2a0e 100644 --- a/src/NzbDrone.Core.Test/HealthCheck/Checks/SystemTimeCheckFixture.cs +++ b/src/NzbDrone.Core.Test/HealthCheck/Checks/SystemTimeCheckFixture.cs @@ -22,7 +22,7 @@ public void Setup() private void GivenServerTime(DateTime dateTime) { - var json = new ServiceTimeResponse {DateTimeUtc = dateTime}.ToJson(); + var json = new ServiceTimeResponse { DateTimeUtc = dateTime }.ToJson(); Mocker.GetMock() .Setup(s => s.Execute(It.IsAny())) diff --git a/src/NzbDrone.Core.Test/HealthCheck/HealthCheckServiceFixture.cs b/src/NzbDrone.Core.Test/HealthCheck/HealthCheckServiceFixture.cs index 31eee2656..901070e9f 100644 --- a/src/NzbDrone.Core.Test/HealthCheck/HealthCheckServiceFixture.cs +++ b/src/NzbDrone.Core.Test/HealthCheck/HealthCheckServiceFixture.cs @@ -15,7 +15,7 @@ namespace NzbDrone.Core.Test.HealthCheck { public class HealthCheckServiceFixture : CoreTest { - FakeHealthCheck _healthCheck; + private FakeHealthCheck _healthCheck; [SetUp] public void SetUp() @@ -49,7 +49,6 @@ public void should_execute_unconditional() _healthCheck.Executed.Should().BeTrue(); } - } public class FakeEvent : IEvent diff --git a/src/NzbDrone.Core.Test/HistoryTests/HistoryRepositoryFixture.cs b/src/NzbDrone.Core.Test/HistoryTests/HistoryRepositoryFixture.cs index 89b0aea1b..746d06f8d 100644 --- a/src/NzbDrone.Core.Test/HistoryTests/HistoryRepositoryFixture.cs +++ b/src/NzbDrone.Core.Test/HistoryTests/HistoryRepositoryFixture.cs @@ -2,15 +2,14 @@ using FluentAssertions; using NUnit.Framework; using NzbDrone.Core.History; -using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Qualities; +using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.HistoryTests { [TestFixture] public class HistoryRepositoryFixture : DbTest { - [Test] public void should_read_write_dictionary() { @@ -26,7 +25,6 @@ public void should_read_write_dictionary() StoredModel.Data.Should().HaveCount(2); } - [Test] public void should_get_download_history() { @@ -49,6 +47,5 @@ public void should_get_download_history() downloadHistory.Should().HaveCount(1); } - } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core.Test/HistoryTests/HistoryServiceFixture.cs b/src/NzbDrone.Core.Test/HistoryTests/HistoryServiceFixture.cs index 0c74874df..e73cb901d 100644 --- a/src/NzbDrone.Core.Test/HistoryTests/HistoryServiceFixture.cs +++ b/src/NzbDrone.Core.Test/HistoryTests/HistoryServiceFixture.cs @@ -4,19 +4,19 @@ using FizzWare.NBuilder; using Moq; using NUnit.Framework; +using NzbDrone.Core.Download; +using NzbDrone.Core.History; +using NzbDrone.Core.Indexers; +using NzbDrone.Core.Languages; using NzbDrone.Core.MediaFiles; using NzbDrone.Core.MediaFiles.Events; using NzbDrone.Core.Parser.Model; -using NzbDrone.Core.Profiles.Qualities; -using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.History; -using NzbDrone.Core.Qualities; -using NzbDrone.Core.Test.Qualities; -using NzbDrone.Core.Download; -using NzbDrone.Core.Indexers; -using NzbDrone.Core.Tv; -using NzbDrone.Core.Languages; using NzbDrone.Core.Profiles.Languages; +using NzbDrone.Core.Profiles.Qualities; +using NzbDrone.Core.Qualities; +using NzbDrone.Core.Test.Framework; +using NzbDrone.Core.Test.Qualities; +using NzbDrone.Core.Tv; namespace NzbDrone.Core.Test.HistoryTests { @@ -37,18 +37,15 @@ public void Setup() _profileCustom = new QualityProfile { - Cutoff = Quality.WEBDL720p.Id, + Cutoff = Quality.WEBDL720p.Id, Items = QualityFixture.GetDefaultQualities(Quality.DVD), - }; - _languageProfile = new LanguageProfile { Cutoff = Language.Spanish, Languages = Languages.LanguageFixture.GetDefaultLanguages() }; - } [Test] diff --git a/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupAdditionalNamingSpecsFixture.cs b/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupAdditionalNamingSpecsFixture.cs index 52134d539..657ec78ef 100644 --- a/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupAdditionalNamingSpecsFixture.cs +++ b/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupAdditionalNamingSpecsFixture.cs @@ -34,4 +34,4 @@ public void should_not_delete_if_only_one_spec() AllStoredModels.Should().HaveCount(1); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupAdditionalUsersFixture.cs b/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupAdditionalUsersFixture.cs index 065b9d375..aea416ef1 100644 --- a/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupAdditionalUsersFixture.cs +++ b/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupAdditionalUsersFixture.cs @@ -34,4 +34,4 @@ public void should_not_delete_if_only_one_user() AllStoredModels.Should().HaveCount(1); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupOrphanedBlocklistFixture.cs b/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupOrphanedBlocklistFixture.cs index 36d7534b1..d64be6666 100644 --- a/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupOrphanedBlocklistFixture.cs +++ b/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupOrphanedBlocklistFixture.cs @@ -1,4 +1,5 @@ -using FizzWare.NBuilder; +using System.Collections.Generic; +using FizzWare.NBuilder; using FluentAssertions; using NUnit.Framework; using NzbDrone.Core.Blocklisting; @@ -6,7 +7,6 @@ using NzbDrone.Core.Qualities; using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Tv; -using System.Collections.Generic; namespace NzbDrone.Core.Test.Housekeeping.Housekeepers { diff --git a/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupOrphanedEpisodeFilesFixture.cs b/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupOrphanedEpisodeFilesFixture.cs index b09def40c..558c114ef 100644 --- a/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupOrphanedEpisodeFilesFixture.cs +++ b/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupOrphanedEpisodeFilesFixture.cs @@ -4,9 +4,9 @@ using NUnit.Framework; using NzbDrone.Core.Housekeeping.Housekeepers; using NzbDrone.Core.MediaFiles; +using NzbDrone.Core.Qualities; using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Tv; -using NzbDrone.Core.Qualities; namespace NzbDrone.Core.Test.Housekeeping.Housekeepers { diff --git a/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupOrphanedHistoryItemsFixture.cs b/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupOrphanedHistoryItemsFixture.cs index 3b9b9d8bb..f8e2df17d 100644 --- a/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupOrphanedHistoryItemsFixture.cs +++ b/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupOrphanedHistoryItemsFixture.cs @@ -107,4 +107,4 @@ public void should_not_delete_unorphaned_data_by_episode() AllStoredModels.Should().Contain(h => h.EpisodeId == _episode.Id); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupOrphanedImportListStatusFixture.cs b/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupOrphanedImportListStatusFixture.cs index e051327ee..105f15eb6 100644 --- a/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupOrphanedImportListStatusFixture.cs +++ b/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupOrphanedImportListStatusFixture.cs @@ -51,4 +51,4 @@ public void should_not_delete_unorphaned_indexerstatus() AllStoredModels.Should().Contain(h => h.ProviderId == _importList.Id); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupOrphanedIndexerStatusFixture.cs b/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupOrphanedIndexerStatusFixture.cs index c5e757188..c7418960c 100644 --- a/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupOrphanedIndexerStatusFixture.cs +++ b/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupOrphanedIndexerStatusFixture.cs @@ -51,4 +51,4 @@ public void should_not_delete_unorphaned_indexerstatus() AllStoredModels.Should().Contain(h => h.ProviderId == _indexer.Id); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupUnusedTagsFixture.cs b/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupUnusedTagsFixture.cs index 70f3582e6..cb2297989 100644 --- a/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupUnusedTagsFixture.cs +++ b/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupUnusedTagsFixture.cs @@ -2,9 +2,9 @@ using FluentAssertions; using NUnit.Framework; using NzbDrone.Core.Housekeeping.Housekeepers; -using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Tags; using NzbDrone.Core.Profiles.Releases; +using NzbDrone.Core.Tags; +using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.Housekeeping.Housekeepers { diff --git a/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/FixFutureDownloadClientStatusTimesFixture.cs b/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/FixFutureDownloadClientStatusTimesFixture.cs index 7ba5dbf22..396bc9dcd 100644 --- a/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/FixFutureDownloadClientStatusTimesFixture.cs +++ b/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/FixFutureDownloadClientStatusTimesFixture.cs @@ -35,9 +35,7 @@ public void should_set_disabled_till_when_its_too_far_in_the_future() Mocker.GetMock() .Verify(v => v.UpdateMany( It.Is>(i => i.All( - s => s.DisabledTill.Value <= DateTime.UtcNow.AddMinutes(disabledTillTime))) - ) - ); + s => s.DisabledTill.Value <= DateTime.UtcNow.AddMinutes(disabledTillTime))))); } [Test] @@ -60,9 +58,7 @@ public void should_set_initial_failure_when_its_in_the_future() Mocker.GetMock() .Verify(v => v.UpdateMany( It.Is>(i => i.All( - s => s.InitialFailure.Value <= DateTime.UtcNow)) - ) - ); + s => s.InitialFailure.Value <= DateTime.UtcNow)))); } [Test] @@ -85,9 +81,7 @@ public void should_set_most_recent_failure_when_its_in_the_future() Mocker.GetMock() .Verify(v => v.UpdateMany( It.Is>(i => i.All( - s => s.MostRecentFailure.Value <= DateTime.UtcNow)) - ) - ); + s => s.MostRecentFailure.Value <= DateTime.UtcNow)))); } [Test] @@ -109,11 +103,7 @@ public void should_not_change_statuses_when_times_are_in_the_past() Mocker.GetMock() .Verify(v => v.UpdateMany( - It.Is>(i => i.Count == 0) - ) - ); + It.Is>(i => i.Count == 0))); } - - } } diff --git a/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/FixFutureIndexerStatusTimesFixture.cs b/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/FixFutureIndexerStatusTimesFixture.cs index 56cc9cdac..9d9df469e 100644 --- a/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/FixFutureIndexerStatusTimesFixture.cs +++ b/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/FixFutureIndexerStatusTimesFixture.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using FizzWare.NBuilder; @@ -35,9 +35,7 @@ public void should_set_disabled_till_when_its_too_far_in_the_future() Mocker.GetMock() .Verify(v => v.UpdateMany( It.Is>(i => i.All( - s => s.DisabledTill.Value < DateTime.UtcNow.AddMinutes(disabledTillTime))) - ) - ); + s => s.DisabledTill.Value < DateTime.UtcNow.AddMinutes(disabledTillTime))))); } [Test] @@ -60,9 +58,7 @@ public void should_set_initial_failure_when_its_in_the_future() Mocker.GetMock() .Verify(v => v.UpdateMany( It.Is>(i => i.All( - s => s.InitialFailure.Value <= DateTime.UtcNow)) - ) - ); + s => s.InitialFailure.Value <= DateTime.UtcNow)))); } [Test] @@ -85,9 +81,7 @@ public void should_set_most_recent_failure_when_its_in_the_future() Mocker.GetMock() .Verify(v => v.UpdateMany( It.Is>(i => i.All( - s => s.MostRecentFailure.Value <= DateTime.UtcNow)) - ) - ); + s => s.MostRecentFailure.Value <= DateTime.UtcNow)))); } [Test] @@ -109,11 +103,7 @@ public void should_not_change_statuses_when_times_are_in_the_past() Mocker.GetMock() .Verify(v => v.UpdateMany( - It.Is>(i => i.Count == 0) - ) - ); + It.Is>(i => i.Count == 0))); } - - } } diff --git a/src/NzbDrone.Core.Test/Http/HttpProxySettingsProviderFixture.cs b/src/NzbDrone.Core.Test/Http/HttpProxySettingsProviderFixture.cs index 2e7759397..067149904 100644 --- a/src/NzbDrone.Core.Test/Http/HttpProxySettingsProviderFixture.cs +++ b/src/NzbDrone.Core.Test/Http/HttpProxySettingsProviderFixture.cs @@ -1,9 +1,9 @@ -using NzbDrone.Core.Http; +using FluentAssertions; using NUnit.Framework; -using FluentAssertions; -using NzbDrone.Test.Common; -using NzbDrone.Common.Http.Proxy; using NzbDrone.Common.Http; +using NzbDrone.Common.Http.Proxy; +using NzbDrone.Core.Http; +using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.Http { diff --git a/src/NzbDrone.Core.Test/Http/TorCacheHttpRequestInterceptorFixture.cs b/src/NzbDrone.Core.Test/Http/TorCacheHttpRequestInterceptorFixture.cs index 6273c7ef8..f92d8728a 100644 --- a/src/NzbDrone.Core.Test/Http/TorCacheHttpRequestInterceptorFixture.cs +++ b/src/NzbDrone.Core.Test/Http/TorCacheHttpRequestInterceptorFixture.cs @@ -1,8 +1,8 @@ -using NUnit.Framework; +using FluentAssertions; +using NUnit.Framework; using NzbDrone.Common.Http; using NzbDrone.Core.Http; using NzbDrone.Test.Common; -using FluentAssertions; namespace NzbDrone.Core.Test.Http { diff --git a/src/NzbDrone.Core.Test/ImportListTests/ImportListSyncServiceFixture.cs b/src/NzbDrone.Core.Test/ImportListTests/ImportListSyncServiceFixture.cs index ac83a2f72..2822d9838 100644 --- a/src/NzbDrone.Core.Test/ImportListTests/ImportListSyncServiceFixture.cs +++ b/src/NzbDrone.Core.Test/ImportListTests/ImportListSyncServiceFixture.cs @@ -1,13 +1,13 @@ -using System.Linq; using System.Collections.Generic; +using System.Linq; using Moq; using NUnit.Framework; using NzbDrone.Core.ImportLists; +using NzbDrone.Core.ImportLists.Exclusions; using NzbDrone.Core.MetadataSource; -using NzbDrone.Core.Tv; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.ImportLists.Exclusions; +using NzbDrone.Core.Tv; namespace NzbDrone.Core.Test.ImportListTests { @@ -23,7 +23,7 @@ public void SetUp() Title = "Breaking Bad" }; - _importListReports = new List{importListItem1}; + _importListReports = new List { importListItem1 }; Mocker.GetMock() .Setup(v => v.Fetch()) @@ -35,7 +35,7 @@ public void SetUp() Mocker.GetMock() .Setup(v => v.Get(It.IsAny())) - .Returns(new ImportListDefinition{ ShouldMonitor = MonitorTypes.All }); + .Returns(new ImportListDefinition { ShouldMonitor = MonitorTypes.All }); Mocker.GetMock() .Setup(v => v.Fetch()) @@ -55,25 +55,27 @@ private void WithExistingSeries() { Mocker.GetMock() .Setup(v => v.FindByTvdbId(_importListReports.First().TvdbId)) - .Returns(new Series{TvdbId = _importListReports.First().TvdbId }); + .Returns(new Series { TvdbId = _importListReports.First().TvdbId }); } private void WithExcludedSeries() { Mocker.GetMock() .Setup(v => v.All()) - .Returns(new List { - new ImportListExclusion { + .Returns(new List + { + new ImportListExclusion + { TvdbId = 81189 - } - }); + } + }); } private void WithMonitorType(MonitorTypes monitor) { Mocker.GetMock() .Setup(v => v.Get(It.IsAny())) - .Returns(new ImportListDefinition{ ShouldMonitor = monitor }); + .Returns(new ImportListDefinition { ShouldMonitor = monitor }); } [Test] @@ -95,7 +97,6 @@ public void should_not_search_if_series_title_and_series_id() .Verify(v => v.SearchForNewSeries(It.IsAny()), Times.Never()); } - [Test] public void should_not_add_if_existing_series() { @@ -105,7 +106,7 @@ public void should_not_add_if_existing_series() Subject.Execute(new ImportListSyncCommand()); Mocker.GetMock() - .Verify(v => v.AddSeries(It.Is>(t=>t.Count == 0), It.IsAny())); + .Verify(v => v.AddSeries(It.Is>(t => t.Count == 0), It.IsAny())); } [TestCase(MonitorTypes.None, false)] diff --git a/src/NzbDrone.Core.Test/IndexerSearchTests/ReleaseSearchServiceFixture.cs b/src/NzbDrone.Core.Test/IndexerSearchTests/ReleaseSearchServiceFixture.cs index b64b0e612..f0eef026e 100644 --- a/src/NzbDrone.Core.Test/IndexerSearchTests/ReleaseSearchServiceFixture.cs +++ b/src/NzbDrone.Core.Test/IndexerSearchTests/ReleaseSearchServiceFixture.cs @@ -70,7 +70,7 @@ private void WithEpisode(int seasonNumber, int episodeNumber, int? sceneSeasonNu .With(v => v.EpisodeNumber, episodeNumber) .With(v => v.SceneSeasonNumber, sceneSeasonNumber) .With(v => v.SceneEpisodeNumber, sceneEpisodeNumber) - .With(v => v.AirDate = (airDate ?? $"{2000 + seasonNumber}-{(episodeNumber % 12) + 1:00}-05")) + .With(v => v.AirDate = airDate ?? $"{2000 + seasonNumber}-{(episodeNumber % 12) + 1:00}-05") .With(v => v.AirDateUtc = DateTime.ParseExact(v.AirDate, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal).ToUniversalTime()) .With(v => v.Monitored = true) .Build(); @@ -138,7 +138,8 @@ private List WatchForSearchCriteria() [Test] public void Tags_IndexerTags_SeriesNoTags_IndexerNotIncluded() { - _mockIndexer.SetupGet(s => s.Definition).Returns(new IndexerDefinition { + _mockIndexer.SetupGet(s => s.Definition).Returns(new IndexerDefinition + { Id = 1, Tags = new HashSet { 3 } }); @@ -462,7 +463,7 @@ public void season_search_for_daily_should_not_search_for_unmonitored_episodes() WithEpisode(1, 2, null, null, "2005-12-31"); WithEpisode(1, 3, null, null, "2006-01-01"); _xemSeries.SeriesType = SeriesTypes.Daily; - _xemEpisodes[0].Monitored = false; + _xemEpisodes[0].Monitored = false; var allCriteria = WatchForSearchCriteria(); diff --git a/src/NzbDrone.Core.Test/IndexerSearchTests/SeriesSearchServiceFixture.cs b/src/NzbDrone.Core.Test/IndexerSearchTests/SeriesSearchServiceFixture.cs index c1aa202c2..7e826c421 100644 --- a/src/NzbDrone.Core.Test/IndexerSearchTests/SeriesSearchServiceFixture.cs +++ b/src/NzbDrone.Core.Test/IndexerSearchTests/SeriesSearchServiceFixture.cs @@ -6,9 +6,9 @@ using NzbDrone.Core.DecisionEngine; using NzbDrone.Core.Download; using NzbDrone.Core.IndexerSearch; +using NzbDrone.Core.Messaging.Commands; using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Tv; -using NzbDrone.Core.Messaging.Commands; namespace NzbDrone.Core.Test.IndexerSearchTests { diff --git a/src/NzbDrone.Core.Test/IndexerTests/BasicRssParserFixture.cs b/src/NzbDrone.Core.Test/IndexerTests/BasicRssParserFixture.cs index ce3abe40e..b2e171a58 100644 --- a/src/NzbDrone.Core.Test/IndexerTests/BasicRssParserFixture.cs +++ b/src/NzbDrone.Core.Test/IndexerTests/BasicRssParserFixture.cs @@ -59,4 +59,4 @@ public void should_handle_relative_url() result.First().DownloadUrl.Should().Be("http://my.indexer.com/getnzb/123.nzb&i=782&r=123"); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core.Test/IndexerTests/BroadcastheNetTests/BroadcastheNetFixture.cs b/src/NzbDrone.Core.Test/IndexerTests/BroadcastheNetTests/BroadcastheNetFixture.cs index e1b43d988..acfd6ceae 100644 --- a/src/NzbDrone.Core.Test/IndexerTests/BroadcastheNetTests/BroadcastheNetFixture.cs +++ b/src/NzbDrone.Core.Test/IndexerTests/BroadcastheNetTests/BroadcastheNetFixture.cs @@ -1,4 +1,7 @@ -using Moq; +using System; +using System.Linq; +using FluentAssertions; +using Moq; using NUnit.Framework; using NzbDrone.Common.Http; using NzbDrone.Core.Indexers; @@ -6,9 +9,6 @@ using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Test.Framework; using NzbDrone.Test.Common; -using System; -using System.Linq; -using FluentAssertions; namespace NzbDrone.Core.Test.IndexerTests.BroadcastheNetTests { @@ -54,7 +54,7 @@ public void should_parse_recent_feed_from_BroadcastheNet() torrentInfo.TvdbId.Should().Be(71998); torrentInfo.TvRageId.Should().Be(4055); torrentInfo.MagnetUrl.Should().BeNullOrEmpty(); - torrentInfo.Peers.Should().Be(40+9); + torrentInfo.Peers.Should().Be(40 + 9); torrentInfo.Seeders.Should().Be(40); torrentInfo.Origin.Should().Be("Scene"); diff --git a/src/NzbDrone.Core.Test/IndexerTests/FanzubTests/FanzubFixture.cs b/src/NzbDrone.Core.Test/IndexerTests/FanzubTests/FanzubFixture.cs index ed8587e38..e807192ec 100644 --- a/src/NzbDrone.Core.Test/IndexerTests/FanzubTests/FanzubFixture.cs +++ b/src/NzbDrone.Core.Test/IndexerTests/FanzubTests/FanzubFixture.cs @@ -31,7 +31,7 @@ public void should_parse_recent_feed_from_fanzub() Mocker.GetMock() .Setup(o => o.Execute(It.Is(v => v.Method == HttpMethod.GET))) .Returns(r => new HttpResponse(r, new HttpHeader(), recentFeed)); - + var releases = Subject.FetchRecent(); releases.Should().HaveCount(3); diff --git a/src/NzbDrone.Core.Test/IndexerTests/FileListTests/FileListFixture.cs b/src/NzbDrone.Core.Test/IndexerTests/FileListTests/FileListFixture.cs index d7f5802be..cac1c00ad 100644 --- a/src/NzbDrone.Core.Test/IndexerTests/FileListTests/FileListFixture.cs +++ b/src/NzbDrone.Core.Test/IndexerTests/FileListTests/FileListFixture.cs @@ -54,4 +54,4 @@ public void should_parse_recent_feed_from_FileList() torrentInfo.Seeders.Should().Be(12); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core.Test/IndexerTests/HDBitsTests/HDBitsFixture.cs b/src/NzbDrone.Core.Test/IndexerTests/HDBitsTests/HDBitsFixture.cs index 1edc5631d..ba90d4fa9 100644 --- a/src/NzbDrone.Core.Test/IndexerTests/HDBitsTests/HDBitsFixture.cs +++ b/src/NzbDrone.Core.Test/IndexerTests/HDBitsTests/HDBitsFixture.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Linq; using System.Text; using FluentAssertions; @@ -64,8 +64,7 @@ public void should_warn_on_wrong_passkey() Mocker.GetMock() .Setup(v => v.Execute(It.IsAny())) - .Returns(r => new HttpResponse(r, new HttpHeader(), - Encoding.UTF8.GetBytes(responseJson))); + .Returns(r => new HttpResponse(r, new HttpHeader(), Encoding.UTF8.GetBytes(responseJson))); var torrents = Subject.FetchRecent(); diff --git a/src/NzbDrone.Core.Test/IndexerTests/IPTorrentsTests/IPTorrentsFixture.cs b/src/NzbDrone.Core.Test/IndexerTests/IPTorrentsTests/IPTorrentsFixture.cs index 08204e6a7..d00a2d731 100644 --- a/src/NzbDrone.Core.Test/IndexerTests/IPTorrentsTests/IPTorrentsFixture.cs +++ b/src/NzbDrone.Core.Test/IndexerTests/IPTorrentsTests/IPTorrentsFixture.cs @@ -1,3 +1,6 @@ +using System; +using System.Linq; +using FluentAssertions; using Moq; using NUnit.Framework; using NzbDrone.Common.Http; @@ -5,9 +8,6 @@ using NzbDrone.Core.Indexers.IPTorrents; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Test.Framework; -using System; -using System.Linq; -using FluentAssertions; namespace NzbDrone.Core.Test.IndexerTests.IPTorrentsTests { diff --git a/src/NzbDrone.Core.Test/IndexerTests/IndexerServiceFixture.cs b/src/NzbDrone.Core.Test/IndexerTests/IndexerServiceFixture.cs index 7d4509d8f..4cc12f77b 100644 --- a/src/NzbDrone.Core.Test/IndexerTests/IndexerServiceFixture.cs +++ b/src/NzbDrone.Core.Test/IndexerTests/IndexerServiceFixture.cs @@ -33,7 +33,7 @@ public void should_remove_missing_indexers_on_startup() Mocker.SetConstant(repo); var existingIndexers = Builder.CreateNew().BuildNew(); - existingIndexers.ConfigContract = typeof (NewznabSettings).Name; + existingIndexers.ConfigContract = typeof(NewznabSettings).Name; repo.Insert(existingIndexers); diff --git a/src/NzbDrone.Core.Test/IndexerTests/IntegrationTests/IndexerIntegrationTests.cs b/src/NzbDrone.Core.Test/IndexerTests/IntegrationTests/IndexerIntegrationTests.cs index 392403dae..97a30d403 100644 --- a/src/NzbDrone.Core.Test/IndexerTests/IntegrationTests/IndexerIntegrationTests.cs +++ b/src/NzbDrone.Core.Test/IndexerTests/IntegrationTests/IndexerIntegrationTests.cs @@ -70,6 +70,5 @@ private void ValidateResult(IList reports, bool hasSize = false, bo reports.Should().OnlyContain(c => c.Size > 0); } } - } } diff --git a/src/NzbDrone.Core.Test/IndexerTests/NewznabTests/NewznabFixture.cs b/src/NzbDrone.Core.Test/IndexerTests/NewznabTests/NewznabFixture.cs index f38cdbf8a..1bce91ff5 100644 --- a/src/NzbDrone.Core.Test/IndexerTests/NewznabTests/NewznabFixture.cs +++ b/src/NzbDrone.Core.Test/IndexerTests/NewznabTests/NewznabFixture.cs @@ -64,7 +64,6 @@ public void should_parse_recent_feed_from_newznab_nzb_su() releaseInfo.Size.Should().Be(1183105773); } - [Test] public void should_parse_recent_feed_from_newznab_animetosho() { diff --git a/src/NzbDrone.Core.Test/IndexerTests/NewznabTests/NewznabRequestGeneratorFixture.cs b/src/NzbDrone.Core.Test/IndexerTests/NewznabTests/NewznabRequestGeneratorFixture.cs index 59c37ef20..b9b4aec81 100644 --- a/src/NzbDrone.Core.Test/IndexerTests/NewznabTests/NewznabRequestGeneratorFixture.cs +++ b/src/NzbDrone.Core.Test/IndexerTests/NewznabTests/NewznabRequestGeneratorFixture.cs @@ -21,14 +21,14 @@ public void SetUp() Subject.Settings = new NewznabSettings() { BaseUrl = "http://127.0.0.1:1234/", - Categories = new [] { 1, 2 }, - AnimeCategories = new [] { 3, 4 }, + Categories = new[] { 1, 2 }, + AnimeCategories = new[] { 3, 4 }, ApiKey = "abcd", }; _singleEpisodeSearchCriteria = new SingleEpisodeSearchCriteria { - Series = new Tv.Series { TvRageId = 10, TvdbId = 20, TvMazeId = 30, ImdbId ="t40" }, + Series = new Tv.Series { TvRageId = 10, TvdbId = 20, TvMazeId = 30, ImdbId = "t40" }, SceneTitles = new List { "Monkey Island" }, SeasonNumber = 1, EpisodeNumber = 2 diff --git a/src/NzbDrone.Core.Test/IndexerTests/NewznabTests/NewznabSettingFixture.cs b/src/NzbDrone.Core.Test/IndexerTests/NewznabTests/NewznabSettingFixture.cs index 21da9fa64..44b2766ab 100644 --- a/src/NzbDrone.Core.Test/IndexerTests/NewznabTests/NewznabSettingFixture.cs +++ b/src/NzbDrone.Core.Test/IndexerTests/NewznabTests/NewznabSettingFixture.cs @@ -7,7 +7,6 @@ namespace NzbDrone.Core.Test.IndexerTests.NewznabTests { public class NewznabSettingFixture : CoreTest { - [TestCase("http://nzbs.org")] [TestCase("http:///www.nzbplanet.net")] public void requires_apikey(string url) @@ -18,10 +17,8 @@ public void requires_apikey(string url) BaseUrl = url }; - setting.Validate().IsValid.Should().BeFalse(); setting.Validate().Errors.Should().Contain(c => c.PropertyName == nameof(NewznabSettings.ApiKey)); - } [TestCase("")] @@ -35,14 +32,11 @@ public void invalid_url_should_not_apikey(string url) BaseUrl = url }; - setting.Validate().IsValid.Should().BeFalse(); setting.Validate().Errors.Should().NotContain(c => c.PropertyName == nameof(NewznabSettings.ApiKey)); setting.Validate().Errors.Should().Contain(c => c.PropertyName == nameof(NewznabSettings.BaseUrl)); - } - [TestCase("http://nzbs2.org")] public void doesnt_requires_apikey(string url) { @@ -52,7 +46,6 @@ public void doesnt_requires_apikey(string url) BaseUrl = url }; - setting.Validate().IsValid.Should().BeTrue(); } } diff --git a/src/NzbDrone.Core.Test/IndexerTests/NyaaTests/NyaaFixture.cs b/src/NzbDrone.Core.Test/IndexerTests/NyaaTests/NyaaFixture.cs index 5b317f8e9..d2db3be6d 100644 --- a/src/NzbDrone.Core.Test/IndexerTests/NyaaTests/NyaaFixture.cs +++ b/src/NzbDrone.Core.Test/IndexerTests/NyaaTests/NyaaFixture.cs @@ -82,7 +82,7 @@ public void should_parse_2021_recent_feed_from_Nyaa() torrentInfo.Size.Should().Be(639211930); //609.6 MiB torrentInfo.MagnetUrl.Should().Be(null); torrentInfo.Seeders.Should().Be(4); - torrentInfo.Peers.Should().Be(3+4); + torrentInfo.Peers.Should().Be(3 + 4); } } } diff --git a/src/NzbDrone.Core.Test/IndexerTests/OmgwtfnzbsTests/OmgwtfnzbsFixture.cs b/src/NzbDrone.Core.Test/IndexerTests/OmgwtfnzbsTests/OmgwtfnzbsFixture.cs index c5542b943..3e211d4cb 100644 --- a/src/NzbDrone.Core.Test/IndexerTests/OmgwtfnzbsTests/OmgwtfnzbsFixture.cs +++ b/src/NzbDrone.Core.Test/IndexerTests/OmgwtfnzbsTests/OmgwtfnzbsFixture.cs @@ -35,7 +35,7 @@ public void should_parse_recent_feed_from_omgwtfnzbs() Mocker.GetMock() .Setup(o => o.Execute(It.Is(v => v.Method == HttpMethod.GET))) .Returns(r => new HttpResponse(r, new HttpHeader(), recentFeed)); - + var releases = Subject.FetchRecent(); releases.Should().HaveCount(100); diff --git a/src/NzbDrone.Core.Test/IndexerTests/SeasonSearchFixture.cs b/src/NzbDrone.Core.Test/IndexerTests/SeasonSearchFixture.cs index 3092546e0..316d4ae08 100644 --- a/src/NzbDrone.Core.Test/IndexerTests/SeasonSearchFixture.cs +++ b/src/NzbDrone.Core.Test/IndexerTests/SeasonSearchFixture.cs @@ -36,7 +36,7 @@ private void WithIndexer(bool paging, int resultCount) var requestGenerator = Mocker.GetMock(); Subject._requestGenerator = requestGenerator.Object; - + var requests = Builder.CreateListOfSize(paging ? 100 : 1) .All() .WithFactory(() => new IndexerRequest("http://my.feed.local/", HttpAccept.Rss)) @@ -64,7 +64,7 @@ public void should_not_use_offset_if_result_count_is_less_than_90() { WithIndexer(true, 25); - Subject.Fetch(new SeasonSearchCriteria { Series = _series, SceneTitles = new List{_series.Title} }); + Subject.Fetch(new SeasonSearchCriteria { Series = _series, SceneTitles = new List { _series.Title } }); Mocker.GetMock().Verify(v => v.Execute(It.IsAny()), Times.Once()); } diff --git a/src/NzbDrone.Core.Test/IndexerTests/TestIndexer.cs b/src/NzbDrone.Core.Test/IndexerTests/TestIndexer.cs index a4c3a05d4..2b73b3b73 100644 --- a/src/NzbDrone.Core.Test/IndexerTests/TestIndexer.cs +++ b/src/NzbDrone.Core.Test/IndexerTests/TestIndexer.cs @@ -18,7 +18,6 @@ public class TestIndexer : HttpIndexerBase public TestIndexer(IHttpClient httpClient, IIndexerStatusService indexerStatusService, IConfigService configService, IParsingService parsingService, Logger logger) : base(httpClient, indexerStatusService, configService, parsingService, logger) { - } public IIndexerRequestGenerator _requestGenerator; diff --git a/src/NzbDrone.Core.Test/IndexerTests/TorrentRssIndexerTests/TestTorrentRssIndexer.cs b/src/NzbDrone.Core.Test/IndexerTests/TorrentRssIndexerTests/TestTorrentRssIndexer.cs index ce7ec77b5..17d60e25b 100644 --- a/src/NzbDrone.Core.Test/IndexerTests/TorrentRssIndexerTests/TestTorrentRssIndexer.cs +++ b/src/NzbDrone.Core.Test/IndexerTests/TorrentRssIndexerTests/TestTorrentRssIndexer.cs @@ -1,13 +1,13 @@ using System.Collections.Generic; using FluentValidation.Results; using NLog; +using NLog.Config; +using NLog.Targets; using NzbDrone.Common.Http; using NzbDrone.Core.Configuration; using NzbDrone.Core.Indexers; using NzbDrone.Core.Indexers.TorrentRss; using NzbDrone.Core.Parser; -using NLog.Config; -using NLog.Targets; namespace NzbDrone.Core.Test.IndexerTests.TorrentRssIndexerTests { @@ -31,13 +31,13 @@ public List TestPublic() /// private void SetupNLog() { - // Step 1. Create configuration object + // Step 1. Create configuration object var config = new LoggingConfiguration(); var fileTarget = new FileTarget(); config.AddTarget("file", fileTarget); - // Step 3. Set target properties + // Step 3. Set target properties fileTarget.FileName = "${basedir}/log.txt"; fileTarget.Layout = GetStandardLayout(); diff --git a/src/NzbDrone.Core.Test/IndexerTests/TorrentRssIndexerTests/TorrentRssIndexerFixture.cs b/src/NzbDrone.Core.Test/IndexerTests/TorrentRssIndexerTests/TorrentRssIndexerFixture.cs index 0a384c099..6189f6460 100644 --- a/src/NzbDrone.Core.Test/IndexerTests/TorrentRssIndexerTests/TorrentRssIndexerFixture.cs +++ b/src/NzbDrone.Core.Test/IndexerTests/TorrentRssIndexerTests/TorrentRssIndexerFixture.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Linq; using FluentAssertions; using Moq; @@ -13,7 +13,6 @@ namespace NzbDrone.Core.Test.IndexerTests.TorrentRssIndexerTests { - [TestFixture] public class TorrentRssIndexerFixture : CoreTest { @@ -220,7 +219,7 @@ public void should_parse_recent_feed_from_AnimeTosho_without_size() torrentInfo.CommentUrl.Should().Be("https://animetosho.org/view/fff-ore-monogatari-vol-01-bd-720p-aac.1009077"); torrentInfo.Indexer.Should().Be(Subject.Definition.Name); torrentInfo.PublishDate.Should().Be(DateTime.Parse("Tue, 02 Aug 2016 13:48:04 +0000").ToUniversalTime()); - torrentInfo.Size.Should().Be((long)Math.Round((double)1.366m * 1024L * 1024L * 1024L)); + torrentInfo.Size.Should().Be((long)Math.Round(1.366D * 1024L * 1024L * 1024L)); torrentInfo.InfoHash.Should().BeNull(); torrentInfo.MagnetUrl.Should().BeNull(); torrentInfo.Peers.Should().NotHaveValue(); diff --git a/src/NzbDrone.Core.Test/IndexerTests/TorrentRssIndexerTests/TorrentRssParserFactoryFixture.cs b/src/NzbDrone.Core.Test/IndexerTests/TorrentRssIndexerTests/TorrentRssParserFactoryFixture.cs index 0ed86b3c1..e506c2978 100644 --- a/src/NzbDrone.Core.Test/IndexerTests/TorrentRssIndexerTests/TorrentRssParserFactoryFixture.cs +++ b/src/NzbDrone.Core.Test/IndexerTests/TorrentRssIndexerTests/TorrentRssParserFactoryFixture.cs @@ -1,11 +1,11 @@ -using Moq; +using FluentAssertions; +using Moq; using NUnit.Framework; using NzbDrone.Common.Cache; +using NzbDrone.Core.Indexers; +using NzbDrone.Core.Indexers.Exceptions; using NzbDrone.Core.Indexers.TorrentRss; using NzbDrone.Core.Test.Framework; -using FluentAssertions; -using NzbDrone.Core.Indexers.Exceptions; -using NzbDrone.Core.Indexers; namespace NzbDrone.Core.Test.IndexerTests.TorrentRssIndexerTests { diff --git a/src/NzbDrone.Core.Test/IndexerTests/TorrentleechTests/TorrentleechFixture.cs b/src/NzbDrone.Core.Test/IndexerTests/TorrentleechTests/TorrentleechFixture.cs index 8ecb58144..6b4d5fd0e 100644 --- a/src/NzbDrone.Core.Test/IndexerTests/TorrentleechTests/TorrentleechFixture.cs +++ b/src/NzbDrone.Core.Test/IndexerTests/TorrentleechTests/TorrentleechFixture.cs @@ -1,13 +1,13 @@ -using Moq; +using System; +using System.Linq; +using FluentAssertions; +using Moq; using NUnit.Framework; using NzbDrone.Common.Http; using NzbDrone.Core.Indexers; using NzbDrone.Core.Indexers.Torrentleech; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Test.Framework; -using System; -using System.Linq; -using FluentAssertions; namespace NzbDrone.Core.Test.IndexerTests.TorrentleechTests { @@ -50,7 +50,7 @@ public void should_parse_recent_feed_from_Torrentleech() torrentInfo.Size.Should().Be(0); torrentInfo.InfoHash.Should().Be(null); torrentInfo.MagnetUrl.Should().Be(null); - torrentInfo.Peers.Should().Be(7+1); + torrentInfo.Peers.Should().Be(7 + 1); torrentInfo.Seeders.Should().Be(1); } } diff --git a/src/NzbDrone.Core.Test/IndexerTests/TorznabTests/TorznabFixture.cs b/src/NzbDrone.Core.Test/IndexerTests/TorznabTests/TorznabFixture.cs index 056d61b89..eb8a8255b 100644 --- a/src/NzbDrone.Core.Test/IndexerTests/TorznabTests/TorznabFixture.cs +++ b/src/NzbDrone.Core.Test/IndexerTests/TorznabTests/TorznabFixture.cs @@ -1,5 +1,6 @@ using System; using System.Linq; +using System.Net.Http; using FizzWare.NBuilder; using FluentAssertions; using Moq; diff --git a/src/NzbDrone.Core.Test/Instrumentation/DatabaseTargetFixture.cs b/src/NzbDrone.Core.Test/Instrumentation/DatabaseTargetFixture.cs index 716b5c042..b19dbe513 100644 --- a/src/NzbDrone.Core.Test/Instrumentation/DatabaseTargetFixture.cs +++ b/src/NzbDrone.Core.Test/Instrumentation/DatabaseTargetFixture.cs @@ -18,7 +18,7 @@ namespace NzbDrone.Core.Test.Instrumentation public class DatabaseTargetFixture : DbTest { private static string _uniqueMessage; - Logger _logger; + private Logger _logger; protected override MigrationType MigrationType => MigrationType.Log; @@ -64,7 +64,6 @@ public void write_long_log() VerifyLog(StoredModel, LogLevel.Info); } - [Test] [Explicit] [ManualTest] @@ -126,7 +125,6 @@ public void null_string_as_arg_should_not_fail() epFile.RelativePath.Should().BeNull(); } - [TearDown] public void Teardown() { diff --git a/src/NzbDrone.Core.Test/Languages/LanguageFixture.cs b/src/NzbDrone.Core.Test/Languages/LanguageFixture.cs index 5cfe5ae84..90b61ef92 100644 --- a/src/NzbDrone.Core.Test/Languages/LanguageFixture.cs +++ b/src/NzbDrone.Core.Test/Languages/LanguageFixture.cs @@ -1,10 +1,10 @@ -using System.Linq; -using System.Collections.Generic; +using System.Collections.Generic; +using System.Linq; using FluentAssertions; using NUnit.Framework; +using NzbDrone.Core.Languages; using NzbDrone.Core.Profiles.Languages; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Languages; namespace NzbDrone.Core.Test.Languages { @@ -13,64 +13,66 @@ public class LanguageFixture : CoreTest { public static object[] FromIntCases = { - new object[] {1, Language.English}, - new object[] {2, Language.French}, - new object[] {3, Language.Spanish}, - new object[] {4, Language.German}, - new object[] {5, Language.Italian}, - new object[] {6, Language.Danish}, - new object[] {7, Language.Dutch}, - new object[] {8, Language.Japanese}, - new object[] {9, Language.Icelandic}, - new object[] {10, Language.Chinese}, - new object[] {11, Language.Russian}, - new object[] {12, Language.Polish}, - new object[] {13, Language.Vietnamese}, - new object[] {14, Language.Swedish}, - new object[] {15, Language.Norwegian}, - new object[] {16, Language.Finnish}, - new object[] {17, Language.Turkish}, - new object[] {18, Language.Portuguese}, - new object[] {19, Language.Flemish}, - new object[] {20, Language.Greek}, - new object[] {21, Language.Korean}, - new object[] {22, Language.Hungarian} + new object[] { 1, Language.English }, + new object[] { 2, Language.French }, + new object[] { 3, Language.Spanish }, + new object[] { 4, Language.German }, + new object[] { 5, Language.Italian }, + new object[] { 6, Language.Danish }, + new object[] { 7, Language.Dutch }, + new object[] { 8, Language.Japanese }, + new object[] { 9, Language.Icelandic }, + new object[] { 10, Language.Chinese }, + new object[] { 11, Language.Russian }, + new object[] { 12, Language.Polish }, + new object[] { 13, Language.Vietnamese }, + new object[] { 14, Language.Swedish }, + new object[] { 15, Language.Norwegian }, + new object[] { 16, Language.Finnish }, + new object[] { 17, Language.Turkish }, + new object[] { 18, Language.Portuguese }, + new object[] { 19, Language.Flemish }, + new object[] { 20, Language.Greek }, + new object[] { 21, Language.Korean }, + new object[] { 22, Language.Hungarian } }; public static object[] ToIntCases = { - new object[] {Language.English, 1}, - new object[] {Language.French, 2}, - new object[] {Language.Spanish, 3}, - new object[] {Language.German, 4}, - new object[] {Language.Italian, 5}, - new object[] {Language.Danish, 6}, - new object[] {Language.Dutch, 7}, - new object[] {Language.Japanese, 8}, - new object[] {Language.Icelandic, 9}, - new object[] {Language.Chinese, 10}, - new object[] {Language.Russian, 11}, - new object[] {Language.Polish, 12}, - new object[] {Language.Vietnamese, 13}, - new object[] {Language.Swedish, 14}, - new object[] {Language.Norwegian, 15}, - new object[] {Language.Finnish, 16}, - new object[] {Language.Turkish, 17}, - new object[] {Language.Portuguese, 18}, - new object[] {Language.Flemish, 19}, - new object[] {Language.Greek, 20}, - new object[] {Language.Korean, 21}, - new object[] {Language.Hungarian, 22} + new object[] { Language.English, 1 }, + new object[] { Language.French, 2 }, + new object[] { Language.Spanish, 3 }, + new object[] { Language.German, 4 }, + new object[] { Language.Italian, 5 }, + new object[] { Language.Danish, 6 }, + new object[] { Language.Dutch, 7 }, + new object[] { Language.Japanese, 8 }, + new object[] { Language.Icelandic, 9 }, + new object[] { Language.Chinese, 10 }, + new object[] { Language.Russian, 11 }, + new object[] { Language.Polish, 12 }, + new object[] { Language.Vietnamese, 13 }, + new object[] { Language.Swedish, 14 }, + new object[] { Language.Norwegian, 15 }, + new object[] { Language.Finnish, 16 }, + new object[] { Language.Turkish, 17 }, + new object[] { Language.Portuguese, 18 }, + new object[] { Language.Flemish, 19 }, + new object[] { Language.Greek, 20 }, + new object[] { Language.Korean, 21 }, + new object[] { Language.Hungarian, 22 } }; - [Test, TestCaseSource("FromIntCases")] + [Test] + [TestCaseSource("FromIntCases")] public void should_be_able_to_convert_int_to_languageTypes(int source, Language expected) { var language = (Language)source; language.Should().Be(expected); } - [Test, TestCaseSource("ToIntCases")] + [Test] + [TestCaseSource("ToIntCases")] public void should_be_able_to_convert_languageTypes_to_int(Language source, int expected) { var i = (int)source; @@ -87,7 +89,9 @@ public static List GetDefaultLanguages(params Language[] al }; if (allowed.Length == 0) + { allowed = languages.ToArray(); + } var items = languages .Except(allowed) diff --git a/src/NzbDrone.Core.Test/Languages/LanguageProfileRepositoryFixture.cs b/src/NzbDrone.Core.Test/Languages/LanguageProfileRepositoryFixture.cs index 8b04967be..cff03b447 100644 --- a/src/NzbDrone.Core.Test/Languages/LanguageProfileRepositoryFixture.cs +++ b/src/NzbDrone.Core.Test/Languages/LanguageProfileRepositoryFixture.cs @@ -1,9 +1,9 @@ -using FluentAssertions; using System.Linq; +using FluentAssertions; using NUnit.Framework; using NzbDrone.Core.Languages; -using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Profiles.Languages; +using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.Languages { @@ -15,18 +15,17 @@ public void should_be_able_to_read_and_write() { var profile = new LanguageProfile { - Languages = Language.All.OrderByDescending(l => l.Name).Select(l => new LanguageProfileItem {Language = l, Allowed = l == Language.English}).ToList(), + Languages = Language.All.OrderByDescending(l => l.Name).Select(l => new LanguageProfileItem { Language = l, Allowed = l == Language.English }).ToList(), Name = "TestProfile", Cutoff = Language.English }; Subject.Insert(profile); - StoredModel.Name.Should().Be(profile.Name); StoredModel.Cutoff.Should().Be(profile.Cutoff); StoredModel.Languages.Should().Equal(profile.Languages, (a, b) => a.Language == b.Language && a.Allowed == b.Allowed); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core.Test/Languages/LanguageProfileServiceFixture.cs b/src/NzbDrone.Core.Test/Languages/LanguageProfileServiceFixture.cs index f4cb6966d..0d63f98da 100644 --- a/src/NzbDrone.Core.Test/Languages/LanguageProfileServiceFixture.cs +++ b/src/NzbDrone.Core.Test/Languages/LanguageProfileServiceFixture.cs @@ -5,9 +5,9 @@ using NUnit.Framework; using NzbDrone.Core.ImportLists; using NzbDrone.Core.Lifecycle; +using NzbDrone.Core.Profiles.Languages; using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Tv; -using NzbDrone.Core.Profiles.Languages; namespace NzbDrone.Core.Test.Languages { @@ -33,6 +33,7 @@ public void init_should_add_default_profiles() } [Test] + //This confirms that new profiles are added only if no other profiles exists. //We don't want to keep adding them back if a user deleted them on purpose. public void Init_should_skip_if_any_profiles_already_exist() @@ -47,7 +48,6 @@ public void Init_should_skip_if_any_profiles_already_exist() .Verify(v => v.Insert(It.IsAny()), Times.Never()); } - [Test] public void should_not_be_able_to_delete_profile_if_assigned_to_series() { @@ -56,7 +56,6 @@ public void should_not_be_able_to_delete_profile_if_assigned_to_series() .With(c => c.LanguageProfileId = 2) .Build().ToList(); - Mocker.GetMock().Setup(c => c.GetAllSeries()).Returns(seriesList); Assert.Throws(() => Subject.Delete(2)); @@ -72,7 +71,6 @@ public void should_delete_profile_if_not_assigned_to_series() .With(c => c.LanguageProfileId = 2) .Build().ToList(); - Mocker.GetMock().Setup(c => c.GetAllSeries()).Returns(seriesList); Subject.Delete(1); @@ -93,8 +91,6 @@ public void should_not_be_able_to_delete_profile_if_assigned_to_import_list() .With(c => c.LanguageProfileId = 1) .Build().ToList(); - - Mocker.GetMock().Setup(c => c.GetAllSeries()).Returns(seriesList); Mocker.GetMock() @@ -106,4 +102,4 @@ public void should_not_be_able_to_delete_profile_if_assigned_to_import_list() Mocker.GetMock().Verify(c => c.Delete(It.IsAny()), Times.Never()); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core.Test/MediaCoverTests/CoverExistsSpecificationFixture.cs b/src/NzbDrone.Core.Test/MediaCoverTests/CoverExistsSpecificationFixture.cs index bb3b0a99c..8260a7146 100644 --- a/src/NzbDrone.Core.Test/MediaCoverTests/CoverExistsSpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/MediaCoverTests/CoverExistsSpecificationFixture.cs @@ -20,24 +20,19 @@ public void Setup() _httpResponse = new HttpResponse(null, new HttpHeader(), "", HttpStatusCode.OK); Mocker.GetMock().Setup(c => c.GetFileSize(It.IsAny())).Returns(100); Mocker.GetMock().Setup(c => c.Head(It.IsAny())).Returns(_httpResponse); - } - private void GivenFileExistsOnDisk() { Mocker.GetMock().Setup(c => c.FileExists(It.IsAny())).Returns(true); } - private void GivenExistingFileSize(long bytes) { GivenFileExistsOnDisk(); Mocker.GetMock().Setup(c => c.GetFileSize(It.IsAny())).Returns(bytes); - } - [Test] public void should_return_false_if_file_not_exists() { @@ -53,7 +48,6 @@ public void should_return_false_if_file_exists_but_diffrent_size() Subject.AlreadyExists("http://url", "c:\\file.exe").Should().BeFalse(); } - [Test] public void should_return_ture_if_file_exists_and_same_size() { @@ -69,4 +63,4 @@ public void should_return_true_if_there_is_no_size_header_and_file_exist() Subject.AlreadyExists("http://url", "c:\\file.exe").Should().BeFalse(); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core.Test/MediaCoverTests/ImageResizerFixture.cs b/src/NzbDrone.Core.Test/MediaCoverTests/ImageResizerFixture.cs index e5a4c05f7..5a719fc90 100644 --- a/src/NzbDrone.Core.Test/MediaCoverTests/ImageResizerFixture.cs +++ b/src/NzbDrone.Core.Test/MediaCoverTests/ImageResizerFixture.cs @@ -66,4 +66,4 @@ public void should_delete_file_if_failed() File.Exists(resizedFile).Should().BeFalse(); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core.Test/MediaCoverTests/MediaCoverServiceFixture.cs b/src/NzbDrone.Core.Test/MediaCoverTests/MediaCoverServiceFixture.cs index fdf2efb07..a6cb13b6b 100644 --- a/src/NzbDrone.Core.Test/MediaCoverTests/MediaCoverServiceFixture.cs +++ b/src/NzbDrone.Core.Test/MediaCoverTests/MediaCoverServiceFixture.cs @@ -17,7 +17,7 @@ namespace NzbDrone.Core.Test.MediaCoverTests [TestFixture] public class MediaCoverServiceFixture : CoreTest { - Series _series; + private Series _series; [SetUp] public void Setup() @@ -35,7 +35,7 @@ public void should_convert_cover_urls_to_local() { var covers = new List { - new MediaCover.MediaCover {CoverType = MediaCoverTypes.Banner} + new MediaCover.MediaCover { CoverType = MediaCoverTypes.Banner } }; Mocker.GetMock().Setup(c => c.FileGetLastWrite(It.IsAny())) @@ -46,7 +46,6 @@ public void should_convert_cover_urls_to_local() Subject.ConvertToLocalUrls(12, covers); - covers.Single().Url.Should().Be("/MediaCover/12/banner.jpg?lastWrite=1234"); } @@ -55,13 +54,11 @@ public void should_convert_media_urls_to_local_without_time_if_file_doesnt_exist { var covers = new List { - new MediaCover.MediaCover {CoverType = MediaCoverTypes.Banner} + new MediaCover.MediaCover { CoverType = MediaCoverTypes.Banner } }; - Subject.ConvertToLocalUrls(12, covers); - covers.Single().Url.Should().Be("/MediaCover/12/banner.jpg"); } @@ -162,4 +159,4 @@ public void should_log_error_if_resize_failed() .Verify(v => v.Resize(It.IsAny(), It.IsAny(), It.IsAny()), Times.Exactly(2)); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core.Test/MediaFiles/DownloadedEpisodesImportServiceFixture.cs b/src/NzbDrone.Core.Test/MediaFiles/DownloadedEpisodesImportServiceFixture.cs index 66b067da1..11e5a2f1b 100644 --- a/src/NzbDrone.Core.Test/MediaFiles/DownloadedEpisodesImportServiceFixture.cs +++ b/src/NzbDrone.Core.Test/MediaFiles/DownloadedEpisodesImportServiceFixture.cs @@ -47,7 +47,6 @@ public void Setup() .Setup(s => s.Import(It.IsAny>(), true, null, ImportMode.Auto)) .Returns(new List()); - var downloadItem = Builder.CreateNew() .With(v => v.DownloadId = "sab1") .With(v => v.Status = DownloadItemStatus.Downloading) @@ -286,7 +285,7 @@ public void should_not_delete_if_there_is_large_rar_file() Mocker.GetMock() .Setup(s => s.GetFiles(It.IsAny(), SearchOption.AllDirectories)) - .Returns(new []{ _videoFiles.First().Replace(".ext", ".rar") }); + .Returns(new[] { _videoFiles.First().Replace(".ext", ".rar") }); Mocker.GetMock() .Setup(s => s.GetFileSize(It.IsAny())) @@ -319,7 +318,6 @@ public void should_use_folder_if_folder_import() var imported = new List(); imported.Add(new ImportDecision(localEpisode)); - Subject.ProcessPath(fileName); Mocker.GetMock() diff --git a/src/NzbDrone.Core.Test/MediaFiles/EpisodeFilePreferredWordCalculatorFixture.cs b/src/NzbDrone.Core.Test/MediaFiles/EpisodeFilePreferredWordCalculatorFixture.cs index 4ef7d1167..bf6a89bc7 100644 --- a/src/NzbDrone.Core.Test/MediaFiles/EpisodeFilePreferredWordCalculatorFixture.cs +++ b/src/NzbDrone.Core.Test/MediaFiles/EpisodeFilePreferredWordCalculatorFixture.cs @@ -15,11 +15,11 @@ namespace NzbDrone.Core.Test.MediaFiles [TestFixture] public class EpisodeFilePreferredWordCalculatorFixture : CoreTest { - private Series _series; - private EpisodeFile _episodeFile; private readonly KeyValuePair _positiveScore = new KeyValuePair("Positive", 10); private readonly KeyValuePair _negativeScore = new KeyValuePair("Negative", -10); private KeyValuePair _neutralScore = new KeyValuePair("Neutral", 0); + private Series _series; + private EpisodeFile _episodeFile; [SetUp] public void Setup() @@ -149,4 +149,4 @@ public void should_return_0_score_if_0_result_has_matches() Subject.Calculate(_series, _episodeFile).Should().Be(0); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core.Test/MediaFiles/EpisodeImport/Aggregation/Aggregators/AggregateLanguageFixture.cs b/src/NzbDrone.Core.Test/MediaFiles/EpisodeImport/Aggregation/Aggregators/AggregateLanguageFixture.cs index 8f65460cc..72a35f8e5 100644 --- a/src/NzbDrone.Core.Test/MediaFiles/EpisodeImport/Aggregation/Aggregators/AggregateLanguageFixture.cs +++ b/src/NzbDrone.Core.Test/MediaFiles/EpisodeImport/Aggregation/Aggregators/AggregateLanguageFixture.cs @@ -10,7 +10,7 @@ namespace NzbDrone.Core.Test.MediaFiles.EpisodeImport.Aggregation.Aggregators { - [TestFixture] + [TestFixture] public class AggregateLanguageFixture : CoreTest { private LocalEpisode _localEpisode; @@ -64,7 +64,6 @@ public void should_return_download_client_item_language_when_download_client_ite _localEpisode.FileEpisodeInfo = GetParsedEpisodeInfo(Language.English, _simpleReleaseTitle); Subject.Aggregate(_localEpisode, null).Language.Should().Be(_localEpisode.DownloadClientEpisodeInfo.Language); - } [Test] @@ -84,7 +83,6 @@ public void should_return_english_if_parsed_language_is_in_episode_title_and_rel _localEpisode.FileEpisodeInfo = GetParsedEpisodeInfo(Language.Swedish, "Series.Title.S01E01.The.Swedish.Job.720p.WEB-DL-RlsGrp"); Subject.Aggregate(_localEpisode, null).Language.Should().Be(Language.English); - } [Test] @@ -94,7 +92,6 @@ public void should_return_parsed_if_parsed_language_is_not_episode_title_and_rel _localEpisode.FileEpisodeInfo = GetParsedEpisodeInfo(Language.French, "Series.Title.S01E01.The.Swedish.Job.720p.WEB-DL-RlsGrp"); Subject.Aggregate(_localEpisode, null).Language.Should().Be(_localEpisode.FileEpisodeInfo.Language); - } } } diff --git a/src/NzbDrone.Core.Test/MediaFiles/EpisodeImport/Aggregation/Aggregators/AggregateQualityFixture.cs b/src/NzbDrone.Core.Test/MediaFiles/EpisodeImport/Aggregation/Aggregators/AggregateQualityFixture.cs index 3f5084407..b88b66ffb 100644 --- a/src/NzbDrone.Core.Test/MediaFiles/EpisodeImport/Aggregation/Aggregators/AggregateQualityFixture.cs +++ b/src/NzbDrone.Core.Test/MediaFiles/EpisodeImport/Aggregation/Aggregators/AggregateQualityFixture.cs @@ -12,7 +12,7 @@ namespace NzbDrone.Core.Test.MediaFiles.EpisodeImport.Aggregation.Aggregators { - [TestFixture] + [TestFixture] public class AggregateQualityFixture : CoreTest { private Mock _mediaInfoAugmenter; diff --git a/src/NzbDrone.Core.Test/MediaFiles/EpisodeImport/Aggregation/Aggregators/AggregateReleaseGroupFixture.cs b/src/NzbDrone.Core.Test/MediaFiles/EpisodeImport/Aggregation/Aggregators/AggregateReleaseGroupFixture.cs index 60f29a01c..beaf6b716 100644 --- a/src/NzbDrone.Core.Test/MediaFiles/EpisodeImport/Aggregation/Aggregators/AggregateReleaseGroupFixture.cs +++ b/src/NzbDrone.Core.Test/MediaFiles/EpisodeImport/Aggregation/Aggregators/AggregateReleaseGroupFixture.cs @@ -1,5 +1,4 @@ - -using FizzWare.NBuilder; +using FizzWare.NBuilder; using FluentAssertions; using NUnit.Framework; using NzbDrone.Core.MediaFiles.EpisodeImport.Aggregation.Aggregators; @@ -56,7 +55,7 @@ public void should_not_use_folder_for_full_season() localEpisode.ReleaseGroup.Should().Be("Wizzy"); } - + [Test] public void should_prefer_downloadclient() { diff --git a/src/NzbDrone.Core.Test/MediaFiles/EpisodeImport/Aggregation/Aggregators/Augmenters/Quality/AugmentQualityFromReleaseNameFixture.cs b/src/NzbDrone.Core.Test/MediaFiles/EpisodeImport/Aggregation/Aggregators/Augmenters/Quality/AugmentQualityFromReleaseNameFixture.cs index 1fcd8fb29..a6f5d5368 100644 --- a/src/NzbDrone.Core.Test/MediaFiles/EpisodeImport/Aggregation/Aggregators/Augmenters/Quality/AugmentQualityFromReleaseNameFixture.cs +++ b/src/NzbDrone.Core.Test/MediaFiles/EpisodeImport/Aggregation/Aggregators/Augmenters/Quality/AugmentQualityFromReleaseNameFixture.cs @@ -64,8 +64,7 @@ public void should_return_augmented_quality(string title, QualitySource source, .Setup(s => s.GetLatestGrab(It.IsAny())) .Returns(Builder.CreateNew() .With(h => h.SourceTitle = title) - .Build() - ); + .Build()); var result = Subject.AugmentQuality(_localEpisode, _downloadClientItem); diff --git a/src/NzbDrone.Core.Test/MediaFiles/EpisodeImport/GetSceneNameFixture.cs b/src/NzbDrone.Core.Test/MediaFiles/EpisodeImport/GetSceneNameFixture.cs index 491bef4c8..704218fbe 100644 --- a/src/NzbDrone.Core.Test/MediaFiles/EpisodeImport/GetSceneNameFixture.cs +++ b/src/NzbDrone.Core.Test/MediaFiles/EpisodeImport/GetSceneNameFixture.cs @@ -4,16 +4,16 @@ using FluentAssertions; using Moq; using NUnit.Framework; +using NzbDrone.Core.Languages; using NzbDrone.Core.MediaFiles; using NzbDrone.Core.MediaFiles.EpisodeImport; using NzbDrone.Core.Parser.Model; +using NzbDrone.Core.Profiles.Languages; using NzbDrone.Core.Profiles.Qualities; using NzbDrone.Core.Qualities; using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Tv; using NzbDrone.Test.Common; -using NzbDrone.Core.Languages; -using NzbDrone.Core.Profiles.Languages; namespace NzbDrone.Core.Test.MediaFiles.EpisodeImport { @@ -43,7 +43,7 @@ public void Setup() _localEpisode = new LocalEpisode { Series = series, - Episodes = new List {episode}, + Episodes = new List { episode }, Path = Path.Combine(series.Path, "Series Title - S02E23 - Episode Title.mkv"), Quality = new QualityModel(Quality.Bluray720p), ReleaseGroup = "DRONE" @@ -159,7 +159,7 @@ public void should_not_use_folder_name_as_scenename_if_it_is_for_a_full_season() { ReleaseTitle = _seasonName, FullSeason = true - }; + }; SceneNameCalculator.GetSceneName(_localEpisode).Should() .BeNull(); diff --git a/src/NzbDrone.Core.Test/MediaFiles/EpisodeImport/ImportApprovedEpisodesFixture.cs b/src/NzbDrone.Core.Test/MediaFiles/EpisodeImport/ImportApprovedEpisodesFixture.cs index f8519f201..44d7cdfd0 100644 --- a/src/NzbDrone.Core.Test/MediaFiles/EpisodeImport/ImportApprovedEpisodesFixture.cs +++ b/src/NzbDrone.Core.Test/MediaFiles/EpisodeImport/ImportApprovedEpisodesFixture.cs @@ -8,18 +8,18 @@ using NzbDrone.Common.Disk; using NzbDrone.Core.DecisionEngine; using NzbDrone.Core.Download; +using NzbDrone.Core.Languages; using NzbDrone.Core.MediaFiles; using NzbDrone.Core.MediaFiles.EpisodeImport; using NzbDrone.Core.MediaFiles.Events; using NzbDrone.Core.Messaging.Events; using NzbDrone.Core.Parser.Model; +using NzbDrone.Core.Profiles.Languages; using NzbDrone.Core.Profiles.Qualities; using NzbDrone.Core.Qualities; using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Tv; using NzbDrone.Test.Common; -using NzbDrone.Core.Languages; -using NzbDrone.Core.Profiles.Languages; namespace NzbDrone.Core.Test.MediaFiles.EpisodeImport { @@ -41,8 +41,8 @@ public void Setup() var series = Builder.CreateNew() .With(e => e.QualityProfile = new QualityProfile { Items = Qualities.QualityFixture.GetDefaultQualities() }) - .With(l => l.LanguageProfile = new LanguageProfile - { + .With(l => l.LanguageProfile = new LanguageProfile + { Cutoff = Language.Spanish, Languages = Languages.LanguageFixture.GetDefaultLanguages() }) @@ -52,16 +52,13 @@ public void Setup() var episodes = Builder.CreateListOfSize(5) .Build(); - - _rejectedDecisions.Add(new ImportDecision(new LocalEpisode(), new Rejection("Rejected!"))); _rejectedDecisions.Add(new ImportDecision(new LocalEpisode(), new Rejection("Rejected!"))); _rejectedDecisions.Add(new ImportDecision(new LocalEpisode(), new Rejection("Rejected!"))); foreach (var episode in episodes) { - _approvedDecisions.Add(new ImportDecision - ( + _approvedDecisions.Add(new ImportDecision( new LocalEpisode { Series = series, @@ -177,8 +174,8 @@ public void should_import_larger_files_first() var fileDecision = _approvedDecisions.First(); fileDecision.LocalEpisode.Size = 1.Gigabytes(); - var sampleDecision = new ImportDecision - (new LocalEpisode + var sampleDecision = new ImportDecision( + new LocalEpisode { Series = fileDecision.LocalEpisode.Series, Episodes = new List { fileDecision.LocalEpisode.Episodes.First() }, @@ -187,7 +184,6 @@ public void should_import_larger_files_first() Size = 80.Megabytes() }); - var all = new List(); all.Add(fileDecision); all.Add(sampleDecision); @@ -369,7 +365,7 @@ public void should_use_folder_info_release_title_to_find_relative_path_when_down var outputPath = Path.Combine(@"C:\Test\Unsorted\TV\".AsOsAgnostic(), name); var localEpisode = _approvedDecisions.First().LocalEpisode; - _downloadClientItem.OutputPath = new OsPath(); + _downloadClientItem.OutputPath = default(OsPath); localEpisode.FolderEpisodeInfo = new ParsedEpisodeInfo { ReleaseTitle = name }; localEpisode.Path = Path.Combine(outputPath, "subfolder", name + ".mkv"); diff --git a/src/NzbDrone.Core.Test/MediaFiles/EpisodeImport/ImportDecisionMakerFixture.cs b/src/NzbDrone.Core.Test/MediaFiles/EpisodeImport/ImportDecisionMakerFixture.cs index cf1cceee1..f613a0937 100644 --- a/src/NzbDrone.Core.Test/MediaFiles/EpisodeImport/ImportDecisionMakerFixture.cs +++ b/src/NzbDrone.Core.Test/MediaFiles/EpisodeImport/ImportDecisionMakerFixture.cs @@ -1,22 +1,22 @@ using System.Collections.Generic; using System.Linq; +using FizzWare.NBuilder; using FluentAssertions; using Moq; using NUnit.Framework; using NzbDrone.Core.DecisionEngine; +using NzbDrone.Core.Download; +using NzbDrone.Core.Languages; using NzbDrone.Core.MediaFiles; using NzbDrone.Core.MediaFiles.EpisodeImport; +using NzbDrone.Core.MediaFiles.EpisodeImport.Aggregation; using NzbDrone.Core.Parser.Model; +using NzbDrone.Core.Profiles.Languages; +using NzbDrone.Core.Profiles.Qualities; using NzbDrone.Core.Qualities; using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Tv; using NzbDrone.Test.Common; -using FizzWare.NBuilder; -using NzbDrone.Core.Download; -using NzbDrone.Core.Languages; -using NzbDrone.Core.MediaFiles.EpisodeImport.Aggregation; -using NzbDrone.Core.Profiles.Qualities; -using NzbDrone.Core.Profiles.Languages; namespace NzbDrone.Core.Test.MediaFiles.EpisodeImport { diff --git a/src/NzbDrone.Core.Test/MediaFiles/EpisodeImport/Specifications/EpisodeTitleSpecificationFixture.cs b/src/NzbDrone.Core.Test/MediaFiles/EpisodeImport/Specifications/EpisodeTitleSpecificationFixture.cs index 9d241a6cb..630acc959 100644 --- a/src/NzbDrone.Core.Test/MediaFiles/EpisodeImport/Specifications/EpisodeTitleSpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/MediaFiles/EpisodeImport/Specifications/EpisodeTitleSpecificationFixture.cs @@ -144,7 +144,6 @@ public void should_reject_if_episode_title_is_required_for_bulk_season_releases_ .Setup(s => s.EpisodeTitleRequired) .Returns(EpisodeTitleRequiredType.BulkSeasonReleases); - Mocker.GetMock() .Setup(s => s.GetEpisodesBySeason(It.IsAny(), It.IsAny())) .Returns(Builder.CreateListOfSize(5) @@ -164,7 +163,6 @@ public void should_reject_if_episode_title_is_required_for_bulk_season_releases_ .Setup(s => s.EpisodeTitleRequired) .Returns(EpisodeTitleRequiredType.BulkSeasonReleases); - Mocker.GetMock() .Setup(s => s.GetEpisodesBySeason(It.IsAny(), It.IsAny())) .Returns(Builder.CreateListOfSize(5) diff --git a/src/NzbDrone.Core.Test/MediaFiles/EpisodeImport/Specifications/FreeSpaceSpecificationFixture.cs b/src/NzbDrone.Core.Test/MediaFiles/EpisodeImport/Specifications/FreeSpaceSpecificationFixture.cs index 420962f69..7a607f97c 100644 --- a/src/NzbDrone.Core.Test/MediaFiles/EpisodeImport/Specifications/FreeSpaceSpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/MediaFiles/EpisodeImport/Specifications/FreeSpaceSpecificationFixture.cs @@ -26,18 +26,18 @@ public void Setup() { _rootFolder = @"C:\Test\TV".AsOsAgnostic(); - _series = Builder.CreateNew() + _series = Builder.CreateNew() .With(s => s.SeriesType = SeriesTypes.Standard) .With(s => s.Path = Path.Combine(_rootFolder, "30 Rock")) .Build(); - var episodes = Builder.CreateListOfSize(1) + var episodes = Builder.CreateListOfSize(1) .All() .With(e => e.SeasonNumber = 1) .Build() .ToList(); - _localEpisode = new LocalEpisode + _localEpisode = new LocalEpisode { Path = @"C:\Test\Unsorted\30 Rock\30.rock.s01e01.avi".AsOsAgnostic(), Episodes = episodes, diff --git a/src/NzbDrone.Core.Test/MediaFiles/EpisodeImport/Specifications/MatchesFolderSpecificationFixture.cs b/src/NzbDrone.Core.Test/MediaFiles/EpisodeImport/Specifications/MatchesFolderSpecificationFixture.cs index d7c23b143..5fee6a979 100644 --- a/src/NzbDrone.Core.Test/MediaFiles/EpisodeImport/Specifications/MatchesFolderSpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/MediaFiles/EpisodeImport/Specifications/MatchesFolderSpecificationFixture.cs @@ -35,7 +35,6 @@ public void Setup() .With(p => p.FullSeason = false) .Build()) .Build(); - } private void GivenEpisodes(ParsedEpisodeInfo parsedEpisodeInfo, int[] episodeNumbers) @@ -44,11 +43,11 @@ private void GivenEpisodes(ParsedEpisodeInfo parsedEpisodeInfo, int[] episodeNum var episodes = episodeNumbers.Select(n => Builder.CreateNew() - .With(e => e.Id = seasonNumber * 10 + n) + .With(e => e.Id = (seasonNumber * 10) + n) .With(e => e.SeasonNumber = seasonNumber) .With(e => e.EpisodeNumber = n) - .Build() - ).ToList(); + .Build()) + .ToList(); Mocker.GetMock() .Setup(s => s.GetEpisodes(parsedEpisodeInfo, It.IsAny(), true, null)) @@ -89,7 +88,7 @@ public void should_should_be_accepted_for_full_season() _localEpisode.FolderEpisodeInfo.FullSeason = true; GivenEpisodes(_localEpisode.FileEpisodeInfo, _localEpisode.FileEpisodeInfo.EpisodeNumbers); - GivenEpisodes(_localEpisode.FolderEpisodeInfo, new []{ 1, 2, 3, 4, 5 }); + GivenEpisodes(_localEpisode.FolderEpisodeInfo, new[] { 1, 2, 3, 4, 5 }); Subject.IsSatisfiedBy(_localEpisode, null).Accepted.Should().BeTrue(); } @@ -251,7 +250,7 @@ public void should_be_accepted_if_file_has_absolute_episode_number_and_folder_us _localEpisode.FolderEpisodeInfo.SeasonNumber = 1; _localEpisode.FolderEpisodeInfo.EpisodeNumbers = new[] { 1, 2 }; - GivenEpisodes(_localEpisode.FileEpisodeInfo, new []{ 1 }); + GivenEpisodes(_localEpisode.FileEpisodeInfo, new[] { 1 }); GivenEpisodes(_localEpisode.FolderEpisodeInfo, _localEpisode.FolderEpisodeInfo.EpisodeNumbers); _localEpisode.Path = @"C:\Test\Unsorted\Series.Title.S01.720p.HDTV-Sonarr\S02E01.mkv".AsOsAgnostic(); diff --git a/src/NzbDrone.Core.Test/MediaFiles/EpisodeImport/Specifications/UpgradeSpecificationFixture.cs b/src/NzbDrone.Core.Test/MediaFiles/EpisodeImport/Specifications/UpgradeSpecificationFixture.cs index 5cdb1e9a3..29930a09f 100644 --- a/src/NzbDrone.Core.Test/MediaFiles/EpisodeImport/Specifications/UpgradeSpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/MediaFiles/EpisodeImport/Specifications/UpgradeSpecificationFixture.cs @@ -5,16 +5,16 @@ using Moq; using NUnit.Framework; using NzbDrone.Core.Configuration; +using NzbDrone.Core.Languages; using NzbDrone.Core.MediaFiles; using NzbDrone.Core.MediaFiles.EpisodeImport.Specifications; using NzbDrone.Core.Parser.Model; +using NzbDrone.Core.Profiles.Languages; using NzbDrone.Core.Profiles.Qualities; +using NzbDrone.Core.Profiles.Releases; using NzbDrone.Core.Qualities; using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Tv; -using NzbDrone.Core.Languages; -using NzbDrone.Core.Profiles.Languages; -using NzbDrone.Core.Profiles.Releases; namespace NzbDrone.Core.Test.MediaFiles.EpisodeImport.Specifications { @@ -29,8 +29,8 @@ public void Setup() { _series = Builder.CreateNew() .With(s => s.SeriesType = SeriesTypes.Standard) - .With(e => e.QualityProfile = new QualityProfile - { + .With(e => e.QualityProfile = new QualityProfile + { Items = Qualities.QualityFixture.GetDefaultQualities(), }) .With(l => l.LanguageProfile = new LanguageProfile diff --git a/src/NzbDrone.Core.Test/MediaFiles/MediaFileRepositoryFixture.cs b/src/NzbDrone.Core.Test/MediaFiles/MediaFileRepositoryFixture.cs index ace441e7b..5acfc34d2 100644 --- a/src/NzbDrone.Core.Test/MediaFiles/MediaFileRepositoryFixture.cs +++ b/src/NzbDrone.Core.Test/MediaFiles/MediaFileRepositoryFixture.cs @@ -16,19 +16,17 @@ public void get_files_by_series() var files = Builder.CreateListOfSize(10) .All() .With(c => c.Id = 0) - .With(c => c.Quality =new QualityModel(Quality.Bluray720p)) + .With(c => c.Quality = new QualityModel(Quality.Bluray720p)) .Random(4) .With(s => s.SeriesId = 12) .BuildListOfNew(); - Db.InsertMany(files); var seriesFiles = Subject.GetFilesBySeries(12); seriesFiles.Should().HaveCount(4); seriesFiles.Should().OnlyContain(c => c.SeriesId == 12); - } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core.Test/MediaFiles/MediaFileServiceTests/FilterFixture.cs b/src/NzbDrone.Core.Test/MediaFiles/MediaFileServiceTests/FilterFixture.cs index 5e74ea3e3..0d6cf2dfe 100644 --- a/src/NzbDrone.Core.Test/MediaFiles/MediaFileServiceTests/FilterFixture.cs +++ b/src/NzbDrone.Core.Test/MediaFiles/MediaFileServiceTests/FilterFixture.cs @@ -40,7 +40,6 @@ public void filter_should_return_all_files_if_no_existing_files() .Setup(c => c.GetFilesBySeries(It.IsAny())) .Returns(new List()); - Subject.FilterExistingFiles(files, _series).Should().BeEquivalentTo(files); } @@ -58,7 +57,6 @@ public void filter_should_return_none_if_all_files_exist() .Setup(c => c.GetFilesBySeries(It.IsAny())) .Returns(files.Select(f => new EpisodeFile { RelativePath = Path.GetFileName(f) }).ToList()); - Subject.FilterExistingFiles(files, _series).Should().BeEmpty(); } @@ -76,10 +74,9 @@ public void filter_should_return_none_existing_files() .Setup(c => c.GetFilesBySeries(It.IsAny())) .Returns(new List { - new EpisodeFile{ RelativePath = "file2.avi".AsOsAgnostic()} + new EpisodeFile { RelativePath = "file2.avi".AsOsAgnostic() } }); - Subject.FilterExistingFiles(files, _series).Should().HaveCount(2); Subject.FilterExistingFiles(files, _series).Should().NotContain("C:\\file2.avi".AsOsAgnostic()); } @@ -100,10 +97,9 @@ public void filter_should_return_none_existing_files_ignoring_case() .Setup(c => c.GetFilesBySeries(It.IsAny())) .Returns(new List { - new EpisodeFile{ RelativePath = "file2.avi".AsOsAgnostic()} + new EpisodeFile { RelativePath = "file2.avi".AsOsAgnostic() } }); - Subject.FilterExistingFiles(files, _series).Should().HaveCount(2); Subject.FilterExistingFiles(files, _series).Should().NotContain("C:\\file2.avi".AsOsAgnostic()); } @@ -124,7 +120,7 @@ public void filter_should_return_none_existing_files_not_ignoring_case() .Setup(c => c.GetFilesBySeries(It.IsAny())) .Returns(new List { - new EpisodeFile{ RelativePath = "file2.avi".AsOsAgnostic()} + new EpisodeFile { RelativePath = "file2.avi".AsOsAgnostic() } }); Subject.FilterExistingFiles(files, _series).Should().HaveCount(3); diff --git a/src/NzbDrone.Core.Test/MediaFiles/MediaFileTableCleanupServiceFixture.cs b/src/NzbDrone.Core.Test/MediaFiles/MediaFileTableCleanupServiceFixture.cs index bb249561b..a6b123e71 100644 --- a/src/NzbDrone.Core.Test/MediaFiles/MediaFileTableCleanupServiceFixture.cs +++ b/src/NzbDrone.Core.Test/MediaFiles/MediaFileTableCleanupServiceFixture.cs @@ -1,6 +1,6 @@ using System.Collections.Generic; -using System.Linq; using System.IO; +using System.Linq; using FizzWare.NBuilder; using Moq; using NUnit.Framework; diff --git a/src/NzbDrone.Core.Test/MediaFiles/MediaInfo/MediaInfoFormatterTests/FormatVideoDynamicRangeFixture.cs b/src/NzbDrone.Core.Test/MediaFiles/MediaInfo/MediaInfoFormatterTests/FormatVideoDynamicRangeFixture.cs index 06903a4ff..e5000554c 100644 --- a/src/NzbDrone.Core.Test/MediaFiles/MediaInfo/MediaInfoFormatterTests/FormatVideoDynamicRangeFixture.cs +++ b/src/NzbDrone.Core.Test/MediaFiles/MediaInfo/MediaInfoFormatterTests/FormatVideoDynamicRangeFixture.cs @@ -67,4 +67,4 @@ public void should_format_video_dynamic_range_type(int bitDepth, string colourPr MediaInfoFormatter.FormatVideoDynamicRangeType(mediaInfo).Should().Be(expectedVideoDynamicRange); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core.Test/MediaFiles/MediaInfo/MediaInfoModelExtensionsFixture.cs b/src/NzbDrone.Core.Test/MediaFiles/MediaInfo/MediaInfoModelExtensionsFixture.cs index 86e423e21..5beec7b1d 100644 --- a/src/NzbDrone.Core.Test/MediaFiles/MediaInfo/MediaInfoModelExtensionsFixture.cs +++ b/src/NzbDrone.Core.Test/MediaFiles/MediaInfo/MediaInfoModelExtensionsFixture.cs @@ -1,12 +1,7 @@ -using FluentAssertions; +using FluentAssertions; using NUnit.Framework; using NzbDrone.Core.MediaFiles.MediaInfo; using NzbDrone.Test.Common; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace NzbDrone.Core.Test.MediaFiles.MediaInfo { diff --git a/src/NzbDrone.Core.Test/MediaFiles/MediaInfo/UpdateMediaInfoServiceFixture.cs b/src/NzbDrone.Core.Test/MediaFiles/MediaInfo/UpdateMediaInfoServiceFixture.cs index e763dc34d..de3621fcd 100644 --- a/src/NzbDrone.Core.Test/MediaFiles/MediaInfo/UpdateMediaInfoServiceFixture.cs +++ b/src/NzbDrone.Core.Test/MediaFiles/MediaInfo/UpdateMediaInfoServiceFixture.cs @@ -4,13 +4,13 @@ using Moq; using NUnit.Framework; using NzbDrone.Common.Disk; +using NzbDrone.Core.Configuration; using NzbDrone.Core.MediaFiles; using NzbDrone.Core.MediaFiles.Events; using NzbDrone.Core.MediaFiles.MediaInfo; using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Tv; using NzbDrone.Test.Common; -using NzbDrone.Core.Configuration; namespace NzbDrone.Core.Test.MediaFiles.MediaInfo { @@ -199,7 +199,7 @@ public void should_not_update_files_if_media_info_disabled() Mocker.GetMock() .SetupGet(s => s.EnableMediaInfo) .Returns(false); - + GivenFileExists(); GivenSuccessfulScan(); @@ -222,7 +222,7 @@ public void should_not_update_if_media_info_disabled() Mocker.GetMock() .SetupGet(s => s.EnableMediaInfo) .Returns(false); - + GivenFileExists(); GivenSuccessfulScan(); @@ -240,7 +240,7 @@ public void should_update_media_info() { var episodeFile = Builder.CreateNew() .With(v => v.RelativePath = "media.mkv") - .With(e => e.MediaInfo = new MediaInfoModel{SchemaRevision = 3}) + .With(e => e.MediaInfo = new MediaInfoModel { SchemaRevision = 3 }) .Build(); GivenFileExists(); @@ -254,13 +254,13 @@ public void should_update_media_info() Mocker.GetMock() .Verify(v => v.Update(episodeFile), Times.Once()); } - + [Test] public void should_not_update_media_info_if_new_info_is_null() { var episodeFile = Builder.CreateNew() .With(v => v.RelativePath = "media.mkv") - .With(e => e.MediaInfo = new MediaInfoModel{SchemaRevision = 3}) + .With(e => e.MediaInfo = new MediaInfoModel { SchemaRevision = 3 }) .Build(); GivenFileExists(); @@ -270,13 +270,13 @@ public void should_not_update_media_info_if_new_info_is_null() episodeFile.MediaInfo.Should().NotBeNull(); } - + [Test] public void should_not_save_episode_file_if_new_info_is_null() { var episodeFile = Builder.CreateNew() .With(v => v.RelativePath = "media.mkv") - .With(e => e.MediaInfo = new MediaInfoModel{SchemaRevision = 3}) + .With(e => e.MediaInfo = new MediaInfoModel { SchemaRevision = 3 }) .Build(); GivenFileExists(); diff --git a/src/NzbDrone.Core.Test/MediaFiles/MediaInfo/VideoFileInfoReaderFixture.cs b/src/NzbDrone.Core.Test/MediaFiles/MediaInfo/VideoFileInfoReaderFixture.cs index 969393ce5..946efbf62 100644 --- a/src/NzbDrone.Core.Test/MediaFiles/MediaInfo/VideoFileInfoReaderFixture.cs +++ b/src/NzbDrone.Core.Test/MediaFiles/MediaInfo/VideoFileInfoReaderFixture.cs @@ -67,7 +67,6 @@ public void get_info() info.AudioAdditionalFeatures.Should().BeOneOf("", "LC"); info.VideoHdrFormat.Should().BeEmpty(); info.VideoHdrFormatCompatibility.Should().BeEmpty(); - } [Test] diff --git a/src/NzbDrone.Core.Test/MediaFiles/RenameEpisodeFileServiceFixture.cs b/src/NzbDrone.Core.Test/MediaFiles/RenameEpisodeFileServiceFixture.cs index 5757641dc..6e2ef99fd 100644 --- a/src/NzbDrone.Core.Test/MediaFiles/RenameEpisodeFileServiceFixture.cs +++ b/src/NzbDrone.Core.Test/MediaFiles/RenameEpisodeFileServiceFixture.cs @@ -16,7 +16,7 @@ public class RenameEpisodeFileServiceFixture : CoreTest _episodeFiles; - + [SetUp] public void Setup() { @@ -60,7 +60,7 @@ public void should_not_publish_event_if_no_files_to_rename() { GivenNoEpisodeFiles(); - Subject.Execute(new RenameFilesCommand(_series.Id, new List{1})); + Subject.Execute(new RenameFilesCommand(_series.Id, new List { 1 })); Mocker.GetMock() .Verify(v => v.PublishEvent(It.IsAny()), Times.Never()); diff --git a/src/NzbDrone.Core.Test/Messaging/Commands/CommandEqualityComparerFixture.cs b/src/NzbDrone.Core.Test/Messaging/Commands/CommandEqualityComparerFixture.cs index 364e62a48..4e3140897 100644 --- a/src/NzbDrone.Core.Test/Messaging/Commands/CommandEqualityComparerFixture.cs +++ b/src/NzbDrone.Core.Test/Messaging/Commands/CommandEqualityComparerFixture.cs @@ -36,7 +36,7 @@ public void should_return_true_when_there_are_no_properties() [Test] public void should_return_true_when_single_property_matches() { - var command1 = new EpisodeSearchCommand { EpisodeIds = new List{ 1 } }; + var command1 = new EpisodeSearchCommand { EpisodeIds = new List { 1 } }; var command2 = new EpisodeSearchCommand { EpisodeIds = new List { 1 } }; CommandEqualityComparer.Instance.Equals(command1, command2).Should().BeTrue(); diff --git a/src/NzbDrone.Core.Test/Messaging/Commands/CommandExecutorFixture.cs b/src/NzbDrone.Core.Test/Messaging/Commands/CommandExecutorFixture.cs index 28ef04eb9..dddd0b483 100644 --- a/src/NzbDrone.Core.Test/Messaging/Commands/CommandExecutorFixture.cs +++ b/src/NzbDrone.Core.Test/Messaging/Commands/CommandExecutorFixture.cs @@ -212,13 +212,10 @@ public CommandA(int id = 0) public class CommandB : Command { - public CommandB() { - } public override string CompletionMessage => null; } - } diff --git a/src/NzbDrone.Core.Test/Messaging/Events/EventAggregatorFixture.cs b/src/NzbDrone.Core.Test/Messaging/Events/EventAggregatorFixture.cs index 2251915e8..d71b453fe 100644 --- a/src/NzbDrone.Core.Test/Messaging/Events/EventAggregatorFixture.cs +++ b/src/NzbDrone.Core.Test/Messaging/Events/EventAggregatorFixture.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using Moq; using NUnit.Framework; @@ -12,33 +12,31 @@ namespace NzbDrone.Core.Test.Messaging.Events [TestFixture] public class EventAggregatorFixture : TestBase { - private Mock> HandlerA1; - private Mock> HandlerA2; + private Mock> _handlerA1; + private Mock> _handlerA2; - private Mock> HandlerB1; - private Mock> HandlerB2; - - private Mock> AsyncHandlerA1; + private Mock> _handlerB1; + private Mock> _handlerB2; + private Mock> _asyncHandlerA1; [SetUp] public void Setup() { - HandlerA1 = new Mock>(); - HandlerA2 = new Mock>(); - HandlerB1 = new Mock>(); - HandlerB2 = new Mock>(); + _handlerA1 = new Mock>(); + _handlerA2 = new Mock>(); + _handlerB1 = new Mock>(); + _handlerB2 = new Mock>(); - AsyncHandlerA1 = new Mock>(); + _asyncHandlerA1 = new Mock>(); Mocker.GetMock() .Setup(c => c.BuildAll>()) - .Returns(new List> { HandlerA1.Object, HandlerA2.Object }); + .Returns(new List> { _handlerA1.Object, _handlerA2.Object }); Mocker.GetMock() .Setup(c => c.BuildAll>()) - .Returns(new List> { HandlerB1.Object, HandlerB2.Object }); - + .Returns(new List> { _handlerB1.Object, _handlerB2.Object }); } [Test] @@ -48,8 +46,8 @@ public void should_publish_event_to_handlers() Subject.PublishEvent(eventA); - HandlerA1.Verify(c => c.Handle(eventA), Times.Once()); - HandlerA2.Verify(c => c.Handle(eventA), Times.Once()); + _handlerA1.Verify(c => c.Handle(eventA), Times.Once()); + _handlerA2.Verify(c => c.Handle(eventA), Times.Once()); } [Test] @@ -57,35 +55,31 @@ public void should_not_publish_to_incompatible_handlers() { var eventA = new EventA(); - Subject.PublishEvent(eventA); - HandlerA1.Verify(c => c.Handle(eventA), Times.Once()); - HandlerA2.Verify(c => c.Handle(eventA), Times.Once()); + _handlerA1.Verify(c => c.Handle(eventA), Times.Once()); + _handlerA2.Verify(c => c.Handle(eventA), Times.Once()); - HandlerB1.Verify(c => c.Handle(It.IsAny()), Times.Never()); - HandlerB2.Verify(c => c.Handle(It.IsAny()), Times.Never()); + _handlerB1.Verify(c => c.Handle(It.IsAny()), Times.Never()); + _handlerB2.Verify(c => c.Handle(It.IsAny()), Times.Never()); } - [Test] public void broken_handler_should_not_effect_others_handler() { var eventA = new EventA(); - - HandlerA1.Setup(c => c.Handle(It.IsAny())) + _handlerA1.Setup(c => c.Handle(It.IsAny())) .Throws(new NotImplementedException()); Subject.PublishEvent(eventA); - HandlerA1.Verify(c => c.Handle(eventA), Times.Once()); - HandlerA2.Verify(c => c.Handle(eventA), Times.Once()); + _handlerA1.Verify(c => c.Handle(eventA), Times.Once()); + _handlerA2.Verify(c => c.Handle(eventA), Times.Once()); ExceptionVerification.ExpectedErrors(1); } - /* [Test] public void should_queue_multiple_async_events() { @@ -95,12 +89,12 @@ public void should_queue_multiple_async_events() var handlers = new List> { - AsyncHandlerA1.Object, AsyncHandlerA1.Object, AsyncHandlerA1.Object, AsyncHandlerA1.Object, AsyncHandlerA1.Object, - AsyncHandlerA1.Object, + AsyncHandlerA1.Object, + AsyncHandlerA1.Object, AsyncHandlerA1.Object, }; @@ -131,14 +125,11 @@ public void should_queue_multiple_async_events() }*/ } - public class EventA : IEvent { - } public class EventB : IEvent { - } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core.Test/MetadataSource/SkyHook/SkyHookProxyFixture.cs b/src/NzbDrone.Core.Test/MetadataSource/SkyHook/SkyHookProxyFixture.cs index e6178c0d2..82f90e9ab 100644 --- a/src/NzbDrone.Core.Test/MetadataSource/SkyHook/SkyHookProxyFixture.cs +++ b/src/NzbDrone.Core.Test/MetadataSource/SkyHook/SkyHookProxyFixture.cs @@ -64,6 +64,7 @@ private void ValidateSeries(Series series) series.Network.Should().NotBeNullOrWhiteSpace(); series.Runtime.Should().BeGreaterThan(0); series.TitleSlug.Should().NotBeNullOrWhiteSpace(); + //series.TvRageId.Should().BeGreaterThan(0); series.TvdbId.Should().BeGreaterThan(0); } diff --git a/src/NzbDrone.Core.Test/MetadataSource/SkyHook/SkyHookProxySearchFixture.cs b/src/NzbDrone.Core.Test/MetadataSource/SkyHook/SkyHookProxySearchFixture.cs index 1134911d2..171005dbc 100644 --- a/src/NzbDrone.Core.Test/MetadataSource/SkyHook/SkyHookProxySearchFixture.cs +++ b/src/NzbDrone.Core.Test/MetadataSource/SkyHook/SkyHookProxySearchFixture.cs @@ -26,6 +26,7 @@ public void Setup() [TestCase("Mr. D", "Mr. D")] [TestCase("Rob & Big", "Rob & Big")] [TestCase("M*A*S*H", "M*A*S*H")] + //[TestCase("imdb:tt0436992", "Doctor Who (2005)")] [TestCase("tvdb:78804", "Doctor Who (2005)")] [TestCase("tvdbid:78804", "Doctor Who (2005)")] @@ -64,14 +65,13 @@ public void should_return_existing_series_if_found(string term) { TvdbId = tvdbId }; - + Mocker.GetMock().Setup(c => c.FindByTvdbId(tvdbId)).Returns(existingSeries); var result = Subject.SearchForNewSeries("tvdbid: " + tvdbId); result.Should().Contain(existingSeries); result.Should().ContainSingle(c => c.TvdbId == tvdbId); - } } } diff --git a/src/NzbDrone.Core.Test/NotificationTests/NotificationBaseFixture.cs b/src/NzbDrone.Core.Test/NotificationTests/NotificationBaseFixture.cs index 6beb3e805..bed2c42b3 100644 --- a/src/NzbDrone.Core.Test/NotificationTests/NotificationBaseFixture.cs +++ b/src/NzbDrone.Core.Test/NotificationTests/NotificationBaseFixture.cs @@ -15,7 +15,7 @@ namespace NzbDrone.Core.Test.NotificationTests [TestFixture] public class NotificationBaseFixture : TestBase { - class TestSetting : IProviderConfig + private class TestSetting : IProviderConfig { public NzbDroneValidationResult Validate() { @@ -23,12 +23,11 @@ public NzbDroneValidationResult Validate() } } - class TestNotificationWithOnDownload : NotificationBase + private class TestNotificationWithOnDownload : NotificationBase { public override string Name => "TestNotification"; public override string Link => ""; - public override ValidationResult Test() { throw new NotImplementedException(); @@ -38,15 +37,13 @@ public override void OnDownload(DownloadMessage downloadMessage) { TestLogger.Info("OnDownload was called"); } - } - class TestNotificationWithAllEvents : NotificationBase + private class TestNotificationWithAllEvents : NotificationBase { public override string Name => "TestNotification"; public override string Link => ""; - public override ValidationResult Test() { throw new NotImplementedException(); @@ -66,14 +63,17 @@ public override void OnRename(Series series, List renamedFil { TestLogger.Info("OnRename was called"); } + public override void OnEpisodeFileDelete(EpisodeDeleteMessage message) { TestLogger.Info("Episode OnDelete was called"); } + public override void OnSeriesDelete(SeriesDeleteMessage deleteMessage) { TestLogger.Info("Series OnDelete was called"); } + public override void OnHealthIssue(NzbDrone.Core.HealthCheck.HealthCheck artist) { TestLogger.Info("OnHealthIssue was called"); @@ -83,21 +83,17 @@ public override void OnApplicationUpdate(ApplicationUpdateMessage updateMessage) { TestLogger.Info("OnApplicationUpdate was called"); } - } - class TestNotificationWithNoEvents : NotificationBase + private class TestNotificationWithNoEvents : NotificationBase { public override string Name => "TestNotification"; public override string Link => ""; - public override ValidationResult Test() { throw new NotImplementedException(); } - - } [Test] @@ -128,7 +124,6 @@ public void should_support_all_if_implemented() notification.SupportsOnApplicationUpdate.Should().BeTrue(); } - [Test] public void should_support_none_if_none_are_implemented() { @@ -145,5 +140,4 @@ public void should_support_none_if_none_are_implemented() notification.SupportsOnApplicationUpdate.Should().BeFalse(); } } - } diff --git a/src/NzbDrone.Core.Test/NotificationTests/ProwlProviderTest.cs b/src/NzbDrone.Core.Test/NotificationTests/ProwlProviderTest.cs index deac7d245..1ca0e52a3 100644 --- a/src/NzbDrone.Core.Test/NotificationTests/ProwlProviderTest.cs +++ b/src/NzbDrone.Core.Test/NotificationTests/ProwlProviderTest.cs @@ -30,7 +30,7 @@ public void Verify_should_throw_for_an_invalid_apiKey() _settings.ApiKey = _badApiKey; Assert.Throws(() => Subject.Test(_settings)); - + ExceptionVerification.ExpectedWarns(1); } @@ -51,4 +51,4 @@ public void SendNotification_should_log_a_warning_for_an_invalid_apiKey() ExceptionVerification.ExpectedWarns(1); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core.Test/NotificationTests/Xbmc/Json/GetSeriesPathFixture.cs b/src/NzbDrone.Core.Test/NotificationTests/Xbmc/Json/GetSeriesPathFixture.cs index a3d3962c7..a253468fb 100644 --- a/src/NzbDrone.Core.Test/NotificationTests/Xbmc/Json/GetSeriesPathFixture.cs +++ b/src/NzbDrone.Core.Test/NotificationTests/Xbmc/Json/GetSeriesPathFixture.cs @@ -61,7 +61,7 @@ private void GivenMatchingSeries() { TvdbId = 1000, Title = "Does not exist" - }; + }; } [Test] diff --git a/src/NzbDrone.Core.Test/NotificationTests/Xbmc/Json/UpdateFixture.cs b/src/NzbDrone.Core.Test/NotificationTests/Xbmc/Json/UpdateFixture.cs index 564778936..3ae9316b9 100644 --- a/src/NzbDrone.Core.Test/NotificationTests/Xbmc/Json/UpdateFixture.cs +++ b/src/NzbDrone.Core.Test/NotificationTests/Xbmc/Json/UpdateFixture.cs @@ -59,9 +59,9 @@ public void should_update_all_paths_when_series_path_not_found() .With(s => s.Title = "Not 30 Rock") .Build(); - Subject.Update(_settings, fakeSeries); + Subject.Update(_settings, fakeSeries); - Mocker.GetMock() + Mocker.GetMock() .Verify(v => v.UpdateLibrary(_settings, null), Times.Once()); } } diff --git a/src/NzbDrone.Core.Test/NotificationTests/Xbmc/OnDownloadFixture.cs b/src/NzbDrone.Core.Test/NotificationTests/Xbmc/OnDownloadFixture.cs index c43786614..53052ea88 100644 --- a/src/NzbDrone.Core.Test/NotificationTests/Xbmc/OnDownloadFixture.cs +++ b/src/NzbDrone.Core.Test/NotificationTests/Xbmc/OnDownloadFixture.cs @@ -15,7 +15,7 @@ namespace NzbDrone.Core.Test.NotificationTests.Xbmc public class OnDownloadFixture : CoreTest { private DownloadMessage _downloadMessage; - + [SetUp] public void Setup() { diff --git a/src/NzbDrone.Core.Test/OrganizerTests/BuildFilePathFixture.cs b/src/NzbDrone.Core.Test/OrganizerTests/BuildFilePathFixture.cs index 3dc61cc9b..a2b9280ec 100644 --- a/src/NzbDrone.Core.Test/OrganizerTests/BuildFilePathFixture.cs +++ b/src/NzbDrone.Core.Test/OrganizerTests/BuildFilePathFixture.cs @@ -14,15 +14,15 @@ namespace NzbDrone.Core.Test.OrganizerTests public class BuildFilePathFixture : CoreTest { - private NamingConfig namingConfig; + private NamingConfig _namingConfig; [SetUp] public void Setup() { - namingConfig = NamingConfig.Default; + _namingConfig = NamingConfig.Default; Mocker.GetMock() - .Setup(c => c.GetConfig()).Returns(namingConfig); + .Setup(c => c.GetConfig()).Returns(_namingConfig); } [Test] @@ -50,8 +50,8 @@ public void CalculateFilePath_SeasonFolder_SingleNumber(string filename, int sea .With(s => s.SceneName = filename) .Build(); - namingConfig.SeasonFolderFormat = seasonFolderFormat; - namingConfig.SpecialsFolderFormat = "MySpecials"; + _namingConfig.SeasonFolderFormat = seasonFolderFormat; + _namingConfig.SpecialsFolderFormat = "MySpecials"; Subject.BuildFilePath(fakeEpisodes, fakeSeries, fakeEpisodeFile, ".mkv").Should().Be(expectedPath.AsOsAgnostic()); } @@ -79,9 +79,9 @@ public void should_clean_season_folder_when_it_contains_illegal_characters_in_se .With(s => s.SceneName = filename) .Build(); - namingConfig.SeasonFolderFormat = "{Series Title} Season {season:0}"; - + _namingConfig.SeasonFolderFormat = "{Series Title} Season {season:0}"; + Subject.BuildFilePath(fakeEpisodes, fakeSeries, fakeEpisodeFile, ".mkv").Should().Be(expectedPath.AsOsAgnostic()); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core.Test/OrganizerTests/FileNameBuilderTests/CleanTitleFixture.cs b/src/NzbDrone.Core.Test/OrganizerTests/FileNameBuilderTests/CleanTitleFixture.cs index f6aabeb9d..7d5520ade 100644 --- a/src/NzbDrone.Core.Test/OrganizerTests/FileNameBuilderTests/CleanTitleFixture.cs +++ b/src/NzbDrone.Core.Test/OrganizerTests/FileNameBuilderTests/CleanTitleFixture.cs @@ -65,6 +65,7 @@ public void Setup() [TestCase("[a] title", "a title")] [TestCase("backslash \\ backlash", "backslash backlash")] [TestCase("I'm the Boss", "Im the Boss")] + //[TestCase("", "")] public void should_get_expected_title_back(string title, string expected) { diff --git a/src/NzbDrone.Core.Test/OrganizerTests/FileNameBuilderTests/EpisodeTitleCollapseFixture.cs b/src/NzbDrone.Core.Test/OrganizerTests/FileNameBuilderTests/EpisodeTitleCollapseFixture.cs index f4da13b5b..6de46e0e7 100644 --- a/src/NzbDrone.Core.Test/OrganizerTests/FileNameBuilderTests/EpisodeTitleCollapseFixture.cs +++ b/src/NzbDrone.Core.Test/OrganizerTests/FileNameBuilderTests/EpisodeTitleCollapseFixture.cs @@ -29,11 +29,9 @@ public void Setup() .With(s => s.Title = "South Park") .Build(); - _namingConfig = NamingConfig.Default; _namingConfig.RenameEpisodes = true; - Mocker.GetMock() .Setup(c => c.GetConfig()).Returns(_namingConfig); @@ -65,7 +63,6 @@ public void Setup() .Returns(v => Quality.DefaultQualityDefinitions.First(c => c.Quality == v)); } - [TestCase("Hey, Baby, What's Wrong (1)", "Hey, Baby, What's Wrong (2)", "Hey, Baby, What's Wrong")] [TestCase("Meet the Guys and Girls of Cycle 20 Part 1", "Meet the Guys and Girls of Cycle 20 Part 2", "Meet the Guys and Girls of Cycle 20")] [TestCase("Meet the Guys and Girls of Cycle 20 Part1", "Meet the Guys and Girls of Cycle 20 Part2", "Meet the Guys and Girls of Cycle 20")] diff --git a/src/NzbDrone.Core.Test/OrganizerTests/FileNameBuilderTests/FileNameBuilderFixture.cs b/src/NzbDrone.Core.Test/OrganizerTests/FileNameBuilderTests/FileNameBuilderFixture.cs index 07e9c2b39..646db8634 100644 --- a/src/NzbDrone.Core.Test/OrganizerTests/FileNameBuilderTests/FileNameBuilderFixture.cs +++ b/src/NzbDrone.Core.Test/OrganizerTests/FileNameBuilderTests/FileNameBuilderFixture.cs @@ -34,11 +34,9 @@ public void Setup() .With(s => s.Title = "South Park") .Build(); - _namingConfig = NamingConfig.Default; _namingConfig.RenameEpisodes = true; - Mocker.GetMock() .Setup(c => c.GetConfig()).Returns(_namingConfig); @@ -50,7 +48,7 @@ public void Setup() .Build(); _episodeFile = new EpisodeFile { Quality = new QualityModel(Quality.HDTV720p), ReleaseGroup = "SonarrTest" }; - + Mocker.GetMock() .Setup(v => v.Get(Moq.It.IsAny())) .Returns(v => Quality.DefaultQualityDefinitions.First(c => c.Quality == v)); @@ -71,7 +69,7 @@ public void should_replace_Series_space_Title() { _namingConfig.StandardEpisodeFormat = "{Series Title}"; - Subject.BuildFileName(new List {_episode1}, _series, _episodeFile) + Subject.BuildFileName(new List { _episode1 }, _series, _episodeFile) .Should().Be("South Park"); } @@ -80,7 +78,7 @@ public void should_replace_Series_underscore_Title() { _namingConfig.StandardEpisodeFormat = "{Series_Title}"; - Subject.BuildFileName(new List {_episode1}, _series, _episodeFile) + Subject.BuildFileName(new List { _episode1 }, _series, _episodeFile) .Should().Be("South_Park"); } @@ -89,7 +87,7 @@ public void should_replace_Series_dot_Title() { _namingConfig.StandardEpisodeFormat = "{Series.Title}"; - Subject.BuildFileName(new List {_episode1}, _series, _episodeFile) + Subject.BuildFileName(new List { _episode1 }, _series, _episodeFile) .Should().Be("South.Park"); } @@ -98,7 +96,7 @@ public void should_replace_Series_dash_Title() { _namingConfig.StandardEpisodeFormat = "{Series-Title}"; - Subject.BuildFileName(new List {_episode1}, _series, _episodeFile) + Subject.BuildFileName(new List { _episode1 }, _series, _episodeFile) .Should().Be("South-Park"); } @@ -107,7 +105,7 @@ public void should_replace_SERIES_TITLE_with_all_caps() { _namingConfig.StandardEpisodeFormat = "{SERIES TITLE}"; - Subject.BuildFileName(new List {_episode1}, _series, _episodeFile) + Subject.BuildFileName(new List { _episode1 }, _series, _episodeFile) .Should().Be("SOUTH PARK"); } @@ -125,7 +123,7 @@ public void should_replace_series_title_with_all_lower_case() { _namingConfig.StandardEpisodeFormat = "{series title}"; - Subject.BuildFileName(new List {_episode1}, _series, _episodeFile) + Subject.BuildFileName(new List { _episode1 }, _series, _episodeFile) .Should().Be("south park"); } @@ -144,7 +142,7 @@ public void should_replace_episode_title() { _namingConfig.StandardEpisodeFormat = "{Episode Title}"; - Subject.BuildFileName(new List {_episode1}, _series, _episodeFile) + Subject.BuildFileName(new List { _episode1 }, _series, _episodeFile) .Should().Be("City Sushi"); } @@ -231,10 +229,10 @@ public void should_replace_all_contents_in_pattern() { _namingConfig.StandardEpisodeFormat = "{Series Title} - S{season:00}E{episode:00} - {Episode Title} [{Quality Title}]"; - Subject.BuildFileName(new List {_episode1}, _series, _episodeFile) + Subject.BuildFileName(new List { _episode1 }, _series, _episodeFile) .Should().Be("South Park - S15E06 - City Sushi [HDTV-720p]"); } - + [TestCase("Some Escaped {{ String", "Some Escaped { String")] [TestCase("Some Escaped }} String", "Some Escaped } String")] [TestCase("Some Escaped {{Series Title}} String", "Some Escaped {Series Title} String")] @@ -392,7 +390,6 @@ public void should_trim_periods_from_end_of_episode_title() .With(e => e.EpisodeNumber = 6) .Build(); - Subject.BuildFileName(new List { episode }, new Series { Title = "30 Rock" }, _episodeFile) .Should().Be("30 Rock - S06E06 - Part 1"); } @@ -409,7 +406,6 @@ public void should_trim_question_marks_from_end_of_episode_title() .With(e => e.EpisodeNumber = 6) .Build(); - Subject.BuildFileName(new List { episode }, new Series { Title = "30 Rock" }, _episodeFile) .Should().Be("30 Rock - S06E06 - Part 1"); } @@ -520,7 +516,7 @@ public void should_use_standard_naming_when_anime_episode_has_no_absolute_number public void should_include_affixes_if_value_not_empty() { _namingConfig.StandardEpisodeFormat = "{Series.Title}.S{season:00}E{episode:00}{_Episode.Title_}{Quality.Title}"; - + Subject.BuildFileName(new List { _episode1 }, _series, _episodeFile) .Should().Be("South.Park.S15E06_City.Sushi_HDTV-720p"); } @@ -835,10 +831,8 @@ public void should_format_audio_languages(string audioLanguages, string expected GivenMediaInfoModel(audioLanguages: audioLanguages); - _namingConfig.StandardEpisodeFormat = "{MediaInfo AudioLanguages}"; - Subject.BuildFileName(new List { _episode1 }, _series, _episodeFile) .Should().Be(expected); } @@ -851,10 +845,8 @@ public void should_format_audio_languages_all(string audioLanguages, string expe GivenMediaInfoModel(audioLanguages: audioLanguages); - _namingConfig.StandardEpisodeFormat = "{MediaInfo AudioLanguagesAll}"; - Subject.BuildFileName(new List { _episode1 }, _series, _episodeFile) .Should().Be(expected); } @@ -874,9 +866,7 @@ public void should_format_subtitle_languages_all(string subtitleLanguages, strin GivenMediaInfoModel(subtitles: subtitleLanguages); - - _namingConfig.StandardEpisodeFormat = "{MediaInfo SubtitleLanguages" + format +"}End"; - + _namingConfig.StandardEpisodeFormat = "{MediaInfo SubtitleLanguages" + format + "}End"; Subject.BuildFileName(new List { _episode1 }, _series, _episodeFile) .Should().Be(expected + "End"); @@ -886,15 +876,17 @@ public void should_format_subtitle_languages_all(string subtitleLanguages, strin [TestCase(10, "BT.2020", "PQ", "South.Park.S15E06.City.Sushi.HDR")] [TestCase(10, "BT.2020", "HLG", "South.Park.S15E06.City.Sushi.HDR")] [TestCase(0, null, null, "South.Park.S15E06.City.Sushi")] - public void should_include_hdr_for_mediainfo_videodynamicrange_with_valid_properties(int bitDepth, string colourPrimaries, - string transferCharacteristics, string expectedName) + public void should_include_hdr_for_mediainfo_videodynamicrange_with_valid_properties(int bitDepth, + string colourPrimaries, + string transferCharacteristics, + string expectedName) { _namingConfig.StandardEpisodeFormat = "{Series.Title}.S{season:00}E{episode:00}.{Episode.Title}.{MediaInfo VideoDynamicRange}"; GivenMediaInfoModel(videoBitDepth: bitDepth, videoColourPrimaries: colourPrimaries, videoTransferCharacteristics: transferCharacteristics); - Subject.BuildFileName(new List {_episode1}, _series, _episodeFile) + Subject.BuildFileName(new List { _episode1 }, _series, _episodeFile) .Should().Be(expectedName); } @@ -906,7 +898,7 @@ public void should_update_media_info_if_token_configured_and_revision_is_old() GivenMediaInfoModel(schemaRevision: 3); - Subject.BuildFileName(new List {_episode1}, _series, _episodeFile); + Subject.BuildFileName(new List { _episode1 }, _series, _episodeFile); Mocker.GetMock().Verify(v => v.Update(_episodeFile, _series), Times.Once()); } @@ -933,7 +925,7 @@ public void should_not_update_media_info_if_token_not_configured_and_revision_is GivenMediaInfoModel(schemaRevision: 3); - Subject.BuildFileName(new List {_episode1}, _series, _episodeFile); + Subject.BuildFileName(new List { _episode1 }, _series, _episodeFile); Mocker.GetMock().Verify(v => v.Update(_episodeFile, _series), Times.Never()); } @@ -946,11 +938,11 @@ public void should_not_update_media_info_if_token_configured_and_revision_is_cur GivenMediaInfoModel(schemaRevision: 5); - Subject.BuildFileName(new List {_episode1}, _series, _episodeFile); + Subject.BuildFileName(new List { _episode1 }, _series, _episodeFile); Mocker.GetMock().Verify(v => v.Update(_episodeFile, _series), Times.Never()); } - + [Test] public void should_not_update_media_info_if_token_configured_and_revision_is_newer() { @@ -959,7 +951,7 @@ public void should_not_update_media_info_if_token_configured_and_revision_is_new GivenMediaInfoModel(schemaRevision: 8); - Subject.BuildFileName(new List {_episode1}, _series, _episodeFile); + Subject.BuildFileName(new List { _episode1 }, _series, _episodeFile); Mocker.GetMock().Verify(v => v.Update(_episodeFile, _series), Times.Never()); } @@ -987,15 +979,20 @@ public void should_use_updated_media_info_if_token_configured_and_revision_is_ol SchemaRevision = 5 }); - var result = Subject.BuildFileName(new List {_episode1}, _series, _episodeFile); + var result = Subject.BuildFileName(new List { _episode1 }, _series, _episodeFile); result.Should().EndWith("HDR"); - } - - private void GivenMediaInfoModel(string videoCodec = "AVC", string audioCodec = "DTS", int audioChannels = 6, int videoBitDepth = 8, - string videoColourPrimaries = "", string videoTransferCharacteristics = "", string audioLanguages = "English", - string subtitles = "English/Spanish/Italian", int schemaRevision = 5) + + private void GivenMediaInfoModel(string videoCodec = "AVC", + string audioCodec = "DTS", + int audioChannels = 6, + int videoBitDepth = 8, + string videoColourPrimaries = "", + string videoTransferCharacteristics = "", + string audioLanguages = "English", + string subtitles = "English/Spanish/Italian", + int schemaRevision = 5) { _episodeFile.MediaInfo = new MediaInfoModel { @@ -1009,7 +1006,6 @@ private void GivenMediaInfoModel(string videoCodec = "AVC", string audioCodec = VideoTransferCharacteristics = videoTransferCharacteristics, SchemaRevision = schemaRevision }; - } } } diff --git a/src/NzbDrone.Core.Test/OrganizerTests/FileNameBuilderTests/MultiEpisodeFixture.cs b/src/NzbDrone.Core.Test/OrganizerTests/FileNameBuilderTests/MultiEpisodeFixture.cs index fd02cf413..896a8cf20 100644 --- a/src/NzbDrone.Core.Test/OrganizerTests/FileNameBuilderTests/MultiEpisodeFixture.cs +++ b/src/NzbDrone.Core.Test/OrganizerTests/FileNameBuilderTests/MultiEpisodeFixture.cs @@ -30,11 +30,9 @@ public void Setup() .With(s => s.Title = "South Park") .Build(); - _namingConfig = NamingConfig.Default; _namingConfig.RenameEpisodes = true; - Mocker.GetMock() .Setup(c => c.GetConfig()).Returns(_namingConfig); @@ -60,7 +58,7 @@ public void Setup() .Build(); _episodeFile = new EpisodeFile { Quality = new QualityModel(Quality.HDTV720p), ReleaseGroup = "SonarrTest" }; - + Mocker.GetMock() .Setup(v => v.Get(Moq.It.IsAny())) .Returns(v => Quality.DefaultQualityDefinitions.First(c => c.Quality == v)); @@ -76,7 +74,7 @@ public void should_replace_Series_space_Title() { _namingConfig.StandardEpisodeFormat = "{Series Title}"; - Subject.BuildFileName(new List {_episode1}, _series, _episodeFile) + Subject.BuildFileName(new List { _episode1 }, _series, _episodeFile) .Should().Be("South Park"); } @@ -86,7 +84,7 @@ public void should_format_extend_multi_episode_properly() _namingConfig.StandardEpisodeFormat = "{Series Title} - S{season:00}E{episode:00} - {Episode Title}"; _namingConfig.MultiEpisodeStyle = 0; - Subject.BuildFileName(new List {_episode1, _episode2}, _series, _episodeFile) + Subject.BuildFileName(new List { _episode1, _episode2 }, _series, _episodeFile) .Should().Be("South Park - S15E06-07 - City Sushi"); } @@ -146,7 +144,7 @@ public void should_get_proper_filename_when_multi_episode_is_duplicated_and_brac { _namingConfig.StandardEpisodeFormat = "{Series Title} - S{season:00}E{episode:00} - ({Quality Title}, {MediaInfo Full}, {Release Group}) - {Episode Title}"; - _namingConfig.MultiEpisodeStyle = (int) MultiEpisodeStyle.Duplicate; + _namingConfig.MultiEpisodeStyle = (int)MultiEpisodeStyle.Duplicate; Subject.BuildFileName(new List { _episode1, _episode2 }, _series, _episodeFile) .Should().Be("South Park - S15E06 - S15E07 - (HDTV-720p, , SonarrTest) - City Sushi"); diff --git a/src/NzbDrone.Core.Test/OrganizerTests/FileNameBuilderTests/MultiEpisodeTitleFixture.cs b/src/NzbDrone.Core.Test/OrganizerTests/FileNameBuilderTests/MultiEpisodeTitleFixture.cs index 2493ddf94..503067c10 100644 --- a/src/NzbDrone.Core.Test/OrganizerTests/FileNameBuilderTests/MultiEpisodeTitleFixture.cs +++ b/src/NzbDrone.Core.Test/OrganizerTests/FileNameBuilderTests/MultiEpisodeTitleFixture.cs @@ -29,11 +29,9 @@ public void Setup() .With(s => s.Title = "South Park") .Build(); - _namingConfig = NamingConfig.Default; _namingConfig.RenameEpisodes = true; - Mocker.GetMock() .Setup(c => c.GetConfig()).Returns(_namingConfig); @@ -52,7 +50,7 @@ public void Setup() .Build(); _episodeFile = new EpisodeFile { Quality = new QualityModel(Quality.HDTV720p), ReleaseGroup = "SonarrTest" }; - + Mocker.GetMock() .Setup(v => v.Get(Moq.It.IsAny())) .Returns(v => Quality.DefaultQualityDefinitions.First(c => c.Quality == v)); @@ -73,7 +71,7 @@ public void should_replace_Series_space_Title(string firstTitle, string secondTi _namingConfig.StandardEpisodeFormat = "{Episode Title} {Quality Full}"; - Subject.BuildFileName(new List {_episode1, _episode2}, _series, _episodeFile) + Subject.BuildFileName(new List { _episode1, _episode2 }, _series, _episodeFile) .Should().Be("Episode Title HDTV-720p"); } } diff --git a/src/NzbDrone.Core.Test/OrganizerTests/FileNameBuilderTests/OriginalTitleFixture.cs b/src/NzbDrone.Core.Test/OrganizerTests/FileNameBuilderTests/OriginalTitleFixture.cs index f4f1e0994..67d7aeaec 100644 --- a/src/NzbDrone.Core.Test/OrganizerTests/FileNameBuilderTests/OriginalTitleFixture.cs +++ b/src/NzbDrone.Core.Test/OrganizerTests/FileNameBuilderTests/OriginalTitleFixture.cs @@ -67,7 +67,7 @@ public void should_include_current_filename_if_not_renaming_files() Subject.BuildFileName(new List { _episode }, _series, _episodeFile) .Should().Be("my.series.s15e06"); } - + [Test] public void should_include_current_filename_if_not_including_season_and_episode_tokens_for_standard_series() { diff --git a/src/NzbDrone.Core.Test/OrganizerTests/FileNameBuilderTests/PreferredWordsFixture.cs b/src/NzbDrone.Core.Test/OrganizerTests/FileNameBuilderTests/PreferredWordsFixture.cs index 64287d854..ba41b4edf 100644 --- a/src/NzbDrone.Core.Test/OrganizerTests/FileNameBuilderTests/PreferredWordsFixture.cs +++ b/src/NzbDrone.Core.Test/OrganizerTests/FileNameBuilderTests/PreferredWordsFixture.cs @@ -1,4 +1,6 @@ -using FizzWare.NBuilder; +using System.Collections.Generic; +using System.Linq; +using FizzWare.NBuilder; using FluentAssertions; using NUnit.Framework; using NzbDrone.Core.MediaFiles; @@ -7,11 +9,6 @@ using NzbDrone.Core.Qualities; using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Tv; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace NzbDrone.Core.Test.OrganizerTests.FileNameBuilderTests { @@ -34,11 +31,9 @@ public void Setup() .With(s => s.Title = "South Park") .Build(); - _namingConfig = NamingConfig.Default; _namingConfig.RenameEpisodes = true; - Mocker.GetMock() .Setup(c => c.GetConfig()).Returns(_namingConfig); @@ -51,12 +46,15 @@ public void Setup() _episodeFile = new EpisodeFile { Quality = new QualityModel(Quality.HDTV720p), ReleaseGroup = "SonarrTest" }; - _preferredWords = new PreferredWordMatchResults() { - All = new List() { + _preferredWords = new PreferredWordMatchResults() + { + All = new List() + { "x265", "extended" }, - ByReleaseProfile = new Dictionary>() { + ByReleaseProfile = new Dictionary>() + { { "CodecProfile", new List() diff --git a/src/NzbDrone.Core.Test/OrganizerTests/FileNameBuilderTests/ReplaceCharacterFixure.cs b/src/NzbDrone.Core.Test/OrganizerTests/FileNameBuilderTests/ReplaceCharacterFixure.cs index cd94a452a..674e7da09 100644 --- a/src/NzbDrone.Core.Test/OrganizerTests/FileNameBuilderTests/ReplaceCharacterFixure.cs +++ b/src/NzbDrone.Core.Test/OrganizerTests/FileNameBuilderTests/ReplaceCharacterFixure.cs @@ -50,18 +50,17 @@ public void Setup() // { "\\", "/", "<", ">", "?", "*", ":", "|", "\"" }; // { "+", "+", "", "", "!", "-", " -", "", "" }; - - [TestCase("CSI: Crime Scene Investigation", "CSI - Crime Scene Investigation")] - [TestCase("Code:Breaker", "Code-Breaker")] - [TestCase("Back Slash\\", "Back Slash+")] - [TestCase("Forward Slash/", "Forward Slash+")] - [TestCase("Greater Than>", "Greater Than")] - [TestCase("Less Than<", "Less Than")] - [TestCase("Question Mark?", "Question Mark!")] - [TestCase("Aster*sk", "Aster-sk")] - [TestCase("Colon: Two Periods", "Colon - Two Periods")] - [TestCase("Pipe|", "Pipe")] - [TestCase("Quotes\"", "Quotes")] + [TestCase("CSI: Crime Scene Investigation", "CSI - Crime Scene Investigation")] + [TestCase("Code:Breaker", "Code-Breaker")] + [TestCase("Back Slash\\", "Back Slash+")] + [TestCase("Forward Slash/", "Forward Slash+")] + [TestCase("Greater Than>", "Greater Than")] + [TestCase("Less Than<", "Less Than")] + [TestCase("Question Mark?", "Question Mark!")] + [TestCase("Aster*sk", "Aster-sk")] + [TestCase("Colon: Two Periods", "Colon - Two Periods")] + [TestCase("Pipe|", "Pipe")] + [TestCase("Quotes\"", "Quotes")] public void should_replace_illegal_characters(string title, string expected) { _series.Title = title; diff --git a/src/NzbDrone.Core.Test/OrganizerTests/FileNameBuilderTests/ReservedDeviceNameFixture.cs b/src/NzbDrone.Core.Test/OrganizerTests/FileNameBuilderTests/ReservedDeviceNameFixture.cs index 63e2dd4dd..2d8176d8b 100644 --- a/src/NzbDrone.Core.Test/OrganizerTests/FileNameBuilderTests/ReservedDeviceNameFixture.cs +++ b/src/NzbDrone.Core.Test/OrganizerTests/FileNameBuilderTests/ReservedDeviceNameFixture.cs @@ -34,11 +34,9 @@ public void Setup() .With(s => s.Title = "South Park") .Build(); - _namingConfig = NamingConfig.Default; _namingConfig.RenameEpisodes = true; - Mocker.GetMock() .Setup(c => c.GetConfig()).Returns(_namingConfig); diff --git a/src/NzbDrone.Core.Test/OrganizerTests/FileNameBuilderTests/TruncatedEpisodeTitlesFixture.cs b/src/NzbDrone.Core.Test/OrganizerTests/FileNameBuilderTests/TruncatedEpisodeTitlesFixture.cs index cb4caa445..74bc4ba73 100644 --- a/src/NzbDrone.Core.Test/OrganizerTests/FileNameBuilderTests/TruncatedEpisodeTitlesFixture.cs +++ b/src/NzbDrone.Core.Test/OrganizerTests/FileNameBuilderTests/TruncatedEpisodeTitlesFixture.cs @@ -28,11 +28,9 @@ public void Setup() .With(s => s.Title = "Series Title") .Build(); - _namingConfig = NamingConfig.Default; _namingConfig.RenameEpisodes = true; - Mocker.GetMock() .Setup(c => c.GetConfig()).Returns(_namingConfig); @@ -82,7 +80,7 @@ public void Setup() }; _episodeFile = new EpisodeFile { Quality = new QualityModel(Quality.HDTV720p), ReleaseGroup = "SonarrTest" }; - + Mocker.GetMock() .Setup(v => v.Get(Moq.It.IsAny())) .Returns(v => Quality.DefaultQualityDefinitions.First(c => c.Quality == v)); @@ -97,7 +95,7 @@ private void GivenProper() public void should_truncate_with_extension() { _series.Title = "The Fantastic Life of Mr. Sisko"; - + _episodes[0].SeasonNumber = 2; _episodes[0].EpisodeNumber = 18; _episodes[0].Title = "This title has to be 197 characters in length, combined with the series title, quality and episode number it becomes 254ish and the extension puts it above the 255 limit and triggers the truncation"; @@ -137,7 +135,7 @@ public void should_truncate_first_episode_title_with_ellipsis_if_only_partially_ _series.Title = "Lorem ipsum dolor sit amet, consectetur adipiscing elit Maecenas et magna sem Morbi vitae volutpat quam, id porta arcu Orci varius natoque penatibus et magnis dis parturient montes nascetur ridiculus musu Cras vestibulum"; _namingConfig.StandardEpisodeFormat = "{Series Title} - S{season:00}E{episode:00} - {Episode Title} {Quality Full}"; - var result = Subject.BuildFileName(new List{_episodes.First()}, _series, _episodeFile); + var result = Subject.BuildFileName(new List { _episodes.First() }, _series, _episodeFile); result.Length.Should().BeLessOrEqualTo(255); result.Should().Be("Lorem ipsum dolor sit amet, consectetur adipiscing elit Maecenas et magna sem Morbi vitae volutpat quam, id porta arcu Orci varius natoque penatibus et magnis dis parturient montes nascetur ridiculus musu Cras vestibulum - S01E01 - Episode Ti... HDTV-720p"); } @@ -147,7 +145,7 @@ public void should_truncate_titles_measuring_series_title_bytes() { _series.Title = "Lor\u00E9m ipsum dolor sit amet, consectetur adipiscing elit Maecenas et magna sem Morbi vitae volutpat quam, id porta arcu Orci varius natoque penatibus et magnis dis parturient montes nascetur ridiculus musu Cras vestibulum"; _namingConfig.StandardEpisodeFormat = "{Series Title} - S{season:00}E{episode:00} - {Episode Title} {Quality Full}"; - + var result = Subject.BuildFileName(new List { _episodes.First() }, _series, _episodeFile); result.GetByteCount().Should().BeLessOrEqualTo(255); diff --git a/src/NzbDrone.Core.Test/OrganizerTests/GetSeasonFolderFixture.cs b/src/NzbDrone.Core.Test/OrganizerTests/GetSeasonFolderFixture.cs index 0ddb369d0..c903585a9 100644 --- a/src/NzbDrone.Core.Test/OrganizerTests/GetSeasonFolderFixture.cs +++ b/src/NzbDrone.Core.Test/OrganizerTests/GetSeasonFolderFixture.cs @@ -9,15 +9,15 @@ namespace NzbDrone.Core.Test.OrganizerTests [TestFixture] public class GetSeasonFolderFixture : CoreTest { - private NamingConfig namingConfig; + private NamingConfig _namingConfig; [SetUp] public void Setup() { - namingConfig = NamingConfig.Default; + _namingConfig = NamingConfig.Default; Mocker.GetMock() - .Setup(c => c.GetConfig()).Returns(namingConfig); + .Setup(c => c.GetConfig()).Returns(_namingConfig); } [TestCase("Venture Bros.", 1, "{Series.Title}.{season:00}", "Venture.Bros.01")] @@ -25,11 +25,11 @@ public void Setup() [TestCase("Series Title?", 1, "{Series Title} Season {season:00}", "Series Title! Season 01")] public void should_use_seriesFolderFormat_to_build_folder_name(string seriesTitle, int seasonNumber, string format, string expected) { - namingConfig.SeasonFolderFormat = format; + _namingConfig.SeasonFolderFormat = format; var series = new Series { Title = seriesTitle }; - Subject.GetSeasonFolder(series, seasonNumber, namingConfig).Should().Be(expected); + Subject.GetSeasonFolder(series, seasonNumber, _namingConfig).Should().Be(expected); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core.Test/OrganizerTests/GetSeriesFolderFixture.cs b/src/NzbDrone.Core.Test/OrganizerTests/GetSeriesFolderFixture.cs index 9cf0b5e01..881f7bd93 100644 --- a/src/NzbDrone.Core.Test/OrganizerTests/GetSeriesFolderFixture.cs +++ b/src/NzbDrone.Core.Test/OrganizerTests/GetSeriesFolderFixture.cs @@ -10,15 +10,15 @@ namespace NzbDrone.Core.Test.OrganizerTests public class GetSeriesFolderFixture : CoreTest { - private NamingConfig namingConfig; + private NamingConfig _namingConfig; [SetUp] public void Setup() { - namingConfig = NamingConfig.Default; + _namingConfig = NamingConfig.Default; Mocker.GetMock() - .Setup(c => c.GetConfig()).Returns(namingConfig); + .Setup(c => c.GetConfig()).Returns(_namingConfig); } [TestCase("30 Rock", "{Series Title}", "30 Rock")] @@ -29,11 +29,11 @@ public void Setup() [TestCase("30 Rock", ".{Series.Title}.", "30.Rock")] public void should_use_seriesFolderFormat_to_build_folder_name(string seriesTitle, string format, string expected) { - namingConfig.SeriesFolderFormat = format; + _namingConfig.SeriesFolderFormat = format; var series = new Series { Title = seriesTitle }; Subject.GetSeriesFolder(series).Should().Be(expected); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core.Test/ParserTests/AbsoluteEpisodeNumberParserFixture.cs b/src/NzbDrone.Core.Test/ParserTests/AbsoluteEpisodeNumberParserFixture.cs index 5f332bb90..734c785fb 100644 --- a/src/NzbDrone.Core.Test/ParserTests/AbsoluteEpisodeNumberParserFixture.cs +++ b/src/NzbDrone.Core.Test/ParserTests/AbsoluteEpisodeNumberParserFixture.cs @@ -5,7 +5,6 @@ namespace NzbDrone.Core.Test.ParserTests { - [TestFixture] public class AbsoluteEpisodeNumberParserFixture : CoreTest { @@ -47,6 +46,7 @@ public class AbsoluteEpisodeNumberParserFixture : CoreTest [TestCase("Initial_Series_Title_-_03(DVD)_-_(Central_Anime)[629BD592].mkv", "Initial Series Title", 3, 0, 0)] [TestCase("Initial_Series_Title - 14 DVD - Central Anime", "Initial Series Title", 14, 0, 0)] [TestCase("Initial_Series_Title_-_14(DVD)_-_(Central_Anime)[0183D922].mkv", "Initial Series Title", 14, 0, 0)] + // [TestCase("Initial D - 4th Stage Ep 01.mkv", "Initial D - 4th Stage", 1, 0, 0)] [TestCase("[ChihiroDesuYo].Series.Title.-.09.1280x720.10bit.AAC.[24CCE81D]", "Series Title", 9, 0, 0)] [TestCase("Series Title - 001 - Fairy Tail", "Series Title", 001, 0, 0)] @@ -54,6 +54,7 @@ public class AbsoluteEpisodeNumberParserFixture : CoreTest [TestCase("Series Title - 050 - Special Request Watch Out for the Guy You Like!", "Series Title", 050, 0, 0)] [TestCase("Series Title - 099 - Natsu vs. Gildarts", "Series Title", 099, 0, 0)] [TestCase("Series Title - 100 - Mest", "Series Title", 100, 0, 0)] + // [TestCase("Fairy Tail - 101 - Mest", "Fairy Tail", 101, 0, 0)] //This gets caught up in the 'see' numbering [TestCase("[Exiled-Destiny] Series Title Ep01 (D2201EC5).mkv", "Series Title", 1, 0, 0)] [TestCase("[Commie] Series Title - 23 [5396CA24].mkv", "Series Title", 23, 0, 0)] @@ -77,6 +78,7 @@ public class AbsoluteEpisodeNumberParserFixture : CoreTest [TestCase("Series Title (2014) - 39 (137) [v2][720p.HDTV][Unison Fansub]", "Series Title (2014)", 39, 0, 0)] [TestCase("[HorribleSubs] Series Title 21 - 101 [480p].mkv", "Series Title 21", 101, 0, 0)] [TestCase("[Cthuyuu].Series.Title.-.03.[720p.H264.AAC][8AD82C3A]", "Series Title", 3, 0, 0)] + //[TestCase("Series.Title.-.03.(1280x720.HEVC.AAC)", "Series Title", 3, 0, 0)] [TestCase("[Cthuyuu] Series Title - 03 [720p H264 AAC][8AD82C3A]", "Series Title", 3, 0, 0)] [TestCase("Series Title Episode 56 [VOSTFR V2][720p][AAC]-Mystic Z-Team", "Series Title", 56, 0, 0)] @@ -110,6 +112,7 @@ public class AbsoluteEpisodeNumberParserFixture : CoreTest [TestCase("Anime Title S21 999", "Anime Title S21", 999, 0, 0)] [TestCase("Anime Title S21 1000", "Anime Title S21", 1000, 0, 0)] [TestCase("[HatSubs] Anime Title 1004 [E63F2984].mkv", "Anime Title", 1004, 0, 0)] + //[TestCase("", "", 0, 0, 0)] public void should_parse_absolute_numbers(string postTitle, string title, int absoluteEpisodeNumber, int seasonNumber, int episodeNumber) { @@ -147,14 +150,15 @@ public void should_parse_absolute_specials(string postTitle, string title, int a [TestCase("Some Anime Show (2011) Episode 99-100 [1080p] [Dual.Audio] [x265]", "Some Anime Show (2011)", 99, 100)] [TestCase("Some Anime Show 1-13 (English Dub) [720p]", "Some Anime Show", 1, 13)] [TestCase("Series.Title.Ep01-12.Complete.English.AC3.DL.1080p.BluRay.x264", "Series Title", 1, 12)] - [TestCase("[Judas] Some Anime Show 091-123 [1080p][HEVC x265 10bit][Dual-Audio][Multi-Subs]", "Some Anime Show", 91, 123 )] + [TestCase("[Judas] Some Anime Show 091-123 [1080p][HEVC x265 10bit][Dual-Audio][Multi-Subs]", "Some Anime Show", 91, 123)] [TestCase("[Judas] Some Anime Show - 091-123 [1080p][HEVC x265 10bit][Dual-Audio][Multi-Subs]", "Some Anime Show", 91, 123)] [TestCase("[HorribleSubs] Some Anime Show 01 - 119 [1080p] [Batch]", "Some Anime Show", 1, 119)] [TestCase("[Erai-raws] Series Title! - 01~10 [1080p][Multiple Subtitle]", "Series Title!", 1, 10)] [TestCase("[Erai-raws] Series-Title! 2 - 01~10 [1080p][Multiple Subtitle]", "Series-Title! 2", 1, 10)] [TestCase("[Erai-raws] Series Title! - 01 ~ 10 [1080p][Multiple Subtitle]", "Series Title!", 1, 10)] [TestCase("[Erai-raws] Series-Title! 2 - 01 ~ 10 [1080p][Multiple Subtitle]", "Series-Title! 2", 1, 10)] - // [TestCase("", "", 1, 2)] + + // [TestCase("", "", 1, 2)] public void should_parse_multi_episode_absolute_numbers(string postTitle, string title, int firstAbsoluteEpisodeNumber, int lastAbsoluteEpisodeNumber) { var absoluteEpisodeNumbers = Enumerable.Range(firstAbsoluteEpisodeNumber, lastAbsoluteEpisodeNumber - firstAbsoluteEpisodeNumber + 1) @@ -191,6 +195,5 @@ public void should_handle_anime_recap_numbering(string postTitle, string title, result.SpecialAbsoluteEpisodeNumbers.Should().BeEquivalentTo(new[] { (decimal)specialEpisodeNumber }); result.FullSeason.Should().BeFalse(); } - } } diff --git a/src/NzbDrone.Core.Test/ParserTests/AnimeMetadataParserFixture.cs b/src/NzbDrone.Core.Test/ParserTests/AnimeMetadataParserFixture.cs index 23651394b..5a1f8bef4 100644 --- a/src/NzbDrone.Core.Test/ParserTests/AnimeMetadataParserFixture.cs +++ b/src/NzbDrone.Core.Test/ParserTests/AnimeMetadataParserFixture.cs @@ -4,7 +4,6 @@ namespace NzbDrone.Core.Test.ParserTests { - [TestFixture] public class AnimeMetadataParserFixture : CoreTest { diff --git a/src/NzbDrone.Core.Test/ParserTests/CrapParserFixture.cs b/src/NzbDrone.Core.Test/ParserTests/CrapParserFixture.cs index 6c6161aaf..f6efa3a7d 100644 --- a/src/NzbDrone.Core.Test/ParserTests/CrapParserFixture.cs +++ b/src/NzbDrone.Core.Test/ParserTests/CrapParserFixture.cs @@ -1,13 +1,12 @@ using System; +using System.Text; using FluentAssertions; using NUnit.Framework; using NzbDrone.Core.Test.Framework; using NzbDrone.Test.Common; -using System.Text; namespace NzbDrone.Core.Test.ParserTests { - [TestFixture] public class CrapParserFixture : CoreTest { @@ -56,7 +55,9 @@ public void should_not_parse_md5() hash = BitConverter.ToString(hashData).Replace("-", ""); if (Parser.Parser.ParseTitle(hash) == null) + { success++; + } } success.Should().Be(repetitions); @@ -82,7 +83,9 @@ public void should_not_parse_random(int length) } if (Parser.Parser.ParseTitle(hash.ToString()) == null) + { success++; + } } success.Should().Be(repetitions); diff --git a/src/NzbDrone.Core.Test/ParserTests/DailyEpisodeParserFixture.cs b/src/NzbDrone.Core.Test/ParserTests/DailyEpisodeParserFixture.cs index dd3cb5b5b..6dbc819eb 100644 --- a/src/NzbDrone.Core.Test/ParserTests/DailyEpisodeParserFixture.cs +++ b/src/NzbDrone.Core.Test/ParserTests/DailyEpisodeParserFixture.cs @@ -7,7 +7,6 @@ namespace NzbDrone.Core.Test.ParserTests { - [TestFixture] public class DailyEpisodeParserFixture : CoreTest { @@ -25,6 +24,7 @@ public class DailyEpisodeParserFixture : CoreTest [TestCase("The_Series_US_04.28.2014_hdtv.x264.Poke.mp4", "The Series US", 2014, 4, 28)] [TestCase("A.Late.Talk.Show.140722.720p.HDTV.x264-YesTV", "A Late Talk Show", 2014, 07, 22)] [TestCase("A_Late_Talk_Show_140722_720p_HDTV_x264-YesTV", "A Late Talk Show", 2014, 07, 22)] + //[TestCase("Corrie.07.01.15", "Corrie", 2015, 1, 7)] [TestCase("The Show Series 2015 02 09 WEBRIP s01e13", "The Show Series", 2015, 2, 9)] [TestCase("Tree_Series_2018_06_22_Seth_Meyers_720p_HEVC_x265-MeGusta", "Tree Series", 2018, 6, 22)] @@ -33,6 +33,7 @@ public class DailyEpisodeParserFixture : CoreTest [TestCase("2019_08_20_1080_all.mp4", "", 2019, 8, 20)] [TestCase("Series and Title 20201013 Ep7432 [720p WebRip (x264)] [SUBS]", "Series and Title", 2020, 10, 13)] [TestCase("Series Title (1955) - 1954-01-23 05 00 00 - Cottage for Sale.ts", "Series Title (1955)", 1954, 1, 23)] + //[TestCase("", "", 0, 0, 0)] public void should_parse_daily_episode(string postTitle, string title, int year, int month, int day) { diff --git a/src/NzbDrone.Core.Test/ParserTests/HashedReleaseFixture.cs b/src/NzbDrone.Core.Test/ParserTests/HashedReleaseFixture.cs index 7cc3578bb..694c031f7 100644 --- a/src/NzbDrone.Core.Test/ParserTests/HashedReleaseFixture.cs +++ b/src/NzbDrone.Core.Test/ParserTests/HashedReleaseFixture.cs @@ -146,7 +146,8 @@ public class HashedReleaseFixture : CoreTest } }; - [Test, TestCaseSource(nameof(HashedReleaseParserCases))] + [Test] + [TestCaseSource(nameof(HashedReleaseParserCases))] public void should_properly_parse_hashed_releases(string path, string title, Quality quality, string releaseGroup) { var result = Parser.Parser.ParsePath(path); diff --git a/src/NzbDrone.Core.Test/ParserTests/IsPossibleSpecialEpisodeFixture.cs b/src/NzbDrone.Core.Test/ParserTests/IsPossibleSpecialEpisodeFixture.cs index 25b0af55f..d81005188 100644 --- a/src/NzbDrone.Core.Test/ParserTests/IsPossibleSpecialEpisodeFixture.cs +++ b/src/NzbDrone.Core.Test/ParserTests/IsPossibleSpecialEpisodeFixture.cs @@ -12,7 +12,7 @@ public void should_not_treat_files_without_a_series_title_as_a_special() { var parsedEpisodeInfo = new ParsedEpisodeInfo { - EpisodeNumbers = new[]{ 7 }, + EpisodeNumbers = new[] { 7 }, SeasonNumber = 1, SeriesTitle = "" }; @@ -40,7 +40,6 @@ public void IsPossibleSpecialEpisode_should_be_true(string title) Parser.Parser.ParseTitle(title).IsPossibleSpecialEpisode.Should().BeTrue(); } - [TestCase("Title.the.Series.S11E00.A.Christmas.Carol.Special.720p.HDTV-FieldOfView")] public void IsPossibleSpecialEpisode_should_be_true_if_e00_special(string title) { diff --git a/src/NzbDrone.Core.Test/ParserTests/LanguageParserFixture.cs b/src/NzbDrone.Core.Test/ParserTests/LanguageParserFixture.cs index b2f2a5833..1462ec672 100644 --- a/src/NzbDrone.Core.Test/ParserTests/LanguageParserFixture.cs +++ b/src/NzbDrone.Core.Test/ParserTests/LanguageParserFixture.cs @@ -1,4 +1,4 @@ -using FluentAssertions; +using FluentAssertions; using NUnit.Framework; using NzbDrone.Core.Languages; using NzbDrone.Core.Parser; @@ -6,7 +6,6 @@ namespace NzbDrone.Core.Test.ParserTests { - [TestFixture] public class LanguageParserFixture : CoreTest { @@ -211,7 +210,7 @@ public void should_parse_language_portuguese(string postTitle) var result = LanguageParser.ParseLanguage(postTitle); result.Id.Should().Be(Language.Portuguese.Id); } - + [TestCase("Title.the.Series.S01E01.FLEMISH.HDTV.x264-BRiGAND")] public void should_parse_language_flemish(string postTitle) { @@ -260,7 +259,7 @@ public void should_parse_language_czech(string postTitle) public void should_parse_language_arabic(string postTitle) { var result = LanguageParser.ParseLanguage(postTitle); - result.Id.Should().Be(Language.Arabic.Id); + result.Id.Should().Be(Language.Arabic.Id); } [TestCase("The Shadow Series S01 E01-08 WebRip Dual Audio [Hindi 5.1 + English 5.1] 720p x264 AAC ESub")] diff --git a/src/NzbDrone.Core.Test/ParserTests/MiniSeriesEpisodeParserFixture.cs b/src/NzbDrone.Core.Test/ParserTests/MiniSeriesEpisodeParserFixture.cs index 23bd35643..4434a8f37 100644 --- a/src/NzbDrone.Core.Test/ParserTests/MiniSeriesEpisodeParserFixture.cs +++ b/src/NzbDrone.Core.Test/ParserTests/MiniSeriesEpisodeParserFixture.cs @@ -5,7 +5,6 @@ namespace NzbDrone.Core.Test.ParserTests { - [TestFixture] public class MiniSeriesEpisodeParserFixture : CoreTest { @@ -13,6 +12,7 @@ public class MiniSeriesEpisodeParserFixture : CoreTest [TestCase("kill-roy-was-here-e07-720p", "kill-roy-was-here", 7)] [TestCase("Series and Show 2012 Part 1 REPACK 720p HDTV x264 2HD", "Series and Show 2012", 1)] [TestCase("Series Show.2016.E04.Power.720p.WEB-DL.DD5.1.H.264-MARS", "Series Show 2016", 4)] + //[TestCase("Killroy.Jumped.And.Was.Here.EP02.Episode.Title.DVDRiP.XviD-DEiTY", "Killroy.Jumped.And.Was.Here", 2)] //[TestCase("", "", 0)] public void should_parse_mini_series_episode(string postTitle, string title, int episodeNumber) @@ -29,8 +29,9 @@ public void should_parse_mini_series_episode(string postTitle, string title, int [TestCase("It's a Series Title.E56.190121.720p-NEXT.mp4", "It's a Series Title", 56, "2019-01-21")] [TestCase("My Only Series Title.E37.190120.1080p-NEXT.mp4", "My Only Series Title", 37, "2019-01-20")] - [TestCase("Series.E191.190121.720p-NEXT.mp4", "Series",191, "2019-01-21")] + [TestCase("Series.E191.190121.720p-NEXT.mp4", "Series", 191, "2019-01-21")] [TestCase("The Series Title Challenge.E932.190120.720p-NEXT.mp4", "The Series Title Challenge", 932, "2019-01-20")] + //[TestCase("", "", 0, "")] public void should_parse_korean_series_episode(string postTitle, string title, int episodeNumber, string airdate) { @@ -42,6 +43,7 @@ public void should_parse_korean_series_episode(string postTitle, string title, i result.SeriesTitle.Should().Be(title); result.AbsoluteEpisodeNumbers.Should().BeEmpty(); result.FullSeason.Should().BeFalse(); + // We don't support both SxxExx and airdate yet //result.AirDate.Should().Be(airdate); } diff --git a/src/NzbDrone.Core.Test/ParserTests/MultiEpisodeParserFixture.cs b/src/NzbDrone.Core.Test/ParserTests/MultiEpisodeParserFixture.cs index 0d0d704e2..f5b5c42b0 100644 --- a/src/NzbDrone.Core.Test/ParserTests/MultiEpisodeParserFixture.cs +++ b/src/NzbDrone.Core.Test/ParserTests/MultiEpisodeParserFixture.cs @@ -4,7 +4,6 @@ namespace NzbDrone.Core.Test.ParserTests { - [TestFixture] public class MultiEpisodeParserFixture : CoreTest { @@ -24,7 +23,7 @@ public class MultiEpisodeParserFixture : CoreTest [TestCase("Series Kings - 2x09-2x10 - Served Code [SDTV] ", "Series Kings", 2, new[] { 9, 10 })] [TestCase("Hell on Series S02E09 E10 HDTV x264 EVOLVE", "Hell on Series", 2, new[] { 9, 10 })] [TestCase("Hell.on.Series.S02E09-E10.720p.HDTV.x264-EVOLVE", "Hell on Series", 2, new[] { 9, 10 })] - [TestCase("Series's Sonarr - 8x01_02 - Free Falling", "Series's Sonarr", 8, new [] { 1,2 })] + [TestCase("Series's Sonarr - 8x01_02 - Free Falling", "Series's Sonarr", 8, new[] { 1, 2 })] [TestCase("8x01_02 - Free Falling", "", 8, new[] { 1, 2 })] [TestCase("Series.S01E91-E100", "Series", 1, new[] { 91, 92, 93, 94, 95, 96, 97, 98, 99, 100 })] [TestCase("Series.S29E161-E165.PDTV.x264-FQM", "Series", 29, new[] { 161, 162, 163, 164, 165 })] @@ -34,44 +33,46 @@ public class MultiEpisodeParserFixture : CoreTest [TestCase("Series.10910.hdtv-lol.mp4", "Series", 1, new[] { 9, 10 })] [TestCase("E.010910.HDTVx264REPACKLOL.mp4", "E", 1, new[] { 9, 10 })] [TestCase("World Series of Sonarr - 2010x15 - 2010x16 - HD TV.mkv", "World Series of Sonarr", 2010, new[] { 15, 16 })] - [TestCase("The Series US S01E01-E02 720p HDTV x264", "The Series US", 1, new [] { 1, 2 })] - [TestCase("Series Title Season 01 Episode 05-06 720p", "Series Title", 1,new [] { 5, 6 })] + [TestCase("The Series US S01E01-E02 720p HDTV x264", "The Series US", 1, new[] { 1, 2 })] + [TestCase("Series Title Season 01 Episode 05-06 720p", "Series Title", 1, new[] { 5, 6 })] + //[TestCase("My Name Is Sonarr - S03E01-E02 - My Name Is Code 28301-016 [SDTV]", "My Name Is Sonarr", 3, new[] { 1, 2 })] //[TestCase("Adventure Series - 5x01 - x02 - Dev the Human (2) & Sonarr the Robot (3)", "Adventure Series", 5, new [] { 1, 2 })] [TestCase("The Series And The Code - S42 Ep10718 - Ep10722", "The Series And The Code", 42, new[] { 10718, 10719, 10720, 10721, 10722 })] [TestCase("The Series And The Code - S42 Ep10688 - Ep10692", "The Series And The Code", 42, new[] { 10688, 10689, 10690, 10691, 10692 })] - [TestCase("Series.S01E02E03.1080p.BluRay.x264-DeBTViD", "Series", 1, new [] { 2, 3 })] - [TestCase("grp-zoos01e11e12-1080p", "grp-zoo", 1, new [] { 11, 12 })] - [TestCase("grp-zoo-s01e11e12-1080p", "grp-zoo", 1, new [] { 11, 12 })] - [TestCase("Series Title.S6.E1.E2.Episode Name.1080p.WEB-DL", "Series Title", 6, new [] { 1, 2 })] - [TestCase("Series Title.S6E1-E2.Episode Name.1080p.WEB-DL", "Series Title", 6, new [] { 1, 2 })] - [TestCase("Series Title.S6E1-S6E2.Episode Name.1080p.WEB-DL", "Series Title", 6, new [] { 1, 2 })] - [TestCase("Series Title.S6E1E2.Episode Name.1080p.WEB-DL", "Series Title", 6, new [] { 1, 2 })] - [TestCase("Series Title.S6E1-E2-E3.Episode Name.1080p.WEB-DL", "Series Title", 6, new [] { 1, 2, 3})] - [TestCase("Series Title.S6.E1E3.Episode Name.1080p.WEB-DL", "Series Title", 6, new [] { 1, 2, 3 })] + [TestCase("Series.S01E02E03.1080p.BluRay.x264-DeBTViD", "Series", 1, new[] { 2, 3 })] + [TestCase("grp-zoos01e11e12-1080p", "grp-zoo", 1, new[] { 11, 12 })] + [TestCase("grp-zoo-s01e11e12-1080p", "grp-zoo", 1, new[] { 11, 12 })] + [TestCase("Series Title.S6.E1.E2.Episode Name.1080p.WEB-DL", "Series Title", 6, new[] { 1, 2 })] + [TestCase("Series Title.S6E1-E2.Episode Name.1080p.WEB-DL", "Series Title", 6, new[] { 1, 2 })] + [TestCase("Series Title.S6E1-S6E2.Episode Name.1080p.WEB-DL", "Series Title", 6, new[] { 1, 2 })] + [TestCase("Series Title.S6E1E2.Episode Name.1080p.WEB-DL", "Series Title", 6, new[] { 1, 2 })] + [TestCase("Series Title.S6E1-E2-E3.Episode Name.1080p.WEB-DL", "Series Title", 6, new[] { 1, 2, 3 })] + [TestCase("Series Title.S6.E1E3.Episode Name.1080p.WEB-DL", "Series Title", 6, new[] { 1, 2, 3 })] [TestCase("Series Title.S6.E1-E2.Episode Name.1080p.WEB-DL", "Series Title", 6, new[] { 1, 2 })] [TestCase("Series Title.S6.E1-S6E2.Episode Name.1080p.WEB-DL", "Series Title", 6, new[] { 1, 2 })] [TestCase("Series Title.S6.E1E2.Episode Name.1080p.WEB-DL", "Series Title", 6, new[] { 1, 2 })] [TestCase("Series Title.S6.E1-E2-E3.Episode Name.1080p.WEB-DL", "Series Title", 6, new[] { 1, 2, 3 })] [TestCase("Series.Title.S05E01-E02.720p.5.1Ch.BluRay", "Series Title", 5, new[] { 1, 2 })] [TestCase("Series.Title.S05E01-02.720p.5.1Ch.BluRay", "Series Title", 5, new[] { 1, 2 })] - [TestCase("S01E01-E03 - Episode Title.HDTV-720p", "", 1, new [] { 1, 2, 3 })] - [TestCase("1x01-x03 - Episode Title.HDTV-720p", "", 1, new [] { 1, 2, 3 })] + [TestCase("S01E01-E03 - Episode Title.HDTV-720p", "", 1, new[] { 1, 2, 3 })] + [TestCase("1x01-x03 - Episode Title.HDTV-720p", "", 1, new[] { 1, 2, 3 })] [TestCase("Series.Title.E07-E08.180612.1080p-NEXT", "Series Title", 1, new[] { 7, 8 })] [TestCase("Series Title? E11-E12 1080p HDTV AAC H.264-NEXT", "Series Title", 1, new[] { 11, 12 })] - [TestCase("The Series Title (2010) - [S01E01-02-03] - Episode Title", "The Series Title (2010)", 1, new [] { 1, 2, 3 })] + [TestCase("The Series Title (2010) - [S01E01-02-03] - Episode Title", "The Series Title (2010)", 1, new[] { 1, 2, 3 })] [TestCase("[AqusiQ-TorrentS.pl]The.Name.of.the.Series.S01E05-06.PL.2160p-Ralf[shogho]", "The Name of the Series", 1, new[] { 5, 6 })] [TestCase("[AgusiQ-TorrentS.pl] The.Name.of.the.Series.S01E05-E06.PL.1080i.Ralf [jans12]", "The Name of the Series", 1, new[] { 5, 6 })] [TestCase("The.Name.of.the.Series.S01E05-6.PL.1080p.WEBRip.x264-666", "The Name of the Series", 1, new[] { 5, 6 })] [TestCase("Series Title - S15E06-07 - City Sushi HDTV-720p", "Series Title", 15, new[] { 6, 7 })] [TestCase("Series Title - S01E01-02-03 - Episode Title HDTV-720p", "Series Title", 1, new[] { 1, 2, 3 })] - [TestCase("Series Title - [02x01x02] - Episode 1", "Series Title", 2, new [] { 1, 2})] - [TestCase("Series Title - [02x01-x02] - Episode 1", "Series Title", 2, new [] { 1, 2})] - [TestCase("Series Title - [02x01-02] - Episode 1", "Series Title", 2, new [] { 1, 2})] - [TestCase("Series Title (2011) - S01E23-E24 - ...E i nuovi orizzonti [HDTV 360p] [ITA].mkv", "Series Title (2011)", 1, new [] { 23, 24 })] - [TestCase("The Series Title! - S01E01-02-03", "The Series Title!", 1, new [] { 1, 2, 3 })] - [TestCase("Series Title! (2013) - S04E44-E45 - Il 200 spettacolare episodio da narcisisti!", "Series Title! (2013)", 4, new [] { 44, 45 })] - [TestCase("Series Title! (2013) - S04E44-E45 - Il 200 spettacolare episodio da narcisisti! [NetflixHD 720p HEVC] [ITA+ENG].mkv", "Series Title! (2013)", 4, new [] { 44, 45 })] + [TestCase("Series Title - [02x01x02] - Episode 1", "Series Title", 2, new[] { 1, 2 })] + [TestCase("Series Title - [02x01-x02] - Episode 1", "Series Title", 2, new[] { 1, 2 })] + [TestCase("Series Title - [02x01-02] - Episode 1", "Series Title", 2, new[] { 1, 2 })] + [TestCase("Series Title (2011) - S01E23-E24 - ...E i nuovi orizzonti [HDTV 360p] [ITA].mkv", "Series Title (2011)", 1, new[] { 23, 24 })] + [TestCase("The Series Title! - S01E01-02-03", "The Series Title!", 1, new[] { 1, 2, 3 })] + [TestCase("Series Title! (2013) - S04E44-E45 - Il 200 spettacolare episodio da narcisisti!", "Series Title! (2013)", 4, new[] { 44, 45 })] + [TestCase("Series Title! (2013) - S04E44-E45 - Il 200 spettacolare episodio da narcisisti! [NetflixHD 720p HEVC] [ITA+ENG].mkv", "Series Title! (2013)", 4, new[] { 44, 45 })] + //[TestCase("", "", , new [] { })] public void should_parse_multiple_episodes(string postTitle, string title, int season, int[] episodes) { diff --git a/src/NzbDrone.Core.Test/ParserTests/NormalizeTitleFixture.cs b/src/NzbDrone.Core.Test/ParserTests/NormalizeTitleFixture.cs index a18a63ba8..8131efcd1 100644 --- a/src/NzbDrone.Core.Test/ParserTests/NormalizeTitleFixture.cs +++ b/src/NzbDrone.Core.Test/ParserTests/NormalizeTitleFixture.cs @@ -5,7 +5,6 @@ namespace NzbDrone.Core.Test.ParserTests { - [TestFixture] public class NormalizeTitleFixture : CoreTest { @@ -111,9 +110,8 @@ public void should_not_remove_common_words_in_the_middle_of_word(string word) foreach (var s in dirtyFormat) { var dirty = string.Format(s, word); - dirty.CleanSeriesTitle().Should().Be(("word" + word.ToLower() + "word")); + dirty.CleanSeriesTitle().Should().Be("word" + word.ToLower() + "word"); } - } [TestCase("The Series", "theseries")] diff --git a/src/NzbDrone.Core.Test/ParserTests/ParserFixture.cs b/src/NzbDrone.Core.Test/ParserTests/ParserFixture.cs index 63abbd75b..c8ea45338 100644 --- a/src/NzbDrone.Core.Test/ParserTests/ParserFixture.cs +++ b/src/NzbDrone.Core.Test/ParserTests/ParserFixture.cs @@ -7,11 +7,9 @@ namespace NzbDrone.Core.Test.ParserTests { - [TestFixture] public class ParserFixture : CoreTest { - [TestCase("Series Title - 4x05 - Title", "seriestitle")] [TestCase("Series & Title - 4x05 - Title", "seriestitle")] [TestCase("Bad Format", "badformat")] @@ -43,7 +41,7 @@ public void should_parse_series_name(string postTitle, string title) [TestCase("Series (2022) S03E14 720p HDTV X264-DIMENSION", "Series", 2022)] [TestCase("Series.2022.S03E14.720p.HDTV.X264-DIMENSION", "Series", 2022)] [TestCase("Series-2022-S03E14-720p-HDTV-X264-DIMENSION", "Series", 2022)] - [TestCase("Series_2022_S03E14_720p_HDTV_X264-DIMENSION", "Series", 2022)] + [TestCase("Series_2022_S03E14_720p_HDTV_X264-DIMENSION", "Series", 2022)] [TestCase("1234 S03E14 720p HDTV X264-DIMENSION", "1234")] [TestCase("1234.S03E14.720p.HDTV.X264-DIMENSION", "1234")] [TestCase("1234-S03E14-720p-HDTV-X264-DIMENSION", "1234")] diff --git a/src/NzbDrone.Core.Test/ParserTests/ParsingServiceTests/GetEpisodesFixture.cs b/src/NzbDrone.Core.Test/ParserTests/ParsingServiceTests/GetEpisodesFixture.cs index 2421b9304..e86092f6c 100644 --- a/src/NzbDrone.Core.Test/ParserTests/ParsingServiceTests/GetEpisodesFixture.cs +++ b/src/NzbDrone.Core.Test/ParserTests/ParsingServiceTests/GetEpisodesFixture.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using FizzWare.NBuilder; @@ -111,7 +111,7 @@ public void should_use_search_criteria_episode_when_it_matches_daily() public void should_fallback_to_daily_episode_lookup_when_search_criteria_episode_doesnt_match() { GivenDailySeries(); - _parsedEpisodeInfo.AirDate = DateTime.Today.AddDays(-5).ToString(Episode.AIR_DATE_FORMAT); ; + _parsedEpisodeInfo.AirDate = DateTime.Today.AddDays(-5).ToString(Episode.AIR_DATE_FORMAT); Subject.Map(_parsedEpisodeInfo, _series.TvdbId, _series.TvRageId, _singleEpisodeSearchCriteria); @@ -306,7 +306,7 @@ public void should_find_episode_by_parsed_season_and_absolute_episode_number_whe Mocker.GetMock() .Setup(s => s.FindEpisodesBySceneNumbering(It.IsAny(), seasonNumber, It.IsAny())) .Returns(new List()); - + Mocker.GetMock() .Setup(s => s.FindEpisode(It.IsAny(), seasonNumber, It.IsAny())) .Returns(_episodes.First()); @@ -326,7 +326,7 @@ public void should_not_find_episode_by_parsed_season_and_absolute_episode_number { GivenAbsoluteNumberingSeries(); _parsedEpisodeInfo.SeasonNumber = seasonNumber; - _parsedEpisodeInfo.EpisodeNumbers = new []{ 1 }; + _parsedEpisodeInfo.EpisodeNumbers = new[] { 1 }; Mocker.GetMock() .Setup(s => s.FindEpisodesBySceneNumbering(It.IsAny(), It.IsAny())) @@ -463,7 +463,7 @@ public void should_not_use_tvdb_season_when_tvdb_season_number_is_less_than_zero public void should_lookup_full_season_by_season_number_if_series_does_not_use_scene_numbering() { GivenFullSeason(); - + Mocker.GetMock() .Setup(s => s.GetEpisodesBySeason(_series.Id, _parsedEpisodeInfo.SeasonNumber)) .Returns(_episodes); @@ -533,8 +533,7 @@ public void should_use_season_zero_when_looking_up_is_partial_special_episode_fo Builder.CreateNew() .With(e => e.SeasonNumber = 0) .With(e => e.EpisodeNumber = 1) - .Build() - ); + .Build()); Subject.Map(_parsedEpisodeInfo, _series.TvdbId, _series.TvRageId); diff --git a/src/NzbDrone.Core.Test/ParserTests/ParsingServiceTests/MapFixture.cs b/src/NzbDrone.Core.Test/ParserTests/ParsingServiceTests/MapFixture.cs index cff5872cb..5249af1aa 100644 --- a/src/NzbDrone.Core.Test/ParserTests/ParsingServiceTests/MapFixture.cs +++ b/src/NzbDrone.Core.Test/ParserTests/ParsingServiceTests/MapFixture.cs @@ -63,7 +63,7 @@ private void GivenMatchBySeriesTitle() private void GivenMatchByTvdbId() { Mocker.GetMock() - .Setup(s => s.FindByTvdbId(It.IsAny())) + .Setup(s => s.FindByTvdbId(It.IsAny())) .Returns(_series); } @@ -98,7 +98,7 @@ public void should_use_tvdbid_when_series_title_lookup_fails() Subject.Map(_parsedEpisodeInfo, _series.TvdbId, _series.TvRageId); Mocker.GetMock() - .Verify(v => v.FindByTvdbId(It.IsAny()), Times.Once()); + .Verify(v => v.FindByTvdbId(It.IsAny()), Times.Once()); } [Test] @@ -181,7 +181,7 @@ public void should_FindByTvdbId_when_search_criteria_and_FindByTitle_matching_fa Subject.Map(_parsedEpisodeInfo, 10, 10, _singleEpisodeSearchCriteria); Mocker.GetMock() - .Verify(v => v.FindByTvdbId(It.IsAny()), Times.Once()); + .Verify(v => v.FindByTvdbId(It.IsAny()), Times.Once()); } [Test] diff --git a/src/NzbDrone.Core.Test/ParserTests/PathParserFixture.cs b/src/NzbDrone.Core.Test/ParserTests/PathParserFixture.cs index 540435c17..8146d469b 100644 --- a/src/NzbDrone.Core.Test/ParserTests/PathParserFixture.cs +++ b/src/NzbDrone.Core.Test/ParserTests/PathParserFixture.cs @@ -5,7 +5,6 @@ namespace NzbDrone.Core.Test.ParserTests { - [TestFixture] public class PathParserFixture : CoreTest { @@ -30,6 +29,7 @@ public class PathParserFixture : CoreTest [TestCase(@"C:\Test\Series\Season 01\1 Pilot (1080p HD).mkv", 1, 1)] [TestCase(@"C:\Test\Series\Season 1\02 Honor Thy Father (1080p HD).m4v", 1, 2)] [TestCase(@"C:\Test\Series\Season 1\2 Honor Thy Developer (1080p HD).m4v", 1, 2)] + //[TestCase(@"C:\series.state.S02E04.720p.WEB-DL.DD5.1.H.264\73696S02-04.mkv", 2, 4)] //Gets treated as S01E04 (because it gets parsed as anime); 2020-01 broken test case: Expected result.EpisodeNumbers to contain 1 item(s), but found 0 public void should_parse_from_path(string path, int season, int episode) { @@ -44,7 +44,7 @@ public void should_parse_from_path(string path, int season, int episode) ExceptionVerification.IgnoreWarns(); } - [TestCase("01-03\\The Series Title (2010) - 1x01-02-03 - Episode Title HDTV-720p Proper", "The Series Title (2010)", 1, new [] { 1, 2, 3 })] + [TestCase("01-03\\The Series Title (2010) - 1x01-02-03 - Episode Title HDTV-720p Proper", "The Series Title (2010)", 1, new[] { 1, 2, 3 })] public void should_parse_multi_episode_from_path(string path, string title, int season, int[] episodes) { var result = Parser.Parser.ParsePath(path.AsOsAgnostic()); diff --git a/src/NzbDrone.Core.Test/ParserTests/QualityParserFixture.cs b/src/NzbDrone.Core.Test/ParserTests/QualityParserFixture.cs index 03f7f5bdc..609d69e6b 100644 --- a/src/NzbDrone.Core.Test/ParserTests/QualityParserFixture.cs +++ b/src/NzbDrone.Core.Test/ParserTests/QualityParserFixture.cs @@ -378,7 +378,8 @@ public void quality_parse(string title, bool proper) ParseAndVerifyQuality(title, Quality.Unknown, proper); } - [Test, TestCaseSource(nameof(SelfQualityParserCases))] + [Test] + [TestCaseSource(nameof(SelfQualityParserCases))] public void parsing_our_own_quality_enum_name(Quality quality) { var fileName = string.Format("My series S01E01 [{0}]", quality.Name); @@ -386,7 +387,8 @@ public void parsing_our_own_quality_enum_name(Quality quality) result.Quality.Should().Be(quality); } - [Test, TestCaseSource(nameof(OtherSourceQualityParserCases))] + [Test] + [TestCaseSource(nameof(OtherSourceQualityParserCases))] public void should_parse_quality_from_other_source(string qualityString, Quality quality) { foreach (var c in new char[] { '-', '.', ' ', '_' }) diff --git a/src/NzbDrone.Core.Test/ParserTests/ReleaseGroupParserFixture.cs b/src/NzbDrone.Core.Test/ParserTests/ReleaseGroupParserFixture.cs index 3efe0e7fd..ab4f29b08 100644 --- a/src/NzbDrone.Core.Test/ParserTests/ReleaseGroupParserFixture.cs +++ b/src/NzbDrone.Core.Test/ParserTests/ReleaseGroupParserFixture.cs @@ -43,6 +43,7 @@ public class ReleaseGroupParserFixture : CoreTest [TestCase("[Tenrai-Sensei] Series [BD][1080p][HEVC 10bit x265][Dual Audio]", "Tenrai-Sensei")] [TestCase("[Erai-raws] Series - 0955 ~ 1005 [1080p]", "Erai-raws")] [TestCase("[Exiled-Destiny] Series Title", "Exiled-Destiny")] + //[TestCase("", "")] public void should_parse_release_group(string title, string expected) { @@ -80,6 +81,7 @@ public void should_not_include_extension_in_release_group() [TestCase("Series.Title.S02E04.720p.WEBRip.x264-SKGTV English", "SKGTV")] [TestCase("Series.Title.S02E04.720p.WEBRip.x264-SKGTV_English", "SKGTV")] [TestCase("Series.Title.S02E04.720p.WEBRip.x264-SKGTV.English", "SKGTV")] + //[TestCase("", "")] public void should_not_include_language_in_release_group(string title, string expected) { @@ -122,6 +124,7 @@ public void should_not_include_repost_in_release_group(string title, string expe [TestCase("[Anime-Koi] Series Title - S01E06 - Guys From Sonarr", "Anime-Koi")] [TestCase("[Anime-Koi] Series Title - S01E07 - A High-Grade Sonarr", "Anime-Koi")] [TestCase("[Anime-Koi] Series Title 2 - 01 [h264-720p][28D54E2C]", "Anime-Koi")] + //[TestCase("Tokyo.Ghoul.02x01.013.HDTV-720p-Anime-Koi", "Anime-Koi")] //[TestCase("", "")] public void should_parse_anime_release_groups(string title, string expected) diff --git a/src/NzbDrone.Core.Test/ParserTests/SceneCheckerFixture.cs b/src/NzbDrone.Core.Test/ParserTests/SceneCheckerFixture.cs index 30258b06c..a2d91c29f 100644 --- a/src/NzbDrone.Core.Test/ParserTests/SceneCheckerFixture.cs +++ b/src/NzbDrone.Core.Test/ParserTests/SceneCheckerFixture.cs @@ -17,7 +17,6 @@ public void should_return_true_for_scene_names(string title) SceneChecker.IsSceneTitle(title).Should().BeTrue(); } - [TestCase("S08E05 - Virtual In-Stanity [WEBDL-720p]")] [TestCase("S08E05 - Virtual In-Stanity.With.Dots [WEBDL-720p]")] [TestCase("Something")] @@ -30,7 +29,5 @@ public void should_return_false_for_non_scene_names(string title) { SceneChecker.IsSceneTitle(title).Should().BeFalse(); } - - } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core.Test/ParserTests/SeasonParserFixture.cs b/src/NzbDrone.Core.Test/ParserTests/SeasonParserFixture.cs index 769927256..4b4988b9e 100644 --- a/src/NzbDrone.Core.Test/ParserTests/SeasonParserFixture.cs +++ b/src/NzbDrone.Core.Test/ParserTests/SeasonParserFixture.cs @@ -4,7 +4,6 @@ namespace NzbDrone.Core.Test.ParserTests { - [TestFixture] public class SeasonParserFixture : CoreTest { diff --git a/src/NzbDrone.Core.Test/ParserTests/SingleEpisodeParserFixture.cs b/src/NzbDrone.Core.Test/ParserTests/SingleEpisodeParserFixture.cs index bc66f7241..e506337d3 100644 --- a/src/NzbDrone.Core.Test/ParserTests/SingleEpisodeParserFixture.cs +++ b/src/NzbDrone.Core.Test/ParserTests/SingleEpisodeParserFixture.cs @@ -5,7 +5,6 @@ namespace NzbDrone.Core.Test.ParserTests { - [TestFixture] public class SingleEpisodeParserFixture : CoreTest { @@ -96,12 +95,14 @@ public class SingleEpisodeParserFixture : CoreTest [TestCase("1x03 - 274 [1080p BluRay].mkv", "", 1, 3)] [TestCase("1x03 - The 112th Congress [1080p BluRay].mkv", "", 1, 3)] [TestCase("Series.2012.S02E14.720p.HDTV.X264-DIMENSION [PublicHD].mkv", "Series 2012", 2, 14)] + //[TestCase("Sex And The City S6E15 - Catch-38 [RavyDavy].avi", "Sex And The City", 6, 15)] // -38 is getting treated as abs number [TestCase("Series.2009.S06E03.720p.HDTV.X264-DIMENSION [PublicHD].mkv", "Series 2009", 6, 3)] [TestCase("20-1.2014.S02E01.720p.HDTV.x264-CROOKS", "20-1 2014", 2, 1)] [TestCase("Series - S01E09 - Debate 109", "Series", 1, 9)] [TestCase("Series - S02E02 - My Maserati Does 185", "Series", 2, 2)] [TestCase("6x13 - The Series Show 100th Episode Special", "", 6, 13)] + //[TestCase("Series - S01E01 - Genesis 101 [HDTV-720p]", "Series", 1, 1)] //[TestCase("The Series S02E01 HDTV x264-KILLERS [eztv]", "The Series", 2, 1)] [TestCase("The Series And the Show - S41 E10478 - 2014-08-15", "The Series And the Show", 41, 10478)] @@ -109,6 +110,7 @@ public class SingleEpisodeParserFixture : CoreTest [TestCase("Series Title [1x05] Episode Title", "Series Title", 1, 5)] [TestCase("Series Title [S01E05] Episode Title", "Series Title", 1, 5)] [TestCase("Series Title Season 01 Episode 05 720p", "Series Title", 1, 5)] + //[TestCase("Off the Series - 101 - Developers (460p.x264.vorbis-2.0) [449].mkv", "Off the Series", 1, 1)] [TestCase("The Series And the Show - S42 E10713 - 2015-07-20.mp4", "The Series And the Show", 42, 10713)] [TestCase("Series.103.hdtv-lol[ettv].mp4", "Series", 1, 3)] @@ -151,6 +153,7 @@ public class SingleEpisodeParserFixture : CoreTest [TestCase("Series Title - Temporada 2 [HDTV 720p][Cap.1901][AC3 5.1 Castellano][www.pctnew.com]", "Series Title", 19, 1)] [TestCase("Series Title 1x1", "Series Title", 1, 1)] [TestCase("1x1", "", 1, 1)] + //[TestCase("", "", 0, 0)] public void should_parse_single_episode(string postTitle, string title, int seasonNumber, int episodeNumber) { diff --git a/src/NzbDrone.Core.Test/ParserTests/UnicodeReleaseParserFixture.cs b/src/NzbDrone.Core.Test/ParserTests/UnicodeReleaseParserFixture.cs index 19cb75c85..3a69e21de 100644 --- a/src/NzbDrone.Core.Test/ParserTests/UnicodeReleaseParserFixture.cs +++ b/src/NzbDrone.Core.Test/ParserTests/UnicodeReleaseParserFixture.cs @@ -1,12 +1,12 @@ -using FluentAssertions; -using NUnit.Framework; -using NzbDrone.Core.Indexers; -using NzbDrone.Core.Test.Framework; -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; +using FluentAssertions; +using NUnit.Framework; +using NzbDrone.Core.Indexers; +using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.ParserTests { @@ -62,6 +62,7 @@ public void should_parse_unbracketed_chinese_anime_releases(string postTitle, st [TestCase("[YMDR][慕留人 -火影忍者新時代-][Anime Series Title-][2017][88-91][1080p][AVC][JAP][BIG5][MP4-AAC][繁中]", "Anime Series Title", "YMDR", new[] { 88, 89, 90, 91 })] [TestCase("[诸神字幕组][战栗杀机][ANIME SERIES TITLE][01-24完][简日双语字幕][720P][MP4]", "ANIME SERIES TITLE", "诸神字幕组", new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24 })] + //[TestCase("【漫貓&愛戀字幕組】[五等分的新娘/五等分的花嫁/五等分の花嫁][Anime Series Title][01_03][BIG5][720P][HEVC]", "Anime Series Title", "漫貓&愛戀字幕組", new[] { 1, 2, 3 })] public void should_parse_chinese_multiepisode_releases(string postTitle, string title, string subgroup, int[] absoluteEpisodeNumbers) { diff --git a/src/NzbDrone.Core.Test/Profiles/Delay/DelayProfileServiceFixture.cs b/src/NzbDrone.Core.Test/Profiles/Delay/DelayProfileServiceFixture.cs index ff2df10f4..c86678035 100644 --- a/src/NzbDrone.Core.Test/Profiles/Delay/DelayProfileServiceFixture.cs +++ b/src/NzbDrone.Core.Test/Profiles/Delay/DelayProfileServiceFixture.cs @@ -44,7 +44,7 @@ public void should_move_to_first_if_afterId_is_null() var moving = _last; var result = Subject.Reorder(moving.Id, null).OrderBy(d => d.Order).ToList(); var moved = result.First(); - + moved.Id.Should().Be(moving.Id); moved.Order.Should().Be(1); } @@ -75,7 +75,6 @@ public void should_reorder_delay_profiles_that_are_after_moved() { delayProfile.Order.Should().Be(int.MaxValue); } - else { delayProfile.Order.Should().Be(i + 1); diff --git a/src/NzbDrone.Core.Test/Profiles/ProfileRepositoryFixture.cs b/src/NzbDrone.Core.Test/Profiles/ProfileRepositoryFixture.cs index 275929863..37eb9a996 100644 --- a/src/NzbDrone.Core.Test/Profiles/ProfileRepositoryFixture.cs +++ b/src/NzbDrone.Core.Test/Profiles/ProfileRepositoryFixture.cs @@ -25,8 +25,6 @@ public void should_be_able_to_read_and_write() StoredModel.Cutoff.Should().Be(profile.Cutoff); StoredModel.Items.Should().Equal(profile.Items, (a, b) => a.Quality == b.Quality && a.Allowed == b.Allowed); - - } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core.Test/Profiles/QualityProfileServiceFixture.cs b/src/NzbDrone.Core.Test/Profiles/QualityProfileServiceFixture.cs index c3f6bb9d1..4b8e4934e 100644 --- a/src/NzbDrone.Core.Test/Profiles/QualityProfileServiceFixture.cs +++ b/src/NzbDrone.Core.Test/Profiles/QualityProfileServiceFixture.cs @@ -32,6 +32,7 @@ public void init_should_add_default_profiles() } [Test] + //This confirms that new profiles are added only if no other profiles exists. //We don't want to keep adding them back if a user deleted them on purpose. public void Init_should_skip_if_any_profiles_already_exist() @@ -46,7 +47,6 @@ public void Init_should_skip_if_any_profiles_already_exist() .Verify(v => v.Insert(It.IsAny()), Times.Never()); } - [Test] public void should_not_be_able_to_delete_profile_if_assigned_to_series() { @@ -59,7 +59,6 @@ public void should_not_be_able_to_delete_profile_if_assigned_to_series() .With(c => c.QualityProfileId = profile.Id) .Build().ToList(); - Mocker.GetMock().Setup(c => c.GetAllSeries()).Returns(seriesList); Mocker.GetMock().Setup(c => c.Get(profile.Id)).Returns(profile); @@ -76,7 +75,6 @@ public void should_delete_profile_if_not_assigned_to_series() .With(c => c.QualityProfileId = 2) .Build().ToList(); - Mocker.GetMock().Setup(c => c.GetAllSeries()).Returns(seriesList); Subject.Delete(1); @@ -101,7 +99,6 @@ public void should_not_be_able_to_delete_profile_if_assigned_to_import_list() .With(c => c.LanguageProfileId = 1) .Build().ToList(); - Mocker.GetMock().Setup(c => c.Get(profile.Id)).Returns(profile); Mocker.GetMock().Setup(c => c.GetAllSeries()).Returns(seriesList); @@ -109,7 +106,6 @@ public void should_not_be_able_to_delete_profile_if_assigned_to_import_list() .Setup(s => s.All()) .Returns(importLists); - Assert.Throws(() => Subject.Delete(1)); Mocker.GetMock().Verify(c => c.Delete(It.IsAny()), Times.Never()); diff --git a/src/NzbDrone.Core.Test/Profiles/Releases/PreferredWordService/CalculateFixture.cs b/src/NzbDrone.Core.Test/Profiles/Releases/PreferredWordService/CalculateFixture.cs index 45af69cd6..fa9fdfb47 100644 --- a/src/NzbDrone.Core.Test/Profiles/Releases/PreferredWordService/CalculateFixture.cs +++ b/src/NzbDrone.Core.Test/Profiles/Releases/PreferredWordService/CalculateFixture.cs @@ -21,7 +21,7 @@ public class CalculateFixture : CoreTest.CreateNew() - .With(s => s.Tags = new HashSet(new[] {1, 2})) + .With(s => s.Tags = new HashSet(new[] { 1, 2 })) .Build(); _releaseProfiles = new List(); @@ -40,7 +40,6 @@ public void Setup() .Returns(_releaseProfiles); } - private void GivenMatchingTerms(params string[] terms) { Mocker.GetMock() diff --git a/src/NzbDrone.Core.Test/Profiles/Releases/PreferredWordService/GetMatchingPreferredWordsFixture.cs b/src/NzbDrone.Core.Test/Profiles/Releases/PreferredWordService/GetMatchingPreferredWordsFixture.cs index 624eb18dd..cef2758b2 100644 --- a/src/NzbDrone.Core.Test/Profiles/Releases/PreferredWordService/GetMatchingPreferredWordsFixture.cs +++ b/src/NzbDrone.Core.Test/Profiles/Releases/PreferredWordService/GetMatchingPreferredWordsFixture.cs @@ -22,7 +22,7 @@ public class GetMatchingPreferredWordsFixture : CoreTest.CreateNew() - .With(s => s.Tags = new HashSet(new[] {1, 2})) + .With(s => s.Tags = new HashSet(new[] { 1, 2 })) .Build(); _releaseProfiles = new List(); @@ -57,12 +57,11 @@ public void Setup() } }); - Mocker.GetMock() .Setup(s => s.MatchingTerm(It.IsAny(), _title)) .Returns((term, title) => title.Contains(term) ? term : null); } - + private void GivenReleaseProfile() { Mocker.GetMock() diff --git a/src/NzbDrone.Core.Test/ProviderTests/DiskProviderTests/ArchiveProviderFixture.cs b/src/NzbDrone.Core.Test/ProviderTests/DiskProviderTests/ArchiveProviderFixture.cs index 5e9d6c6a8..504fa1a3a 100644 --- a/src/NzbDrone.Core.Test/ProviderTests/DiskProviderTests/ArchiveProviderFixture.cs +++ b/src/NzbDrone.Core.Test/ProviderTests/DiskProviderTests/ArchiveProviderFixture.cs @@ -1,7 +1,7 @@ -using FluentAssertions; +using System.IO; +using FluentAssertions; using NUnit.Framework; using NzbDrone.Common; -using System.IO; using NzbDrone.Common.EnvironmentInfo; using NzbDrone.Test.Common; diff --git a/src/NzbDrone.Core.Test/ProviderTests/DiskScanProviderTests/GetVideoFilesFixture.cs b/src/NzbDrone.Core.Test/ProviderTests/DiskScanProviderTests/GetVideoFilesFixture.cs index 8c25cb408..dfb1d660f 100644 --- a/src/NzbDrone.Core.Test/ProviderTests/DiskScanProviderTests/GetVideoFilesFixture.cs +++ b/src/NzbDrone.Core.Test/ProviderTests/DiskScanProviderTests/GetVideoFilesFixture.cs @@ -12,7 +12,6 @@ namespace NzbDrone.Core.Test.ProviderTests.DiskScanProviderTests { - public class GetVideoFilesFixture : CoreTest { private string[] _fileNames; diff --git a/src/NzbDrone.Core.Test/ProviderTests/RecycleBinProviderTests/CleanupFixture.cs b/src/NzbDrone.Core.Test/ProviderTests/RecycleBinProviderTests/CleanupFixture.cs index 5e336420b..7fb282fa2 100644 --- a/src/NzbDrone.Core.Test/ProviderTests/RecycleBinProviderTests/CleanupFixture.cs +++ b/src/NzbDrone.Core.Test/ProviderTests/RecycleBinProviderTests/CleanupFixture.cs @@ -10,7 +10,7 @@ namespace NzbDrone.Core.Test.ProviderTests.RecycleBinProviderTests { [TestFixture] - + public class CleanupFixture : CoreTest { private const string RecycleBin = @"C:\Test\RecycleBin"; @@ -40,10 +40,10 @@ public void Setup() Mocker.GetMock().SetupGet(s => s.RecycleBinCleanupDays).Returns(7); Mocker.GetMock().Setup(s => s.GetDirectories(RecycleBin)) - .Returns(new [] { @"C:\Test\RecycleBin\Folder1", @"C:\Test\RecycleBin\Folder2", @"C:\Test\RecycleBin\Folder3" }); + .Returns(new[] { @"C:\Test\RecycleBin\Folder1", @"C:\Test\RecycleBin\Folder2", @"C:\Test\RecycleBin\Folder3" }); Mocker.GetMock().Setup(s => s.GetFiles(RecycleBin, SearchOption.AllDirectories)) - .Returns(new [] { @"C:\Test\RecycleBin\File1.avi", @"C:\Test\RecycleBin\File2.mkv" }); + .Returns(new[] { @"C:\Test\RecycleBin\File1.avi", @"C:\Test\RecycleBin\File2.mkv" }); } [Test] diff --git a/src/NzbDrone.Core.Test/ProviderTests/RecycleBinProviderTests/DeleteFileFixture.cs b/src/NzbDrone.Core.Test/ProviderTests/RecycleBinProviderTests/DeleteFileFixture.cs index c1798f131..6e3ac490c 100644 --- a/src/NzbDrone.Core.Test/ProviderTests/RecycleBinProviderTests/DeleteFileFixture.cs +++ b/src/NzbDrone.Core.Test/ProviderTests/RecycleBinProviderTests/DeleteFileFixture.cs @@ -70,7 +70,6 @@ public void should_call_fileSetLastWriteTime_for_each_file() WithRecycleBin(); var path = @"C:\Test\TV\30 Rock\S01E01.avi".AsOsAgnostic(); - Mocker.Resolve().DeleteFile(path); Mocker.GetMock().Verify(v => v.FileSetLastWriteTime(@"C:\Test\Recycle Bin\S01E01.avi".AsOsAgnostic(), It.IsAny()), Times.Once()); diff --git a/src/NzbDrone.Core.Test/ProviderTests/RecycleBinProviderTests/EmptyFixture.cs b/src/NzbDrone.Core.Test/ProviderTests/RecycleBinProviderTests/EmptyFixture.cs index fbb0b1c0a..f061c1388 100644 --- a/src/NzbDrone.Core.Test/ProviderTests/RecycleBinProviderTests/EmptyFixture.cs +++ b/src/NzbDrone.Core.Test/ProviderTests/RecycleBinProviderTests/EmptyFixture.cs @@ -9,7 +9,7 @@ namespace NzbDrone.Core.Test.ProviderTests.RecycleBinProviderTests { [TestFixture] - + public class EmptyFixture : CoreTest { private const string RecycleBin = @"C:\Test\RecycleBin"; @@ -20,10 +20,10 @@ public void Setup() Mocker.GetMock().SetupGet(s => s.RecycleBin).Returns(RecycleBin); Mocker.GetMock().Setup(s => s.GetDirectories(RecycleBin)) - .Returns(new [] { @"C:\Test\RecycleBin\Folder1", @"C:\Test\RecycleBin\Folder2", @"C:\Test\RecycleBin\Folder3" }); + .Returns(new[] { @"C:\Test\RecycleBin\Folder1", @"C:\Test\RecycleBin\Folder2", @"C:\Test\RecycleBin\Folder3" }); Mocker.GetMock().Setup(s => s.GetFiles(RecycleBin, SearchOption.TopDirectoryOnly)) - .Returns(new [] { @"C:\Test\RecycleBin\File1.avi", @"C:\Test\RecycleBin\File2.mkv" }); + .Returns(new[] { @"C:\Test\RecycleBin\File1.avi", @"C:\Test\RecycleBin\File2.mkv" }); } [Test] @@ -38,7 +38,7 @@ public void should_return_if_recycleBin_not_configured() [Test] public void should_delete_all_folders() - { + { Mocker.Resolve().Empty(); Mocker.GetMock().Verify(v => v.DeleteFolder(It.IsAny(), true), Times.Exactly(3)); diff --git a/src/NzbDrone.Core.Test/Providers/XemProxyFixture.cs b/src/NzbDrone.Core.Test/Providers/XemProxyFixture.cs index a46ab935c..2a2bfd220 100644 --- a/src/NzbDrone.Core.Test/Providers/XemProxyFixture.cs +++ b/src/NzbDrone.Core.Test/Providers/XemProxyFixture.cs @@ -51,4 +51,4 @@ public void should_filter_out_episodes_without_scene_mapping(int seriesId) result.Should().NotContain(c => c.Tvdb == null); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core.Test/Qualities/QualityDefinitionServiceFixture.cs b/src/NzbDrone.Core.Test/Qualities/QualityDefinitionServiceFixture.cs index a2eec207b..5607eab1c 100644 --- a/src/NzbDrone.Core.Test/Qualities/QualityDefinitionServiceFixture.cs +++ b/src/NzbDrone.Core.Test/Qualities/QualityDefinitionServiceFixture.cs @@ -32,7 +32,7 @@ public void init_should_insert_any_missing_definitions() Subject.Handle(new ApplicationStartedEvent()); Mocker.GetMock() - .Verify(v => v.InsertMany(It.Is>(d => d.Count == Quality.All.Count -1 )), Times.Once()); + .Verify(v => v.InsertMany(It.Is>(d => d.Count == Quality.All.Count - 1)), Times.Once()); } [Test] @@ -58,7 +58,7 @@ public void init_should_remove_old_definitions() .Setup(s => s.All()) .Returns(new List { - new QualityDefinition(new Quality{ Id = 100, Name = "Test" }) { Weight = 1, MinSize = 0, MaxSize = 100, Id = 20 } + new QualityDefinition(new Quality { Id = 100, Name = "Test" }) { Weight = 1, MinSize = 0, MaxSize = 100, Id = 20 } }); Subject.Handle(new ApplicationStartedEvent()); diff --git a/src/NzbDrone.Core.Test/Qualities/QualityFixture.cs b/src/NzbDrone.Core.Test/Qualities/QualityFixture.cs index b8c48d88e..5e95ee625 100644 --- a/src/NzbDrone.Core.Test/Qualities/QualityFixture.cs +++ b/src/NzbDrone.Core.Test/Qualities/QualityFixture.cs @@ -1,5 +1,5 @@ -using System.Linq; -using System.Collections.Generic; +using System.Collections.Generic; +using System.Linq; using FluentAssertions; using NUnit.Framework; using NzbDrone.Core.Profiles.Qualities; @@ -13,48 +13,50 @@ public class QualityFixture : CoreTest { public static object[] FromIntCases = { - new object[] {0, Quality.Unknown}, - new object[] {1, Quality.SDTV}, - new object[] {2, Quality.DVD}, - new object[] {3, Quality.WEBDL1080p}, - new object[] {4, Quality.HDTV720p}, - new object[] {5, Quality.WEBDL720p}, - new object[] {6, Quality.Bluray720p}, - new object[] {7, Quality.Bluray1080p}, - new object[] {8, Quality.WEBDL480p}, - new object[] {9, Quality.HDTV1080p}, - new object[] {10, Quality.RAWHD}, - new object[] {16, Quality.HDTV2160p}, - new object[] {18, Quality.WEBDL2160p}, - new object[] {19, Quality.Bluray2160p}, + new object[] { 0, Quality.Unknown }, + new object[] { 1, Quality.SDTV }, + new object[] { 2, Quality.DVD }, + new object[] { 3, Quality.WEBDL1080p }, + new object[] { 4, Quality.HDTV720p }, + new object[] { 5, Quality.WEBDL720p }, + new object[] { 6, Quality.Bluray720p }, + new object[] { 7, Quality.Bluray1080p }, + new object[] { 8, Quality.WEBDL480p }, + new object[] { 9, Quality.HDTV1080p }, + new object[] { 10, Quality.RAWHD }, + new object[] { 16, Quality.HDTV2160p }, + new object[] { 18, Quality.WEBDL2160p }, + new object[] { 19, Quality.Bluray2160p }, }; public static object[] ToIntCases = { - new object[] {Quality.Unknown, 0}, - new object[] {Quality.SDTV, 1}, - new object[] {Quality.DVD, 2}, - new object[] {Quality.WEBDL1080p, 3}, - new object[] {Quality.HDTV720p, 4}, - new object[] {Quality.WEBDL720p, 5}, - new object[] {Quality.Bluray720p, 6}, - new object[] {Quality.Bluray1080p, 7}, - new object[] {Quality.WEBDL480p, 8}, - new object[] {Quality.HDTV1080p, 9}, - new object[] {Quality.RAWHD, 10}, - new object[] {Quality.HDTV2160p, 16}, - new object[] {Quality.WEBDL2160p, 18}, - new object[] {Quality.Bluray2160p, 19}, + new object[] { Quality.Unknown, 0 }, + new object[] { Quality.SDTV, 1 }, + new object[] { Quality.DVD, 2 }, + new object[] { Quality.WEBDL1080p, 3 }, + new object[] { Quality.HDTV720p, 4 }, + new object[] { Quality.WEBDL720p, 5 }, + new object[] { Quality.Bluray720p, 6 }, + new object[] { Quality.Bluray1080p, 7 }, + new object[] { Quality.WEBDL480p, 8 }, + new object[] { Quality.HDTV1080p, 9 }, + new object[] { Quality.RAWHD, 10 }, + new object[] { Quality.HDTV2160p, 16 }, + new object[] { Quality.WEBDL2160p, 18 }, + new object[] { Quality.Bluray2160p, 19 }, }; - [Test, TestCaseSource(nameof(FromIntCases))] + [Test] + [TestCaseSource(nameof(FromIntCases))] public void should_be_able_to_convert_int_to_qualityTypes(int source, Quality expected) { var quality = (Quality)source; quality.Should().Be(expected); } - [Test, TestCaseSource(nameof(ToIntCases))] + [Test] + [TestCaseSource(nameof(ToIntCases))] public void should_be_able_to_convert_qualityTypes_to_int(Quality source, int expected) { var i = (int)source; @@ -82,7 +84,9 @@ public static List GetDefaultQualities(params Quality }; if (allowed.Length == 0) + { allowed = qualities.ToArray(); + } var items = qualities .Except(allowed) diff --git a/src/NzbDrone.Core.Test/Qualities/RevisionComparableFixture.cs b/src/NzbDrone.Core.Test/Qualities/RevisionComparableFixture.cs index e67640c58..5756ede70 100644 --- a/src/NzbDrone.Core.Test/Qualities/RevisionComparableFixture.cs +++ b/src/NzbDrone.Core.Test/Qualities/RevisionComparableFixture.cs @@ -134,10 +134,10 @@ public void less_than_operator_tests() [Test] public void operating_on_nulls() { - (null > new Revision()).Should().BeFalse(); - (null >= new Revision()).Should().BeFalse(); - (null < new Revision()).Should().BeTrue(); - (null <= new Revision()).Should().BeTrue(); + (new Revision() < null).Should().BeFalse(); + (new Revision() <= null).Should().BeFalse(); + (new Revision() > null).Should().BeTrue(); + (new Revision() >= null).Should().BeTrue(); (new Revision() > null).Should().BeTrue(); (new Revision() >= null).Should().BeTrue(); diff --git a/src/NzbDrone.Core.Test/QueueTests/QueueServiceFixture.cs b/src/NzbDrone.Core.Test/QueueTests/QueueServiceFixture.cs index f1ac1293b..6d1fbe328 100644 --- a/src/NzbDrone.Core.Test/QueueTests/QueueServiceFixture.cs +++ b/src/NzbDrone.Core.Test/QueueTests/QueueServiceFixture.cs @@ -1,15 +1,15 @@ using System; using System.Collections.Generic; using System.Linq; -using NUnit.Framework; -using NzbDrone.Core.Download.TrackedDownloads; -using NzbDrone.Core.Queue; -using NzbDrone.Core.Test.Framework; using FizzWare.NBuilder; using FluentAssertions; +using NUnit.Framework; using NzbDrone.Core.Download; -using NzbDrone.Core.Tv; +using NzbDrone.Core.Download.TrackedDownloads; using NzbDrone.Core.Parser.Model; +using NzbDrone.Core.Queue; +using NzbDrone.Core.Test.Framework; +using NzbDrone.Core.Tv; namespace NzbDrone.Core.Test.QueueTests { @@ -35,7 +35,7 @@ public void SetUp() .All() .With(e => e.SeriesId = series.Id) .Build(); - + var remoteEpisode = Builder.CreateNew() .With(r => r.Series = series) .With(r => r.Episodes = new List(episodes)) diff --git a/src/NzbDrone.Core.Test/RemotePathMappingsTests/RemotePathMappingServiceFixture.cs b/src/NzbDrone.Core.Test/RemotePathMappingsTests/RemotePathMappingServiceFixture.cs index 15bda4fd9..47f023c1b 100644 --- a/src/NzbDrone.Core.Test/RemotePathMappingsTests/RemotePathMappingServiceFixture.cs +++ b/src/NzbDrone.Core.Test/RemotePathMappingsTests/RemotePathMappingServiceFixture.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using FizzWare.NBuilder; using FluentAssertions; using Moq; using NUnit.Framework; @@ -7,7 +8,6 @@ using NzbDrone.Core.RemotePathMappings; using NzbDrone.Core.Test.Framework; using NzbDrone.Test.Common; -using FizzWare.NBuilder; namespace NzbDrone.Core.Test.RemotePathMappingsTests { @@ -72,7 +72,7 @@ public void should_be_able_to_remove_mapping() Subject.Remove(1); Mocker.GetMock().Verify(c => c.Delete(1), Times.Once()); } - + [TestCase("my-server.localdomain", "/mnt/storage", @"D:\mountedstorage")] [TestCase("my-server.localdomain", "/mnt/storage", @"D:\mountedstorage2")] public void adding_duplicated_mapping_should_throw(string host, string remotePath, string localPath) @@ -128,7 +128,7 @@ public void should_fix_wrong_slashes_on_add(string remotePath, string cleanedPat { Host = "my-server.localdomain", RemotePath = remotePath, - LocalPath = @"D:\mountedstorage\downloads\tv" .AsOsAgnostic() + LocalPath = @"D:\mountedstorage\downloads\tv".AsOsAgnostic() }; var result = Subject.Add(mapping); @@ -136,4 +136,4 @@ public void should_fix_wrong_slashes_on_add(string remotePath, string cleanedPat result.RemotePath.Should().Be(cleanedPath); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core.Test/RootFolderTests/RootFolderServiceFixture.cs b/src/NzbDrone.Core.Test/RootFolderTests/RootFolderServiceFixture.cs index 5847e8823..102e36e5a 100644 --- a/src/NzbDrone.Core.Test/RootFolderTests/RootFolderServiceFixture.cs +++ b/src/NzbDrone.Core.Test/RootFolderTests/RootFolderServiceFixture.cs @@ -76,8 +76,7 @@ public void should_be_able_to_remove_root_dir() public void invalid_folder_path_throws_on_add(string path) { Assert.Throws(() => - Mocker.Resolve().Add(new RootFolder { Id = 0, Path = path }) - ); + Mocker.Resolve().Add(new RootFolder { Id = 0, Path = path })); } [Test] @@ -142,4 +141,4 @@ public void should_get_root_folder_with_subfolders_excluding_special_sub_folders unmappedFolders.Should().NotContain(u => u.Name == subFolder); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core.Test/SeriesStatsTests/SeriesStatisticsFixture.cs b/src/NzbDrone.Core.Test/SeriesStatsTests/SeriesStatisticsFixture.cs index c8a321bc6..4616e4d6b 100644 --- a/src/NzbDrone.Core.Test/SeriesStatsTests/SeriesStatisticsFixture.cs +++ b/src/NzbDrone.Core.Test/SeriesStatsTests/SeriesStatisticsFixture.cs @@ -38,7 +38,6 @@ public void Setup() .With(e => e.SeriesId = _series.Id) .With(e => e.Quality = new QualityModel(Quality.HDTV720p)) .BuildNew(); - } private void GivenEpisodeWithFile() @@ -177,6 +176,5 @@ public void should_have_size_on_disk_when_episode_file_exists() stats.Should().HaveCount(1); stats.First().SizeOnDisk.Should().Be(_episodeFile.Size); } - } } diff --git a/src/NzbDrone.Core.Test/ThingiProviderTests/ProviderBaseFixture.cs b/src/NzbDrone.Core.Test/ThingiProviderTests/ProviderBaseFixture.cs index 7de6c61b8..1faf6d750 100644 --- a/src/NzbDrone.Core.Test/ThingiProviderTests/ProviderBaseFixture.cs +++ b/src/NzbDrone.Core.Test/ThingiProviderTests/ProviderBaseFixture.cs @@ -23,7 +23,7 @@ public void should_read_write_download_provider() var storedSetting = (NewznabSettings)storedProvider.Settings; - storedSetting.Should().BeEquivalentTo(newznabSettings, o=>o.IncludingAllRuntimeProperties()); + storedSetting.Should().BeEquivalentTo(newznabSettings, o => o.IncludingAllRuntimeProperties()); } } } diff --git a/src/NzbDrone.Core.Test/ThingiProviderTests/ProviderStatusServiceFixture.cs b/src/NzbDrone.Core.Test/ThingiProviderTests/ProviderStatusServiceFixture.cs index 80d533ed2..f9c0d4325 100644 --- a/src/NzbDrone.Core.Test/ThingiProviderTests/ProviderStatusServiceFixture.cs +++ b/src/NzbDrone.Core.Test/ThingiProviderTests/ProviderStatusServiceFixture.cs @@ -29,7 +29,6 @@ public class MockProviderStatusService : ProviderStatusServiceBase e.Monitored = true) .With(e => e.AirDateUtc = DateTime.UtcNow.AddDays(-7)) + //Missing .TheFirst(1) .With(e => e.EpisodeFileId = 0) + //Has File .TheNext(1) .With(e => e.EpisodeFileId = 1) + //Future .TheNext(1) .With(e => e.EpisodeFileId = 0) .With(e => e.AirDateUtc = DateTime.UtcNow.AddDays(7)) + //Future/TBA .TheNext(1) .With(e => e.EpisodeFileId = 0) @@ -62,7 +66,7 @@ private void GivenSpecials() episode.SeasonNumber = 0; } - _series.Seasons = new List{new Season { Monitored = false, SeasonNumber = 0 }}; + _series.Seasons = new List { new Season { Monitored = false, SeasonNumber = 0 } }; } [Test] @@ -167,7 +171,7 @@ public void should_not_monitor_season_when_all_episodes_are_monitored_except_lat .With(e => e.SeasonNumber = 2) .Build() .ToList(); - + Mocker.GetMock() .Setup(s => s.GetEpisodeBySeries(It.IsAny())) .Returns(_episodes); diff --git a/src/NzbDrone.Core.Test/TvTests/EpisodeMonitoredServiceTests/SetEpisodeMontitoredFixture.cs b/src/NzbDrone.Core.Test/TvTests/EpisodeMonitoredServiceTests/SetEpisodeMontitoredFixture.cs index 34755f71d..432eef2ce 100644 --- a/src/NzbDrone.Core.Test/TvTests/EpisodeMonitoredServiceTests/SetEpisodeMontitoredFixture.cs +++ b/src/NzbDrone.Core.Test/TvTests/EpisodeMonitoredServiceTests/SetEpisodeMontitoredFixture.cs @@ -33,16 +33,20 @@ public void Setup() .All() .With(e => e.Monitored = true) .With(e => e.AirDateUtc = DateTime.UtcNow.AddDays(-7)) + //Missing .TheFirst(1) .With(e => e.EpisodeFileId = 0) + //Has File .TheNext(1) .With(e => e.EpisodeFileId = 1) + //Future .TheNext(1) .With(e => e.EpisodeFileId = 0) .With(e => e.AirDateUtc = DateTime.UtcNow.AddDays(7)) + //Future/TBA .TheNext(1) .With(e => e.EpisodeFileId = 0) @@ -62,7 +66,7 @@ private void GivenSpecials() episode.SeasonNumber = 0; } - _series.Seasons = new List{new Season { Monitored = false, SeasonNumber = 0 }}; + _series.Seasons = new List { new Season { Monitored = false, SeasonNumber = 0 } }; } [Test] @@ -163,7 +167,7 @@ public void should_not_monitor_season_when_all_episodes_are_monitored_except_lat .With(e => e.SeasonNumber = 2) .Build() .ToList(); - + Mocker.GetMock() .Setup(s => s.GetEpisodeBySeries(It.IsAny())) .Returns(_episodes); diff --git a/src/NzbDrone.Core.Test/TvTests/EpisodeRepositoryTests/EpisodesRepositoryReadFixture.cs b/src/NzbDrone.Core.Test/TvTests/EpisodeRepositoryTests/EpisodesRepositoryReadFixture.cs index 07a43b9ca..e68d9246b 100644 --- a/src/NzbDrone.Core.Test/TvTests/EpisodeRepositoryTests/EpisodesRepositoryReadFixture.cs +++ b/src/NzbDrone.Core.Test/TvTests/EpisodeRepositoryTests/EpisodesRepositoryReadFixture.cs @@ -11,16 +11,16 @@ namespace NzbDrone.Core.Test.TvTests.EpisodeRepositoryTests [TestFixture] public class EpisodesRepositoryReadFixture : DbTest { - private Series series; + private Series _series; [SetUp] public void Setup() { - series = Builder.CreateNew() + _series = Builder.CreateNew() .With(s => s.Runtime = 30) .BuildNew(); - Db.Insert(series); + Db.Insert(_series); } [Test] @@ -34,7 +34,7 @@ public void should_get_episodes_by_file() var episode = Builder.CreateListOfSize(2) .All() - .With(e => e.SeriesId = series.Id) + .With(e => e.SeriesId = _series.Id) .With(e => e.EpisodeFileId = episodeFile.Id) .BuildListOfNew(); diff --git a/src/NzbDrone.Core.Test/TvTests/EpisodeRepositoryTests/EpisodesWhereCutoffUnmetFixture.cs b/src/NzbDrone.Core.Test/TvTests/EpisodeRepositoryTests/EpisodesWhereCutoffUnmetFixture.cs index 41c2bdc2a..873af5b12 100644 --- a/src/NzbDrone.Core.Test/TvTests/EpisodeRepositoryTests/EpisodesWhereCutoffUnmetFixture.cs +++ b/src/NzbDrone.Core.Test/TvTests/EpisodeRepositoryTests/EpisodesWhereCutoffUnmetFixture.cs @@ -5,13 +5,13 @@ using FluentAssertions; using NUnit.Framework; using NzbDrone.Core.Datastore; +using NzbDrone.Core.Languages; +using NzbDrone.Core.MediaFiles; +using NzbDrone.Core.Profiles.Languages; using NzbDrone.Core.Profiles.Qualities; +using NzbDrone.Core.Qualities; using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Tv; -using NzbDrone.Core.Qualities; -using NzbDrone.Core.MediaFiles; -using NzbDrone.Core.Languages; -using NzbDrone.Core.Profiles.Languages; namespace NzbDrone.Core.Test.TvTests.EpisodeRepositoryTests { @@ -24,16 +24,16 @@ public class EpisodesWhereCutoffUnmetFixture : DbTest _qualitiesBelowCutoff; private List _languagesBelowCutoff; private List _unairedEpisodes; - + [SetUp] public void Setup() { - var profile = new QualityProfile - { + var profile = new QualityProfile + { Id = 1, Cutoff = Quality.WEBDL480p.Id, - Items = new List - { + Items = new List + { new QualityProfileQualityItem { Allowed = true, Quality = Quality.SDTV }, new QualityProfileQualityItem { Allowed = true, Quality = Quality.WEBDL480p }, new QualityProfileQualityItem { Allowed = true, Quality = Quality.RAWHD } @@ -78,15 +78,15 @@ public void Setup() _qualitiesBelowCutoff = new List { - new QualitiesBelowCutoff(profile.Id, new[] {Quality.SDTV.Id}) + new QualitiesBelowCutoff(profile.Id, new[] { Quality.SDTV.Id }) }; _languagesBelowCutoff = new List { - new LanguagesBelowCutoff(profile.Id, new[] {Language.English.Id}) + new LanguagesBelowCutoff(profile.Id, new[] { Language.English.Id }) }; - var qualityMetLanguageUnmet = new EpisodeFile { RelativePath = "a", Quality = new QualityModel { Quality = Quality.WEBDL480p } , Language = Language.English }; + var qualityMetLanguageUnmet = new EpisodeFile { RelativePath = "a", Quality = new QualityModel { Quality = Quality.WEBDL480p }, Language = Language.English }; var qualityMetLanguageMet = new EpisodeFile { RelativePath = "b", Quality = new QualityModel { Quality = Quality.WEBDL480p }, Language = Language.Spanish }; var qualityMetLanguageExceed = new EpisodeFile { RelativePath = "c", Quality = new QualityModel { Quality = Quality.WEBDL480p }, Language = Language.French }; var qualityUnmetLanguageUnmet = new EpisodeFile { RelativePath = "d", Quality = new QualityModel { Quality = Quality.SDTV }, Language = Language.English }; @@ -138,7 +138,6 @@ public void Setup() .With(e => e.SeasonNumber = 0) .Build(); - _unairedEpisodes = Builder.CreateListOfSize(1) .All() .With(e => e.Id = 0) @@ -148,7 +147,7 @@ public void Setup() .With(e => e.EpisodeFileId = qualityUnmetLanguageUnmet.Id) .Build() .ToList(); - + Db.InsertMany(monitoredSeriesEpisodes); Db.InsertMany(unmonitoredSeriesEpisodes); } diff --git a/src/NzbDrone.Core.Test/TvTests/EpisodeRepositoryTests/EpisodesWithFilesFixture.cs b/src/NzbDrone.Core.Test/TvTests/EpisodeRepositoryTests/EpisodesWithFilesFixture.cs index e12a8b1c0..b1b41503a 100644 --- a/src/NzbDrone.Core.Test/TvTests/EpisodeRepositoryTests/EpisodesWithFilesFixture.cs +++ b/src/NzbDrone.Core.Test/TvTests/EpisodeRepositoryTests/EpisodesWithFilesFixture.cs @@ -4,9 +4,9 @@ using FluentAssertions; using NUnit.Framework; using NzbDrone.Core.MediaFiles; +using NzbDrone.Core.Qualities; using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Tv; -using NzbDrone.Core.Qualities; namespace NzbDrone.Core.Test.TvTests.EpisodeRepositoryTests { @@ -42,12 +42,11 @@ public void Setup() Db.InsertMany(_episodes); } - [Test] public void should_only_get_files_that_have_episode_files() { var result = Subject.EpisodesWithFiles(SERIES_ID); - + result.Should().OnlyContain(e => e.EpisodeFileId > 0); result.Should().HaveCount(_episodeFiles.Count); } diff --git a/src/NzbDrone.Core.Test/TvTests/EpisodeRepositoryTests/EpisodesWithoutFilesFixture.cs b/src/NzbDrone.Core.Test/TvTests/EpisodeRepositoryTests/EpisodesWithoutFilesFixture.cs index c9dece998..c8e063819 100644 --- a/src/NzbDrone.Core.Test/TvTests/EpisodeRepositoryTests/EpisodesWithoutFilesFixture.cs +++ b/src/NzbDrone.Core.Test/TvTests/EpisodeRepositoryTests/EpisodesWithoutFilesFixture.cs @@ -72,7 +72,6 @@ public void Setup() .With(e => e.SeasonNumber = 0) .Build(); - var unairedEpisodes = Builder.CreateListOfSize(1) .All() .With(e => e.Id = 0) @@ -82,7 +81,6 @@ public void Setup() .With(e => e.Monitored = true) .Build(); - Db.InsertMany(monitoredSeriesEpisodes); Db.InsertMany(unmonitoredSeriesEpisodes); Db.InsertMany(unairedEpisodes); diff --git a/src/NzbDrone.Core.Test/TvTests/MoveSeriesServiceFixture.cs b/src/NzbDrone.Core.Test/TvTests/MoveSeriesServiceFixture.cs index 370f6388c..80180f5a6 100644 --- a/src/NzbDrone.Core.Test/TvTests/MoveSeriesServiceFixture.cs +++ b/src/NzbDrone.Core.Test/TvTests/MoveSeriesServiceFixture.cs @@ -103,11 +103,11 @@ public void should_build_new_path_when_root_folder_is_provided() { var seriesFolder = "Series"; var expectedPath = Path.Combine(_bulkCommand.DestinationRootFolder, seriesFolder); - + Mocker.GetMock() .Setup(s => s.GetSeriesFolder(It.IsAny(), null)) .Returns(seriesFolder); - + Subject.Execute(_bulkCommand); Mocker.GetMock() @@ -121,9 +121,8 @@ public void should_skip_series_folder_if_it_does_not_exist() .Setup(s => s.FolderExists(It.IsAny())) .Returns(false); - Subject.Execute(_command); - + Mocker.GetMock() .Verify(v => v.TransferFolder(_command.SourcePath, _command.DestinationPath, TransferMode.Move), Times.Never()); diff --git a/src/NzbDrone.Core.Test/TvTests/RefreshEpisodeServiceFixture.cs b/src/NzbDrone.Core.Test/TvTests/RefreshEpisodeServiceFixture.cs index 7876b535e..6df2dd138 100644 --- a/src/NzbDrone.Core.Test/TvTests/RefreshEpisodeServiceFixture.cs +++ b/src/NzbDrone.Core.Test/TvTests/RefreshEpisodeServiceFixture.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using FizzWare.NBuilder; @@ -7,8 +7,8 @@ using NUnit.Framework; using NzbDrone.Common.Extensions; using NzbDrone.Core.MetadataSource.SkyHook; -using NzbDrone.Core.Tv; using NzbDrone.Core.Test.Framework; +using NzbDrone.Core.Tv; using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.TvTests @@ -26,7 +26,7 @@ public void TestFixture() { UseRealHttp(); - _gameOfThrones = Mocker.Resolve().GetSeriesInfo(121361);//Game of thrones + _gameOfThrones = Mocker.Resolve().GetSeriesInfo(121361); //Game of thrones // Remove specials. _gameOfThrones.Item2.RemoveAll(v => v.SeasonNumber == 0); @@ -64,11 +64,9 @@ public void Setup() Mocker.GetMock().Setup(c => c.InsertMany(It.IsAny>())) .Callback>(e => _insertedEpisodes = e); - Mocker.GetMock().Setup(c => c.UpdateMany(It.IsAny>())) .Callback>(e => _updatedEpisodes = e); - Mocker.GetMock().Setup(c => c.DeleteMany(It.IsAny>())) .Callback>(e => _deletedEpisodes = e); } @@ -78,7 +76,7 @@ public void should_create_all_when_no_existing_episodes() { Mocker.GetMock().Setup(c => c.GetEpisodeBySeries(It.IsAny())) .Returns(new List()); - + Subject.RefreshEpisodeInfo(GetSeries(), GetEpisodes()); _insertedEpisodes.Should().HaveSameCount(GetEpisodes()); @@ -280,7 +278,7 @@ public void should_get_new_season_and_episode_numbers_when_absolute_episode_numb existingEpisode.AbsoluteEpisodeNumber = expectedAbsoluteNumber; Mocker.GetMock().Setup(c => c.GetEpisodeBySeries(It.IsAny())) - .Returns(new List{ existingEpisode }); + .Returns(new List { existingEpisode }); Subject.RefreshEpisodeInfo(GetAnimeSeries(), new List { episode }); @@ -339,7 +337,6 @@ public void should_ignore_episodes_with_no_absolute_episode_in_distinct_by_absol Subject.RefreshEpisodeInfo(GetAnimeSeries(), episodes); _insertedEpisodes.Should().HaveCount(episodes.Count); - } [Test] @@ -457,4 +454,4 @@ public void should_prefer_regular_season_when_absolute_numbers_conflict() _updatedEpisodes.First().AbsoluteEpisodeNumber.Should().Be(episodes[1].AbsoluteEpisodeNumber); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core.Test/TvTests/RefreshSeriesServiceFixture.cs b/src/NzbDrone.Core.Test/TvTests/RefreshSeriesServiceFixture.cs index 09e53fa04..cd110555d 100644 --- a/src/NzbDrone.Core.Test/TvTests/RefreshSeriesServiceFixture.cs +++ b/src/NzbDrone.Core.Test/TvTests/RefreshSeriesServiceFixture.cs @@ -40,7 +40,7 @@ public void Setup() Mocker.GetMock() .Setup(s => s.GetSeries(_series.Id)) .Returns(_series); - + Mocker.GetMock() .Setup(s => s.GetSeriesInfo(It.IsAny())) .Callback(p => { throw new SeriesNotFoundException(p); }); @@ -224,7 +224,6 @@ public void should_filter_duplicate_seasons() Mocker.GetMock() .Verify(v => v.UpdateSeries(It.Is(s => s.Seasons.Count == 2), It.IsAny(), It.IsAny())); - } [Test] diff --git a/src/NzbDrone.Core.Test/TvTests/SeriesFolderPathBuilderFixture.cs b/src/NzbDrone.Core.Test/TvTests/SeriesFolderPathBuilderFixture.cs index 93343034f..616ea1e77 100644 --- a/src/NzbDrone.Core.Test/TvTests/SeriesFolderPathBuilderFixture.cs +++ b/src/NzbDrone.Core.Test/TvTests/SeriesFolderPathBuilderFixture.cs @@ -32,6 +32,7 @@ public void GivenSeriesFolderName(string name) .Setup(s => s.GetSeriesFolder(_series, null)) .Returns(name); } + public void GivenExistingRootFolder(string rootFolder) { Mocker.GetMock() @@ -47,7 +48,6 @@ public void should_create_new_series_path() GivenSeriesFolderName(_series.Title); _series.RootFolderPath = rootFolder; - Subject.BuildPath(_series, false).Should().Be(Path.Combine(rootFolder, _series.Title)); } @@ -75,7 +75,7 @@ public void should_reuse_existing_relative_folder_structure() GivenSeriesFolderName(_series.Title); _series.RootFolderPath = rootFolder; _series.Path = Path.Combine(existingRootFolder, existingRelativePath); - + Subject.BuildPath(_series, true).Should().Be(Path.Combine(rootFolder, existingRelativePath)); } diff --git a/src/NzbDrone.Core.Test/TvTests/SeriesRepositoryTests/SeriesRepositoryFixture.cs b/src/NzbDrone.Core.Test/TvTests/SeriesRepositoryTests/SeriesRepositoryFixture.cs index a3107de93..508fb2f64 100644 --- a/src/NzbDrone.Core.Test/TvTests/SeriesRepositoryTests/SeriesRepositoryFixture.cs +++ b/src/NzbDrone.Core.Test/TvTests/SeriesRepositoryTests/SeriesRepositoryFixture.cs @@ -1,13 +1,13 @@ -using FizzWare.NBuilder; +using System.Linq; +using FizzWare.NBuilder; using FluentAssertions; using NUnit.Framework; -using System.Linq; using NzbDrone.Core.Languages; +using NzbDrone.Core.Profiles.Languages; using NzbDrone.Core.Profiles.Qualities; using NzbDrone.Core.Qualities; using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Tv; -using NzbDrone.Core.Profiles.Languages; namespace NzbDrone.Core.Test.TvTests.SeriesRepositoryTests { @@ -33,7 +33,6 @@ public void should_lazyload_quality_profile() Cutoff = Language.English }; - Mocker.Resolve().Insert(profile); Mocker.Resolve().Insert(langProfile); @@ -43,11 +42,8 @@ public void should_lazyload_quality_profile() Subject.Insert(series); - StoredModel.QualityProfile.Should().NotBeNull(); StoredModel.LanguageProfile.Should().NotBeNull(); - - } private void GivenSeries() @@ -72,7 +68,6 @@ public void should_find_no_inexact_matches(string cleanTitle) found.Should().BeEmpty(); } - [TestCase("crowna")] [TestCase("acrown")] [TestCase("acrowna")] @@ -95,7 +90,7 @@ public void should_find_two_inexact_matches(string cleanTitle) var found = Subject.FindByTitleInexact(cleanTitle); found.Should().HaveCount(2); - found.Select(x => x.CleanTitle).Should().BeEquivalentTo(new [] {"crown", "crownextralong"}); + found.Select(x => x.CleanTitle).Should().BeEquivalentTo(new[] { "crown", "crownextralong" }); } } } diff --git a/src/NzbDrone.Core.Test/TvTests/SeriesServiceTests/UpdateMultipleSeriesFixture.cs b/src/NzbDrone.Core.Test/TvTests/SeriesServiceTests/UpdateMultipleSeriesFixture.cs index 81dbdce75..34750be4d 100644 --- a/src/NzbDrone.Core.Test/TvTests/SeriesServiceTests/UpdateMultipleSeriesFixture.cs +++ b/src/NzbDrone.Core.Test/TvTests/SeriesServiceTests/UpdateMultipleSeriesFixture.cs @@ -7,8 +7,8 @@ using NUnit.Framework; using NzbDrone.Core.Organizer; using NzbDrone.Core.RootFolders; -using NzbDrone.Core.Tv; using NzbDrone.Core.Test.Framework; +using NzbDrone.Core.Tv; using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.TvTests.SeriesServiceTests diff --git a/src/NzbDrone.Core.Test/TvTests/SeriesServiceTests/UpdateSeriesFixture.cs b/src/NzbDrone.Core.Test/TvTests/SeriesServiceTests/UpdateSeriesFixture.cs index cfe23d4ca..cc753b716 100644 --- a/src/NzbDrone.Core.Test/TvTests/SeriesServiceTests/UpdateSeriesFixture.cs +++ b/src/NzbDrone.Core.Test/TvTests/SeriesServiceTests/UpdateSeriesFixture.cs @@ -3,8 +3,8 @@ using FizzWare.NBuilder; using Moq; using NUnit.Framework; -using NzbDrone.Core.Tv; using NzbDrone.Core.Test.Framework; +using NzbDrone.Core.Tv; namespace NzbDrone.Core.Test.TvTests.SeriesServiceTests { @@ -22,14 +22,14 @@ public void Setup() _fakeSeries.Seasons = new List { - new Season{ SeasonNumber = 1, Monitored = true }, - new Season{ SeasonNumber = 2, Monitored = true } + new Season { SeasonNumber = 1, Monitored = true }, + new Season { SeasonNumber = 2, Monitored = true } }; _existingSeries.Seasons = new List { - new Season{ SeasonNumber = 1, Monitored = true }, - new Season{ SeasonNumber = 2, Monitored = true } + new Season { SeasonNumber = 1, Monitored = true }, + new Season { SeasonNumber = 2, Monitored = true } }; } @@ -69,4 +69,4 @@ public void should_update_series_when_it_changes() .Verify(v => v.SetEpisodeMonitoredBySeason(_fakeSeries.Id, It.IsAny(), It.IsAny()), Times.Once()); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core.Test/TvTests/ShouldRefreshSeriesFixture.cs b/src/NzbDrone.Core.Test/TvTests/ShouldRefreshSeriesFixture.cs index 8b8fd64d5..b872c2314 100644 --- a/src/NzbDrone.Core.Test/TvTests/ShouldRefreshSeriesFixture.cs +++ b/src/NzbDrone.Core.Test/TvTests/ShouldRefreshSeriesFixture.cs @@ -12,7 +12,7 @@ namespace NzbDrone.Core.Test.TvTests public class ShouldRefreshSeriesFixture : TestBase { private Series _series; - + [SetUp] public void Setup() { diff --git a/src/NzbDrone.Core.Test/UpdateTests/UpdatePackageProviderFixture.cs b/src/NzbDrone.Core.Test/UpdateTests/UpdatePackageProviderFixture.cs index bf57792bd..661121299 100644 --- a/src/NzbDrone.Core.Test/UpdateTests/UpdatePackageProviderFixture.cs +++ b/src/NzbDrone.Core.Test/UpdateTests/UpdatePackageProviderFixture.cs @@ -43,7 +43,6 @@ public void should_get_master_if_branch_doesnt_exit() Subject.GetLatestUpdate("invalid_branch", new Version(3, 0)).Should().NotBeNull(); } - [Test] public void should_get_recent_updates() { diff --git a/src/NzbDrone.Core.Test/UpdateTests/UpdateServiceFixture.cs b/src/NzbDrone.Core.Test/UpdateTests/UpdateServiceFixture.cs index c6d00fd26..1c5f302df 100644 --- a/src/NzbDrone.Core.Test/UpdateTests/UpdateServiceFixture.cs +++ b/src/NzbDrone.Core.Test/UpdateTests/UpdateServiceFixture.cs @@ -40,7 +40,6 @@ public void Setup() Version = new Version("2.0.0.0") }; } - else { _updatePackage = new UpdatePackage @@ -108,7 +107,6 @@ public void should_not_delete_sandbox_before_update_if_folder_doesnt_exists() Subject.Execute(new ApplicationUpdateCommand()); - Mocker.GetMock().Verify(c => c.DeleteFolder(_sandboxFolder, true), Times.Never()); } @@ -174,7 +172,6 @@ public void should_return_without_error_or_warnings_when_no_updates_are_availabl Subject.Execute(new ApplicationUpdateCommand()); - ExceptionVerification.AssertNoUnexpectedLogs(); } diff --git a/src/NzbDrone.Core/Analytics/AnalyticsService.cs b/src/NzbDrone.Core/Analytics/AnalyticsService.cs index e8735aece..6c71576a7 100644 --- a/src/NzbDrone.Core/Analytics/AnalyticsService.cs +++ b/src/NzbDrone.Core/Analytics/AnalyticsService.cs @@ -24,7 +24,7 @@ public AnalyticsService(IHistoryService historyService, IConfigFileProvider conf _historyService = historyService; } - public bool IsEnabled => _configFileProvider.AnalyticsEnabled && RuntimeInfo.IsProduction || RuntimeInfo.IsDevelopment; + public bool IsEnabled => (_configFileProvider.AnalyticsEnabled && RuntimeInfo.IsProduction) || RuntimeInfo.IsDevelopment; public bool InstallIsActive { @@ -33,8 +33,8 @@ public bool InstallIsActive var lastRecord = _historyService.Paged(new PagingSpec() { Page = 0, PageSize = 1, SortKey = "date", SortDirection = SortDirection.Descending }); var monthAgo = DateTime.UtcNow.AddMonths(-1); - return lastRecord.Records.Any(v => v.Date > monthAgo); + return lastRecord.Records.Any(v => v.Date > monthAgo); } } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Backup/MakeDatabaseBackup.cs b/src/NzbDrone.Core/Backup/MakeDatabaseBackup.cs index bafcd8232..48ca9fb9c 100644 --- a/src/NzbDrone.Core/Backup/MakeDatabaseBackup.cs +++ b/src/NzbDrone.Core/Backup/MakeDatabaseBackup.cs @@ -1,12 +1,12 @@ using System; using System.Collections.Generic; +using System.Data; using System.Data.SQLite; using System.IO; using System.Linq; using System.Text; using NLog; using NzbDrone.Core.Datastore; -using System.Data; namespace NzbDrone.Core.Backup { @@ -30,6 +30,7 @@ public void BackupDatabase(IDatabase database, string targetDirectory) var backupConnectionStringBuilder = new SQLiteConnectionStringBuilder(sourceConnectionString); backupConnectionStringBuilder.DataSource = Path.Combine(targetDirectory, Path.GetFileName(backupConnectionStringBuilder.DataSource)); + // We MUST use journal mode instead of WAL coz WAL has issues when page sizes change. This should also automatically deal with the -journal and -wal files during restore. backupConnectionStringBuilder.JournalMode = SQLiteJournalModeEnum.Truncate; diff --git a/src/NzbDrone.Core/Backup/RestoreBackupFailedException.cs b/src/NzbDrone.Core/Backup/RestoreBackupFailedException.cs index 3a06b1b1b..40c4d2216 100644 --- a/src/NzbDrone.Core/Backup/RestoreBackupFailedException.cs +++ b/src/NzbDrone.Core/Backup/RestoreBackupFailedException.cs @@ -5,11 +5,13 @@ namespace NzbDrone.Core.Backup { public class RestoreBackupFailedException : NzbDroneClientException { - public RestoreBackupFailedException(HttpStatusCode statusCode, string message, params object[] args) : base(statusCode, message, args) + public RestoreBackupFailedException(HttpStatusCode statusCode, string message, params object[] args) + : base(statusCode, message, args) { } - public RestoreBackupFailedException(HttpStatusCode statusCode, string message) : base(statusCode, message) + public RestoreBackupFailedException(HttpStatusCode statusCode, string message) + : base(statusCode, message) { } } diff --git a/src/NzbDrone.Core/Blocklisting/Blocklist.cs b/src/NzbDrone.Core/Blocklisting/Blocklist.cs index 7ba4de8ae..b70f5d53d 100644 --- a/src/NzbDrone.Core/Blocklisting/Blocklist.cs +++ b/src/NzbDrone.Core/Blocklisting/Blocklist.cs @@ -2,9 +2,9 @@ using System.Collections.Generic; using NzbDrone.Core.Datastore; using NzbDrone.Core.Indexers; +using NzbDrone.Core.Languages; using NzbDrone.Core.Qualities; using NzbDrone.Core.Tv; -using NzbDrone.Core.Languages; namespace NzbDrone.Core.Blocklisting { diff --git a/src/NzbDrone.Core/Blocklisting/BlocklistRepository.cs b/src/NzbDrone.Core/Blocklisting/BlocklistRepository.cs index c62caeb3b..fbc2e8b6f 100644 --- a/src/NzbDrone.Core/Blocklisting/BlocklistRepository.cs +++ b/src/NzbDrone.Core/Blocklisting/BlocklistRepository.cs @@ -1,7 +1,7 @@ using System.Collections.Generic; +using Marr.Data.QGen; using NzbDrone.Core.Datastore; using NzbDrone.Core.Messaging.Events; -using Marr.Data.QGen; using NzbDrone.Core.Tv; namespace NzbDrone.Core.Blocklisting @@ -15,8 +15,8 @@ public interface IBlocklistRepository : IBasicRepository public class BlocklistRepository : BasicRepository, IBlocklistRepository { - public BlocklistRepository(IMainDatabase database, IEventAggregator eventAggregator) : - base(database, eventAggregator) + public BlocklistRepository(IMainDatabase database, IEventAggregator eventAggregator) + : base(database, eventAggregator) { } diff --git a/src/NzbDrone.Core/Blocklisting/BlocklistService.cs b/src/NzbDrone.Core/Blocklisting/BlocklistService.cs index a4fb72b6d..33b84dfb8 100644 --- a/src/NzbDrone.Core/Blocklisting/BlocklistService.cs +++ b/src/NzbDrone.Core/Blocklisting/BlocklistService.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using NzbDrone.Common.Extensions; @@ -20,6 +20,7 @@ public interface IBlocklistService void Delete(int id); void Delete(List ids); } + public class BlocklistService : IBlocklistService, IExecute, IHandle, @@ -35,12 +36,15 @@ public BlocklistService(IBlocklistRepository blocklistRepository) public bool Blocklisted(int seriesId, ReleaseInfo release) { var blocklistedByTitle = _blocklistRepository.BlocklistedByTitle(seriesId, release.Title); - + if (release.DownloadProtocol == DownloadProtocol.Torrent) { var torrentInfo = release as TorrentInfo; - if (torrentInfo == null) return false; + if (torrentInfo == null) + { + return false; + } if (torrentInfo.InfoHash.IsNullOrWhiteSpace()) { @@ -79,7 +83,6 @@ public void Block(RemoteEpisode remoteEpisode, string message) Language = remoteEpisode.ParsedEpisodeInfo.Language }; - if (remoteEpisode.Release is TorrentInfo torrentRelease) { blocklist.TorrentInfoHash = torrentRelease.InfoHash; @@ -137,7 +140,10 @@ private bool HasSameIndexer(Blocklist item, string indexer) private bool HasSamePublishedDate(Blocklist item, DateTime publishedDate) { - if (!item.PublishedDate.HasValue) return true; + if (!item.PublishedDate.HasValue) + { + return true; + } return item.PublishedDate.Value.AddMinutes(-2) <= publishedDate && item.PublishedDate.Value.AddMinutes(2) >= publishedDate; @@ -145,7 +151,10 @@ private bool HasSamePublishedDate(Blocklist item, DateTime publishedDate) private bool HasSameSize(Blocklist item, long size) { - if (!item.Size.HasValue) return true; + if (!item.Size.HasValue) + { + return true; + } var difference = Math.Abs(item.Size.Value - size); diff --git a/src/NzbDrone.Core/Configuration/Config.cs b/src/NzbDrone.Core/Configuration/Config.cs index 7aa02522a..ba380e5b5 100644 --- a/src/NzbDrone.Core/Configuration/Config.cs +++ b/src/NzbDrone.Core/Configuration/Config.cs @@ -14,4 +14,4 @@ public string Key public string Value { get; set; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Configuration/ConfigFileProvider.cs b/src/NzbDrone.Core/Configuration/ConfigFileProvider.cs index a97c337e2..ffe0d95ed 100644 --- a/src/NzbDrone.Core/Configuration/ConfigFileProvider.cs +++ b/src/NzbDrone.Core/Configuration/ConfigFileProvider.cs @@ -210,10 +210,11 @@ public string InstanceName { var instanceName = GetValue("InstanceName", BuildInfo.AppName); - if (instanceName.StartsWith(BuildInfo.AppName) || instanceName.EndsWith(BuildInfo.AppName) ) + if (instanceName.StartsWith(BuildInfo.AppName) || instanceName.EndsWith(BuildInfo.AppName)) { return instanceName; } + return BuildInfo.AppName; } } @@ -286,7 +287,6 @@ public void SetValue(string key, object value) { parentContainer.Add(new XElement(key, valueString)); } - else { parentContainer.Descendants(key).Single().Value = valueString; @@ -360,7 +360,6 @@ private XDocument LoadConfigFile() return xDoc; } } - catch (XmlException ex) { throw new InvalidConfigFileException($"{_configFile} is corrupt is invalid. Please delete the config file and Sonarr will recreate it.", ex); diff --git a/src/NzbDrone.Core/Configuration/ConfigRepository.cs b/src/NzbDrone.Core/Configuration/ConfigRepository.cs index c9092c7e5..c8ae80c21 100644 --- a/src/NzbDrone.Core/Configuration/ConfigRepository.cs +++ b/src/NzbDrone.Core/Configuration/ConfigRepository.cs @@ -2,7 +2,6 @@ using NzbDrone.Core.Datastore; using NzbDrone.Core.Messaging.Events; - namespace NzbDrone.Core.Configuration { public interface IConfigRepository : IBasicRepository @@ -18,7 +17,6 @@ public ConfigRepository(IMainDatabase database, IEventAggregator eventAggregator { } - public Config Get(string key) { return Query.Where(c => c.Key == key).SingleOrDefault(); @@ -30,7 +28,7 @@ public Config Upsert(string key, string value) if (dbValue == null) { - return Insert(new Config {Key = key, Value = value}); + return Insert(new Config { Key = key, Value = value }); } dbValue.Value = value; @@ -38,4 +36,4 @@ public Config Upsert(string key, string value) return Update(dbValue); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Configuration/ConfigService.cs b/src/NzbDrone.Core/Configuration/ConfigService.cs index 8cbbaff2d..ab5fed0bd 100644 --- a/src/NzbDrone.Core/Configuration/ConfigService.cs +++ b/src/NzbDrone.Core/Configuration/ConfigService.cs @@ -4,11 +4,11 @@ using System.Linq; using NLog; using NzbDrone.Common.EnsureThat; +using NzbDrone.Common.Http.Proxy; using NzbDrone.Core.Configuration.Events; using NzbDrone.Core.MediaFiles; -using NzbDrone.Core.Messaging.Events; -using NzbDrone.Common.Http.Proxy; using NzbDrone.Core.MediaFiles.EpisodeImport; +using NzbDrone.Core.Messaging.Events; using NzbDrone.Core.Qualities; using NzbDrone.Core.Security; @@ -58,7 +58,10 @@ public void SaveConfigDictionary(Dictionary configValues) { object currentValue; allWithDefaults.TryGetValue(configValue.Key, out currentValue); - if (currentValue == null || configValue.Value == null) continue; + if (currentValue == null || configValue.Value == null) + { + continue; + } var equal = configValue.Value.ToString().Equals(currentValue.ToString()); diff --git a/src/NzbDrone.Core/Configuration/DeploymentInfoProvider.cs b/src/NzbDrone.Core/Configuration/DeploymentInfoProvider.cs index 876fee42d..5f36ed28c 100644 --- a/src/NzbDrone.Core/Configuration/DeploymentInfoProvider.cs +++ b/src/NzbDrone.Core/Configuration/DeploymentInfoProvider.cs @@ -1,7 +1,3 @@ -using NzbDrone.Common.Disk; -using NzbDrone.Common.EnvironmentInfo; -using NzbDrone.Common.Extensions; -using NzbDrone.Core.Update; using System; using System.Collections.Generic; using System.IO; @@ -9,6 +5,10 @@ using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; +using NzbDrone.Common.Disk; +using NzbDrone.Common.EnvironmentInfo; +using NzbDrone.Common.Extensions; +using NzbDrone.Core.Update; namespace NzbDrone.Core.Configuration { @@ -108,7 +108,6 @@ private static T ReadEnumValue(string fileData, string key, T defaultValue) public string ReleaseVersion { get; private set; } public string ReleaseBranch { get; set; } - public bool IsExternalUpdateMechanism => PackageUpdateMechanism >= UpdateMechanism.External; public UpdateMechanism DefaultUpdateMechanism { get; private set; } public string DefaultBranch { get; private set; } diff --git a/src/NzbDrone.Core/Configuration/IConfigService.cs b/src/NzbDrone.Core/Configuration/IConfigService.cs index 3ef1fbf93..6b01ed8e0 100644 --- a/src/NzbDrone.Core/Configuration/IConfigService.cs +++ b/src/NzbDrone.Core/Configuration/IConfigService.cs @@ -1,6 +1,6 @@ using System.Collections.Generic; -using NzbDrone.Core.MediaFiles; using NzbDrone.Common.Http.Proxy; +using NzbDrone.Core.MediaFiles; using NzbDrone.Core.MediaFiles.EpisodeImport; using NzbDrone.Core.Qualities; using NzbDrone.Core.Security; diff --git a/src/NzbDrone.Core/Configuration/InvalidConfigFileException.cs b/src/NzbDrone.Core/Configuration/InvalidConfigFileException.cs index 1251cf30a..4bed2f2a2 100644 --- a/src/NzbDrone.Core/Configuration/InvalidConfigFileException.cs +++ b/src/NzbDrone.Core/Configuration/InvalidConfigFileException.cs @@ -5,11 +5,13 @@ namespace NzbDrone.Core.Configuration { public class InvalidConfigFileException : NzbDroneException { - public InvalidConfigFileException(string message) : base(message) + public InvalidConfigFileException(string message) + : base(message) { } - public InvalidConfigFileException(string message, Exception innerException) : base(message, innerException) + public InvalidConfigFileException(string message, Exception innerException) + : base(message, innerException) { } } diff --git a/src/NzbDrone.Core/DataAugmentation/DailySeries/DailySeries.cs b/src/NzbDrone.Core/DataAugmentation/DailySeries/DailySeries.cs index 829ce6a24..d9c37d58d 100644 --- a/src/NzbDrone.Core/DataAugmentation/DailySeries/DailySeries.cs +++ b/src/NzbDrone.Core/DataAugmentation/DailySeries/DailySeries.cs @@ -4,4 +4,4 @@ public class DailySeries { public int TvdbId { get; set; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/DataAugmentation/DailySeries/DailySeriesDataProxy.cs b/src/NzbDrone.Core/DataAugmentation/DailySeries/DailySeriesDataProxy.cs index 6d1778bdc..41eae4f29 100644 --- a/src/NzbDrone.Core/DataAugmentation/DailySeries/DailySeriesDataProxy.cs +++ b/src/NzbDrone.Core/DataAugmentation/DailySeries/DailySeriesDataProxy.cs @@ -43,4 +43,4 @@ public IEnumerable GetDailySeriesIds() } } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/DataAugmentation/DailySeries/DailySeriesService.cs b/src/NzbDrone.Core/DataAugmentation/DailySeries/DailySeriesService.cs index 6eb5f874a..1f4e1e9b3 100644 --- a/src/NzbDrone.Core/DataAugmentation/DailySeries/DailySeriesService.cs +++ b/src/NzbDrone.Core/DataAugmentation/DailySeries/DailySeriesService.cs @@ -27,4 +27,4 @@ public bool IsDailySeries(int tvdbid) return dailySeries.Any(i => i == tvdbid); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/DataAugmentation/Scene/InvalidSceneMappingException.cs b/src/NzbDrone.Core/DataAugmentation/Scene/InvalidSceneMappingException.cs index 9e291eeb6..f2126ae39 100644 --- a/src/NzbDrone.Core/DataAugmentation/Scene/InvalidSceneMappingException.cs +++ b/src/NzbDrone.Core/DataAugmentation/Scene/InvalidSceneMappingException.cs @@ -11,7 +11,6 @@ public class InvalidSceneMappingException : NzbDroneException public InvalidSceneMappingException(IEnumerable mappings, string releaseTitle) : base(FormatMessage(mappings, releaseTitle)) { - } private static string FormatMessage(IEnumerable mappings, string releaseTitle) diff --git a/src/NzbDrone.Core/DataAugmentation/Scene/SceneMappingProxy.cs b/src/NzbDrone.Core/DataAugmentation/Scene/SceneMappingProxy.cs index 735af870b..1e9cdabdc 100644 --- a/src/NzbDrone.Core/DataAugmentation/Scene/SceneMappingProxy.cs +++ b/src/NzbDrone.Core/DataAugmentation/Scene/SceneMappingProxy.cs @@ -29,4 +29,4 @@ public List Fetch() return _httpClient.Get>(request).Resource; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/DataAugmentation/Scene/SceneMappingRepository.cs b/src/NzbDrone.Core/DataAugmentation/Scene/SceneMappingRepository.cs index ce86916ec..a456afabf 100644 --- a/src/NzbDrone.Core/DataAugmentation/Scene/SceneMappingRepository.cs +++ b/src/NzbDrone.Core/DataAugmentation/Scene/SceneMappingRepository.cs @@ -1,7 +1,6 @@ +using System.Collections.Generic; using NzbDrone.Core.Datastore; using NzbDrone.Core.Messaging.Events; -using System.Collections.Generic; - namespace NzbDrone.Core.DataAugmentation.Scene { @@ -28,4 +27,4 @@ public void Clear(string type) Delete(s => s.Type == type); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/DataAugmentation/Scene/SceneMappingService.cs b/src/NzbDrone.Core/DataAugmentation/Scene/SceneMappingService.cs index dd088f851..94e30fec0 100644 --- a/src/NzbDrone.Core/DataAugmentation/Scene/SceneMappingService.cs +++ b/src/NzbDrone.Core/DataAugmentation/Scene/SceneMappingService.cs @@ -61,7 +61,7 @@ public List GetSceneNames(int tvdbId, List seasonNumbers, List var names = mappings.Where(n => seasonNumbers.Contains(n.SeasonNumber ?? -1) || sceneSeasonNumbers.Contains(n.SceneSeasonNumber ?? -1) || - (n.SeasonNumber ?? -1) == -1 && (n.SceneSeasonNumber ?? -1) == -1 && n.SceneOrigin != "tvdb") + ((n.SeasonNumber ?? -1) == -1 && (n.SceneSeasonNumber ?? -1) == -1 && n.SceneOrigin != "tvdb")) .Where(n => IsEnglish(n.SearchTerm)) .Select(n => n.SearchTerm).Distinct().ToList(); @@ -209,7 +209,6 @@ private List FindMappings(string seriesTitle, string releaseTitle) .ThenByDescending(v => v.SeasonNumber) .First(); - return candidates.Where(v => v.Title == closestMatch.Title).ToList(); } @@ -280,7 +279,7 @@ public void Handle(SeriesRefreshStartingEvent message) UpdateMappings(); } } - + public void Handle(SeriesAddedEvent message) { if (!_updatedAfterStartup) diff --git a/src/NzbDrone.Core/DataAugmentation/Scene/UpdateSceneMappingCommand.cs b/src/NzbDrone.Core/DataAugmentation/Scene/UpdateSceneMappingCommand.cs index 215f8e033..630b69a51 100644 --- a/src/NzbDrone.Core/DataAugmentation/Scene/UpdateSceneMappingCommand.cs +++ b/src/NzbDrone.Core/DataAugmentation/Scene/UpdateSceneMappingCommand.cs @@ -4,6 +4,5 @@ namespace NzbDrone.Core.DataAugmentation.Scene { public class UpdateSceneMappingCommand : Command { - } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/DataAugmentation/Xem/XemProxy.cs b/src/NzbDrone.Core/DataAugmentation/Xem/XemProxy.cs index 21955da6d..473ed8968 100644 --- a/src/NzbDrone.Core/DataAugmentation/Xem/XemProxy.cs +++ b/src/NzbDrone.Core/DataAugmentation/Xem/XemProxy.cs @@ -95,7 +95,7 @@ public List GetSceneTvdbNames() continue; } - //hack to deal with Fate/Zero + //hack to deal with Fate/Zero if (series.Key == 79151 && seasonNumber > 1) { continue; diff --git a/src/NzbDrone.Core/DataAugmentation/Xem/XemService.cs b/src/NzbDrone.Core/DataAugmentation/Xem/XemService.cs index c8443674c..a8c13b7d8 100644 --- a/src/NzbDrone.Core/DataAugmentation/Xem/XemService.cs +++ b/src/NzbDrone.Core/DataAugmentation/Xem/XemService.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using NLog; @@ -20,7 +20,9 @@ public class XemService : ISceneMappingProvider, IHandle, IH public XemService(IEpisodeService episodeService, IXemProxy xemProxy, - ISeriesService seriesService, ICacheManager cacheManager, Logger logger) + ISeriesService seriesService, + ICacheManager cacheManager, + Logger logger) { _episodeService = episodeService; _xemProxy = xemProxy; @@ -112,8 +114,15 @@ private void ExtrapolateMappings(Series series, List episodes, List episodes, List v.Tvdb.Season == episode.SeasonNumber).ToList(); if (seasonMappings.Any(v => v.Tvdb.Episode >= episode.EpisodeNumber)) @@ -173,6 +197,7 @@ private void ExtrapolateMappings(Series series, List episodes, List where TModel : ModelBase, new() + public interface IBasicRepository + where TModel : ModelBase, new() { IEnumerable All(); int Count(); @@ -36,7 +37,8 @@ namespace NzbDrone.Core.Datastore PagingSpec GetPaged(PagingSpec pagingSpec); } - public class BasicRepository : IBasicRepository where TModel : ModelBase, new() + public class BasicRepository : IBasicRepository + where TModel : ModelBase, new() { private readonly IDatabase _database; private readonly IEventAggregator _eventAggregator; @@ -191,6 +193,7 @@ public TModel Upsert(TModel model) Insert(model); return model; } + Update(model); return model; } diff --git a/src/NzbDrone.Core/Datastore/ConnectionStringFactory.cs b/src/NzbDrone.Core/Datastore/ConnectionStringFactory.cs index a69883dc1..8db300f6e 100644 --- a/src/NzbDrone.Core/Datastore/ConnectionStringFactory.cs +++ b/src/NzbDrone.Core/Datastore/ConnectionStringFactory.cs @@ -40,7 +40,7 @@ private static string GetConnectionString(string dbPath) connectionBuilder.JournalMode = OsInfo.IsOsx ? SQLiteJournalModeEnum.Truncate : SQLiteJournalModeEnum.Wal; connectionBuilder.Pooling = true; connectionBuilder.Version = 3; - + if (OsInfo.IsOsx) { connectionBuilder.Add("Full FSync", true); @@ -49,4 +49,4 @@ private static string GetConnectionString(string dbPath) return connectionBuilder.ConnectionString; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Datastore/Converters/BooleanIntConverter.cs b/src/NzbDrone.Core/Datastore/Converters/BooleanIntConverter.cs index 397746b23..8b4d39ee5 100644 --- a/src/NzbDrone.Core/Datastore/Converters/BooleanIntConverter.cs +++ b/src/NzbDrone.Core/Datastore/Converters/BooleanIntConverter.cs @@ -1,4 +1,4 @@ -using System; +using System; using Marr.Data.Converters; using Marr.Data.Mapping; @@ -33,7 +33,7 @@ public object FromDB(ColumnMap map, object dbValue) public object ToDB(object clrValue) { - var val = (Nullable)clrValue; + var val = (bool?)clrValue; switch (val) { @@ -48,4 +48,4 @@ public object ToDB(object clrValue) public Type DbType => typeof(int); } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Datastore/Converters/EmbeddedDocumentConverter.cs b/src/NzbDrone.Core/Datastore/Converters/EmbeddedDocumentConverter.cs index c776b3ea1..19ca6ff4f 100644 --- a/src/NzbDrone.Core/Datastore/Converters/EmbeddedDocumentConverter.cs +++ b/src/NzbDrone.Core/Datastore/Converters/EmbeddedDocumentConverter.cs @@ -1,19 +1,19 @@ -using System; +using System; using Marr.Data.Converters; using Marr.Data.Mapping; using Newtonsoft.Json; -using Newtonsoft.Json.Serialization; using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Serialization; namespace NzbDrone.Core.Datastore.Converters { public class EmbeddedDocumentConverter : IConverter { - protected readonly JsonSerializerSettings SerializerSetting; + protected readonly JsonSerializerSettings _serializerSetting; public EmbeddedDocumentConverter(params JsonConverter[] converters) { - SerializerSetting = new JsonSerializerSettings + _serializerSetting = new JsonSerializerSettings { DateTimeZoneHandling = DateTimeZoneHandling.Utc, NullValueHandling = NullValueHandling.Ignore, @@ -22,12 +22,12 @@ public EmbeddedDocumentConverter(params JsonConverter[] converters) ContractResolver = new CamelCasePropertyNamesContractResolver() }; - SerializerSetting.Converters.Add(new StringEnumConverter { NamingStrategy = new CamelCaseNamingStrategy() }); - SerializerSetting.Converters.Add(new VersionConverter()); + _serializerSetting.Converters.Add(new StringEnumConverter { NamingStrategy = new CamelCaseNamingStrategy() }); + _serializerSetting.Converters.Add(new VersionConverter()); foreach (var converter in converters) { - SerializerSetting.Converters.Add(converter); + _serializerSetting.Converters.Add(converter); } } @@ -44,7 +44,8 @@ public virtual object FromDB(ConverterContext context) { return null; } - return JsonConvert.DeserializeObject(stringValue, context.ColumnMap.FieldType, SerializerSetting); + + return JsonConvert.DeserializeObject(stringValue, context.ColumnMap.FieldType, _serializerSetting); } public object FromDB(ColumnMap map, object dbValue) @@ -54,12 +55,19 @@ public object FromDB(ColumnMap map, object dbValue) public object ToDB(object clrValue) { - if (clrValue == null) return null; - if (clrValue == DBNull.Value) return DBNull.Value; + if (clrValue == null) + { + return null; + } - return JsonConvert.SerializeObject(clrValue, SerializerSetting); + if (clrValue == DBNull.Value) + { + return DBNull.Value; + } + + return JsonConvert.SerializeObject(clrValue, _serializerSetting); } public Type DbType => typeof(string); } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Datastore/Converters/EnumIntConverter.cs b/src/NzbDrone.Core/Datastore/Converters/EnumIntConverter.cs index 3f501fea6..a88eb5454 100644 --- a/src/NzbDrone.Core/Datastore/Converters/EnumIntConverter.cs +++ b/src/NzbDrone.Core/Datastore/Converters/EnumIntConverter.cs @@ -33,4 +33,4 @@ public object ToDB(object clrValue) return DBNull.Value; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Datastore/Converters/LanguageIntConverter.cs b/src/NzbDrone.Core/Datastore/Converters/LanguageIntConverter.cs index 0d71b1b72..f0c4d705b 100644 --- a/src/NzbDrone.Core/Datastore/Converters/LanguageIntConverter.cs +++ b/src/NzbDrone.Core/Datastore/Converters/LanguageIntConverter.cs @@ -27,7 +27,10 @@ public object FromDB(ColumnMap map, object dbValue) public object ToDB(object clrValue) { - if (clrValue == DBNull.Value) return 0; + if (clrValue == DBNull.Value) + { + return 0; + } if (clrValue as Language == null) { @@ -62,4 +65,4 @@ public override void WriteJson(JsonWriter writer, object value, JsonSerializer s writer.WriteValue(ToDB(value)); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Datastore/Converters/ProviderSettingConverter.cs b/src/NzbDrone.Core/Datastore/Converters/ProviderSettingConverter.cs index ace64d6af..17590c4f1 100644 --- a/src/NzbDrone.Core/Datastore/Converters/ProviderSettingConverter.cs +++ b/src/NzbDrone.Core/Datastore/Converters/ProviderSettingConverter.cs @@ -25,8 +25,7 @@ public override object FromDB(ConverterContext context) var ordinal = context.DataRecord.GetOrdinal("ConfigContract"); var contract = context.DataRecord.GetString(ordinal); - - var impType = typeof (IProviderConfig).Assembly.FindTypeByName(contract); + var impType = typeof(IProviderConfig).Assembly.FindTypeByName(contract); if (impType == null) { @@ -35,6 +34,5 @@ public override object FromDB(ConverterContext context) return Json.Deserialize(stringValue, impType); } - } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Datastore/Converters/QualityIntConverter.cs b/src/NzbDrone.Core/Datastore/Converters/QualityIntConverter.cs index 0b225a8a2..e8b72b206 100644 --- a/src/NzbDrone.Core/Datastore/Converters/QualityIntConverter.cs +++ b/src/NzbDrone.Core/Datastore/Converters/QualityIntConverter.cs @@ -1,8 +1,8 @@ using System; using Marr.Data.Converters; using Marr.Data.Mapping; -using NzbDrone.Core.Qualities; using Newtonsoft.Json; +using NzbDrone.Core.Qualities; namespace NzbDrone.Core.Datastore.Converters { @@ -27,7 +27,10 @@ public object FromDB(ColumnMap map, object dbValue) public object ToDB(object clrValue) { - if (clrValue == DBNull.Value) return 0; + if (clrValue == DBNull.Value) + { + return 0; + } if (clrValue as Quality == null) { diff --git a/src/NzbDrone.Core/Datastore/Converters/SystemVersionConverter.cs b/src/NzbDrone.Core/Datastore/Converters/SystemVersionConverter.cs index 68bfbe217..02f875be2 100644 --- a/src/NzbDrone.Core/Datastore/Converters/SystemVersionConverter.cs +++ b/src/NzbDrone.Core/Datastore/Converters/SystemVersionConverter.cs @@ -32,10 +32,10 @@ public object ToDB(object clrValue) { return version.ToString(); } - + return DBNull.Value; } - public Type DbType => typeof(String); + public Type DbType => typeof(string); } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Datastore/Converters/UtcConverter.cs b/src/NzbDrone.Core/Datastore/Converters/UtcConverter.cs index 1225f0806..3fd28d8a8 100644 --- a/src/NzbDrone.Core/Datastore/Converters/UtcConverter.cs +++ b/src/NzbDrone.Core/Datastore/Converters/UtcConverter.cs @@ -29,4 +29,4 @@ public object ToDB(object clrValue) public Type DbType => typeof(DateTime); } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Datastore/CorruptDatabaseException.cs b/src/NzbDrone.Core/Datastore/CorruptDatabaseException.cs index 1d8b6696d..4df2bfea4 100644 --- a/src/NzbDrone.Core/Datastore/CorruptDatabaseException.cs +++ b/src/NzbDrone.Core/Datastore/CorruptDatabaseException.cs @@ -5,19 +5,23 @@ namespace NzbDrone.Core.Datastore { public class CorruptDatabaseException : NzbDroneException { - public CorruptDatabaseException(string message, params object[] args) : base(message, args) + public CorruptDatabaseException(string message, params object[] args) + : base(message, args) { } - public CorruptDatabaseException(string message) : base(message) + public CorruptDatabaseException(string message) + : base(message) { } - public CorruptDatabaseException(string message, Exception innerException, params object[] args) : base(message, innerException, args) + public CorruptDatabaseException(string message, Exception innerException, params object[] args) + : base(message, innerException, args) { } - public CorruptDatabaseException(string message, Exception innerException) : base(message, innerException) + public CorruptDatabaseException(string message, Exception innerException) + : base(message, innerException) { } } diff --git a/src/NzbDrone.Core/Datastore/DbFactory.cs b/src/NzbDrone.Core/Datastore/DbFactory.cs index 587e0ecb0..88cf970e7 100644 --- a/src/NzbDrone.Core/Datastore/DbFactory.cs +++ b/src/NzbDrone.Core/Datastore/DbFactory.cs @@ -9,7 +9,6 @@ using NzbDrone.Common.Instrumentation; using NzbDrone.Core.Datastore.Migration.Framework; - namespace NzbDrone.Core.Datastore { public interface IDbFactory @@ -83,6 +82,7 @@ public IDatabase Create(MigrationContext migrationContext) break; } + case MigrationType.Log: { connectionString = _connectionStringFactory.LogDbConnectionString; @@ -90,6 +90,7 @@ public IDatabase Create(MigrationContext migrationContext) break; } + default: { throw new ArgumentException("Invalid MigrationType"); diff --git a/src/NzbDrone.Core/Datastore/Events/ModelEvent.cs b/src/NzbDrone.Core/Datastore/Events/ModelEvent.cs index af07997ec..d5f0048e0 100644 --- a/src/NzbDrone.Core/Datastore/Events/ModelEvent.cs +++ b/src/NzbDrone.Core/Datastore/Events/ModelEvent.cs @@ -31,4 +31,4 @@ public enum ModelAction Deleted = 3, Sync = 4 } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Datastore/Extensions/MappingExtensions.cs b/src/NzbDrone.Core/Datastore/Extensions/MappingExtensions.cs index 10e6fdd59..9ffb0d5d6 100644 --- a/src/NzbDrone.Core/Datastore/Extensions/MappingExtensions.cs +++ b/src/NzbDrone.Core/Datastore/Extensions/MappingExtensions.cs @@ -11,20 +11,22 @@ namespace NzbDrone.Core.Datastore.Extensions { public static class MappingExtensions { - - public static ColumnMapBuilder MapResultSet(this FluentMappings.MappingsFluentEntity mapBuilder) where T : ResultSet, new() + public static ColumnMapBuilder MapResultSet(this FluentMappings.MappingsFluentEntity mapBuilder) + where T : ResultSet, new() { return mapBuilder .Columns .AutoMapPropertiesWhere(IsMappableProperty); } - public static ColumnMapBuilder RegisterDefinition(this FluentMappings.MappingsFluentEntity mapBuilder, string tableName = null) where T : ProviderDefinition, new() + public static ColumnMapBuilder RegisterDefinition(this FluentMappings.MappingsFluentEntity mapBuilder, string tableName = null) + where T : ProviderDefinition, new() { return RegisterModel(mapBuilder, tableName).Ignore(c => c.ImplementationName); } - - public static ColumnMapBuilder RegisterModel(this FluentMappings.MappingsFluentEntity mapBuilder, string tableName = null) where T : ModelBase, new() + + public static ColumnMapBuilder RegisterModel(this FluentMappings.MappingsFluentEntity mapBuilder, string tableName = null) + where T : ModelBase, new() { return mapBuilder.Table.MapTable(tableName) .Columns @@ -40,15 +42,17 @@ public static RelationshipBuilder AutoMapChildModels(this ColumnMapBuilder { return mapBuilder.Relationships.AutoMapPropertiesWhere(m => m.MemberType == MemberTypes.Property && - typeof(ModelBase).IsAssignableFrom(((PropertyInfo) m).PropertyType)); + typeof(ModelBase).IsAssignableFrom(((PropertyInfo)m).PropertyType)); } public static bool IsMappableProperty(MemberInfo memberInfo) { var propertyInfo = memberInfo as PropertyInfo; - if (propertyInfo == null) return false; - + if (propertyInfo == null) + { + return false; + } if (!propertyInfo.IsReadable() || !propertyInfo.IsWritable()) { @@ -68,4 +72,4 @@ public static List QueryScalar(this IDataMapper dataMapper, stri return dataMapper.ExecuteReader(sql, reader => (TModel)Convert.ChangeType(reader.GetValue(0), typeof(TModel))).ToList(); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Datastore/Extensions/PagingSpecExtensions.cs b/src/NzbDrone.Core/Datastore/Extensions/PagingSpecExtensions.cs index 39cc5b7a6..46d217585 100644 --- a/src/NzbDrone.Core/Datastore/Extensions/PagingSpecExtensions.cs +++ b/src/NzbDrone.Core/Datastore/Extensions/PagingSpecExtensions.cs @@ -13,12 +13,15 @@ public static Expression> OrderByClause(this Paging public static int PagingOffset(this PagingSpec pagingSpec) { - return (pagingSpec.Page - 1)*pagingSpec.PageSize; + return (pagingSpec.Page - 1) * pagingSpec.PageSize; } public static Marr.Data.QGen.SortDirection ToSortDirection(this PagingSpec pagingSpec) { - if (pagingSpec.SortDirection == SortDirection.Descending) return Marr.Data.QGen.SortDirection.Desc; + if (pagingSpec.SortDirection == SortDirection.Descending) + { + return Marr.Data.QGen.SortDirection.Desc; + } return Marr.Data.QGen.SortDirection.Asc; } @@ -41,4 +44,3 @@ private static Expression> CreateExpression(string } } } - \ No newline at end of file diff --git a/src/NzbDrone.Core/Datastore/Extensions/RelationshipExtensions.cs b/src/NzbDrone.Core/Datastore/Extensions/RelationshipExtensions.cs index 7c5669c99..64ea72510 100644 --- a/src/NzbDrone.Core/Datastore/Extensions/RelationshipExtensions.cs +++ b/src/NzbDrone.Core/Datastore/Extensions/RelationshipExtensions.cs @@ -15,12 +15,11 @@ public static RelationshipBuilder HasOne(this Relation return relationshipBuilder.For(portalExpression.GetMemberName()) .LazyLoad( condition: parent => childIdSelector(parent) > 0, - query: (db, parent) => - { + query: (db, parent) => + { var id = childIdSelector(parent); return db.Query().Where(c => c.Id == id).SingleOrDefault(); - } - ); + }); } public static RelationshipBuilder Relationship(this ColumnMapBuilder mapBuilder) @@ -48,4 +47,4 @@ private static string GetMemberName(this Expression return expression.Member.Name; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Datastore/IEmbeddedDocument.cs b/src/NzbDrone.Core/Datastore/IEmbeddedDocument.cs index 14a1587b7..d1fada65f 100644 --- a/src/NzbDrone.Core/Datastore/IEmbeddedDocument.cs +++ b/src/NzbDrone.Core/Datastore/IEmbeddedDocument.cs @@ -3,4 +3,4 @@ public interface IEmbeddedDocument { } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Datastore/LazyList.cs b/src/NzbDrone.Core/Datastore/LazyList.cs index 17d0aba02..193a11812 100644 --- a/src/NzbDrone.Core/Datastore/LazyList.cs +++ b/src/NzbDrone.Core/Datastore/LazyList.cs @@ -8,13 +8,11 @@ public class LazyList : LazyLoaded> public LazyList() : this(new List()) { - } public LazyList(IEnumerable items) : base(new List(items)) { - } public static implicit operator LazyList(List val) @@ -27,4 +25,4 @@ public static implicit operator List(LazyList lazy) return lazy.Value; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Datastore/LogDatabase.cs b/src/NzbDrone.Core/Datastore/LogDatabase.cs index c454e9997..48a1f4f98 100644 --- a/src/NzbDrone.Core/Datastore/LogDatabase.cs +++ b/src/NzbDrone.Core/Datastore/LogDatabase.cs @@ -5,7 +5,6 @@ namespace NzbDrone.Core.Datastore { public interface ILogDatabase : IDatabase { - } public class LogDatabase : ILogDatabase diff --git a/src/NzbDrone.Core/Datastore/MainDatabase.cs b/src/NzbDrone.Core/Datastore/MainDatabase.cs index 8ce09eaf2..bc33d1aef 100644 --- a/src/NzbDrone.Core/Datastore/MainDatabase.cs +++ b/src/NzbDrone.Core/Datastore/MainDatabase.cs @@ -5,7 +5,6 @@ namespace NzbDrone.Core.Datastore { public interface IMainDatabase : IDatabase { - } public class MainDatabase : IMainDatabase diff --git a/src/NzbDrone.Core/Datastore/Migration/001_initial_setup.cs b/src/NzbDrone.Core/Datastore/Migration/001_initial_setup.cs index b2792fe56..624c31d42 100644 --- a/src/NzbDrone.Core/Datastore/Migration/001_initial_setup.cs +++ b/src/NzbDrone.Core/Datastore/Migration/001_initial_setup.cs @@ -116,7 +116,6 @@ protected override void MainDbUpgrade() .WithColumn("TvdbId").AsInt32() .WithColumn("SeasonNumber").AsInt32(); - Create.TableForModel("NamingConfig") .WithColumn("UseSceneName").AsBoolean() .WithColumn("Separator").AsString() diff --git a/src/NzbDrone.Core/Datastore/Migration/004_updated_history.cs b/src/NzbDrone.Core/Datastore/Migration/004_updated_history.cs index 5ebc51ac8..0eaf4da5b 100644 --- a/src/NzbDrone.Core/Datastore/Migration/004_updated_history.cs +++ b/src/NzbDrone.Core/Datastore/Migration/004_updated_history.cs @@ -10,7 +10,6 @@ protected override void MainDbUpgrade() { Delete.Table("History"); - Create.TableForModel("History") .WithColumn("EpisodeId").AsInt32() .WithColumn("SeriesId").AsInt32() diff --git a/src/NzbDrone.Core/Datastore/Migration/018_remove_duplicates.cs b/src/NzbDrone.Core/Datastore/Migration/018_remove_duplicates.cs index d788dd7dc..dbe11a6a9 100644 --- a/src/NzbDrone.Core/Datastore/Migration/018_remove_duplicates.cs +++ b/src/NzbDrone.Core/Datastore/Migration/018_remove_duplicates.cs @@ -1,9 +1,9 @@ -using FluentMigrator; -using NzbDrone.Core.Datastore.Migration.Framework; -using System.Linq; -using System.Data; +using System; using System.Collections.Generic; -using System; +using System.Data; +using System.Linq; +using FluentMigrator; +using NzbDrone.Core.Datastore.Migration.Framework; namespace NzbDrone.Core.Datastore.Migration { diff --git a/src/NzbDrone.Core/Datastore/Migration/019_restore_unique_constraints.cs b/src/NzbDrone.Core/Datastore/Migration/019_restore_unique_constraints.cs index bf70a9532..776371f94 100644 --- a/src/NzbDrone.Core/Datastore/Migration/019_restore_unique_constraints.cs +++ b/src/NzbDrone.Core/Datastore/Migration/019_restore_unique_constraints.cs @@ -17,6 +17,5 @@ protected override void MainDbUpgrade() Create.Index().OnTable("Series").OnColumn("TitleSlug").Unique(); Create.Index().OnTable("Episodes").OnColumn("TvDbEpisodeId").Unique(); } - } } diff --git a/src/NzbDrone.Core/Datastore/Migration/020_add_year_and_seasons_to_series.cs b/src/NzbDrone.Core/Datastore/Migration/020_add_year_and_seasons_to_series.cs index 0e2136141..bfbf78a77 100644 --- a/src/NzbDrone.Core/Datastore/Migration/020_add_year_and_seasons_to_series.cs +++ b/src/NzbDrone.Core/Datastore/Migration/020_add_year_and_seasons_to_series.cs @@ -54,7 +54,7 @@ private void ConvertSeasons(IDbConnection conn, IDbTransaction tran) using (IDbCommand updateCmd = conn.CreateCommand()) { - var text = string.Format("UPDATE Series SET Seasons = '{0}' WHERE Id = {1}", seasons.ToJson() , seriesId); + var text = string.Format("UPDATE Series SET Seasons = '{0}' WHERE Id = {1}", seasons.ToJson(), seriesId); updateCmd.Transaction = tran; updateCmd.CommandText = text; diff --git a/src/NzbDrone.Core/Datastore/Migration/027_fix_omgwtfnzbs.cs b/src/NzbDrone.Core/Datastore/Migration/027_fix_omgwtfnzbs.cs index d7b8b31fc..daa6699bc 100644 --- a/src/NzbDrone.Core/Datastore/Migration/027_fix_omgwtfnzbs.cs +++ b/src/NzbDrone.Core/Datastore/Migration/027_fix_omgwtfnzbs.cs @@ -9,12 +9,12 @@ public class fix_omgwtfnzbs : NzbDroneMigrationBase protected override void MainDbUpgrade() { Update.Table("Indexers") - .Set(new {ConfigContract = "OmgwtfnzbsSettings"}) - .Where(new {Implementation = "Omgwtfnzbs"}); + .Set(new { ConfigContract = "OmgwtfnzbsSettings" }) + .Where(new { Implementation = "Omgwtfnzbs" }); Update.Table("Indexers") - .Set(new {Settings = "{}"}) - .Where(new {Implementation = "Omgwtfnzbs", Settings = (string) null}); + .Set(new { Settings = "{}" }) + .Where(new { Implementation = "Omgwtfnzbs", Settings = (string)null }); Update.Table("Indexers") .Set(new { Settings = "{}" }) diff --git a/src/NzbDrone.Core/Datastore/Migration/029_add_formats_to_naming_config.cs b/src/NzbDrone.Core/Datastore/Migration/029_add_formats_to_naming_config.cs index 6d3dd897b..0191c4273 100644 --- a/src/NzbDrone.Core/Datastore/Migration/029_add_formats_to_naming_config.cs +++ b/src/NzbDrone.Core/Datastore/Migration/029_add_formats_to_naming_config.cs @@ -1,4 +1,4 @@ -using System.Collections.Generic; +using System.Collections.Generic; using System.Data; using System.Linq; using FluentMigrator; @@ -53,7 +53,6 @@ private void ConvertConfig(IDbConnection conn, IDbTransaction tran) { seriesTitlePattern = "{Series.Title}"; } - else { seriesTitlePattern = "{Series Title}"; @@ -70,20 +69,21 @@ private void ConvertConfig(IDbConnection conn, IDbTransaction tran) { episodeTitlePattern += "{Episode.Title}"; } - else { episodeTitlePattern += "{Episode Title}"; } } - var standardEpisodeFormat = string.Format("{0}{1}{2}", seriesTitlePattern, - GetNumberStyle(numberStyle).Pattern, - episodeTitlePattern); + var standardEpisodeFormat = string.Format("{0}{1}{2}", + seriesTitlePattern, + GetNumberStyle(numberStyle).Pattern, + episodeTitlePattern); - var dailyEpisodeFormat = string.Format("{0}{1}{2}", seriesTitlePattern, - dailyEpisodePattern, - episodeTitlePattern); + var dailyEpisodeFormat = string.Format("{0}{1}{2}", + seriesTitlePattern, + dailyEpisodePattern, + episodeTitlePattern); if (includeQuality) { @@ -121,9 +121,8 @@ private void ConvertConfig(IDbConnection conn, IDbTransaction tran) Name = "1x05", Pattern = "{season}x{episode:00}", EpisodeSeparator = "x" - }, - new + new { Id = 1, Name = "01x05", diff --git a/src/NzbDrone.Core/Datastore/Migration/033_add_api_key_to_pushover.cs b/src/NzbDrone.Core/Datastore/Migration/033_add_api_key_to_pushover.cs index 670d1f8ab..1fea6b809 100644 --- a/src/NzbDrone.Core/Datastore/Migration/033_add_api_key_to_pushover.cs +++ b/src/NzbDrone.Core/Datastore/Migration/033_add_api_key_to_pushover.cs @@ -1,4 +1,4 @@ -using System.Data; +using System.Data; using FluentMigrator; using NzbDrone.Common.Serializer; using NzbDrone.Core.Datastore.Migration.Framework; @@ -44,8 +44,8 @@ private void UpdatePushoverSettings(IDbConnection conn, IDbTransaction tran) var text = string.Format("UPDATE Notifications " + "SET Settings = '{0}'" + "WHERE Id = {1}", - settings.ToJson(), id - ); + settings.ToJson(), + id); updateCmd.Transaction = tran; updateCmd.CommandText = text; diff --git a/src/NzbDrone.Core/Datastore/Migration/036_update_with_quality_converters.cs b/src/NzbDrone.Core/Datastore/Migration/036_update_with_quality_converters.cs index 0f2342530..fc6ce05d9 100644 --- a/src/NzbDrone.Core/Datastore/Migration/036_update_with_quality_converters.cs +++ b/src/NzbDrone.Core/Datastore/Migration/036_update_with_quality_converters.cs @@ -1,12 +1,12 @@ -using FluentMigrator; -using NzbDrone.Core.Datastore.Migration.Framework; +using System.Collections.Generic; using System.Data; using System.Linq; +using FluentMigrator; using NzbDrone.Common.Serializer; +using NzbDrone.Core.Datastore.Converters; +using NzbDrone.Core.Datastore.Migration.Framework; using NzbDrone.Core.Profiles.Qualities; using NzbDrone.Core.Qualities; -using System.Collections.Generic; -using NzbDrone.Core.Datastore.Converters; namespace NzbDrone.Core.Datastore.Migration { @@ -23,7 +23,7 @@ protected override void MainDbUpgrade() Execute.WithConnection(ConvertQualityProfiles); Execute.WithConnection(ConvertQualityModels); } - + private void ConvertQualityProfiles(IDbConnection conn, IDbTransaction tran) { var qualityProfileItemConverter = new EmbeddedDocumentConverter(new QualityIntConverter()); diff --git a/src/NzbDrone.Core/Datastore/Migration/037_add_configurable_qualities.cs b/src/NzbDrone.Core/Datastore/Migration/037_add_configurable_qualities.cs index 06ced4854..75f08ff34 100644 --- a/src/NzbDrone.Core/Datastore/Migration/037_add_configurable_qualities.cs +++ b/src/NzbDrone.Core/Datastore/Migration/037_add_configurable_qualities.cs @@ -1,7 +1,7 @@ -using FluentMigrator; -using NzbDrone.Core.Datastore.Migration.Framework; -using System.Data; +using System.Data; using System.Linq; +using FluentMigrator; +using NzbDrone.Core.Datastore.Migration.Framework; using NzbDrone.Core.Qualities; namespace NzbDrone.Core.Datastore.Migration @@ -59,6 +59,6 @@ private void ConvertQualities(IDbConnection conn, IDbTransaction tran) } } } - } + } } } diff --git a/src/NzbDrone.Core/Datastore/Migration/043_convert_config_to_download_clients.cs b/src/NzbDrone.Core/Datastore/Migration/043_convert_config_to_download_clients.cs index 505962776..2f03fde24 100644 --- a/src/NzbDrone.Core/Datastore/Migration/043_convert_config_to_download_clients.cs +++ b/src/NzbDrone.Core/Datastore/Migration/043_convert_config_to_download_clients.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Data; using FluentMigrator; @@ -62,7 +62,6 @@ private void ConvertToThingyProvder(IDbConnection conn, IDbTransaction tran) AddDownloadClient(conn, tran, "Sabnzbd", "Sabnzbd", settings.ToJson(), "SabnzbdSettings", 1); } - else if (client.Equals("nzbget", StringComparison.InvariantCultureIgnoreCase)) { var settings = new ClientSettingsForMigration @@ -78,7 +77,6 @@ private void ConvertToThingyProvder(IDbConnection conn, IDbTransaction tran) AddDownloadClient(conn, tran, "Nzbget", "Nzbget", settings.ToJson(), "NzbgetSettings", 1); } - else if (client.Equals("pneumatic", StringComparison.InvariantCultureIgnoreCase)) { var settings = new FolderSettingsForMigration @@ -88,7 +86,6 @@ private void ConvertToThingyProvder(IDbConnection conn, IDbTransaction tran) AddDownloadClient(conn, tran, "Pneumatic", "Pneumatic", settings.ToJson(), "FolderSettings", 1); } - else if (client.Equals("blackhole", StringComparison.InvariantCultureIgnoreCase)) { var settings = new FolderSettingsForMigration @@ -108,14 +105,19 @@ private T GetConfigValue(Dictionary config, string key, T def if (config.ContainsKey(key)) { - return (T) Convert.ChangeType(config[key], typeof (T)); + return (T)Convert.ChangeType(config[key], typeof(T)); } return defaultValue; } - private void AddDownloadClient(IDbConnection conn, IDbTransaction tran, string name, string implementation, string settings, - string configContract, int protocol) + private void AddDownloadClient(IDbConnection conn, + IDbTransaction tran, + string name, + string implementation, + string settings, + string configContract, + int protocol) { using (IDbCommand updateCmd = conn.CreateCommand()) { diff --git a/src/NzbDrone.Core/Datastore/Migration/045_add_indexes.cs b/src/NzbDrone.Core/Datastore/Migration/045_add_indexes.cs index 4ac4e0034..c37a9fc37 100644 --- a/src/NzbDrone.Core/Datastore/Migration/045_add_indexes.cs +++ b/src/NzbDrone.Core/Datastore/Migration/045_add_indexes.cs @@ -11,10 +11,10 @@ protected override void MainDbUpgrade() Create.Index().OnTable("Blacklist").OnColumn("SeriesId"); Create.Index().OnTable("EpisodeFiles").OnColumn("SeriesId"); - + Create.Index().OnTable("Episodes").OnColumn("EpisodeFileId"); Create.Index().OnTable("Episodes").OnColumn("SeriesId"); - + Create.Index().OnTable("History").OnColumn("EpisodeId"); Create.Index().OnTable("History").OnColumn("Date"); diff --git a/src/NzbDrone.Core/Datastore/Migration/048_add_title_to_scenemappings.cs b/src/NzbDrone.Core/Datastore/Migration/048_add_title_to_scenemappings.cs index 4a2e94bbf..af5c7359c 100644 --- a/src/NzbDrone.Core/Datastore/Migration/048_add_title_to_scenemappings.cs +++ b/src/NzbDrone.Core/Datastore/Migration/048_add_title_to_scenemappings.cs @@ -1,5 +1,5 @@ -using NzbDrone.Core.Datastore.Migration.Framework; -using FluentMigrator; +using FluentMigrator; +using NzbDrone.Core.Datastore.Migration.Framework; namespace NzbDrone.Core.Datastore.Migration { diff --git a/src/NzbDrone.Core/Datastore/Migration/050_add_hash_to_metadata_files.cs b/src/NzbDrone.Core/Datastore/Migration/050_add_hash_to_metadata_files.cs index 8986a7fba..7f97ec993 100644 --- a/src/NzbDrone.Core/Datastore/Migration/050_add_hash_to_metadata_files.cs +++ b/src/NzbDrone.Core/Datastore/Migration/050_add_hash_to_metadata_files.cs @@ -1,5 +1,5 @@ -using NzbDrone.Core.Datastore.Migration.Framework; -using FluentMigrator; +using FluentMigrator; +using NzbDrone.Core.Datastore.Migration.Framework; namespace NzbDrone.Core.Datastore.Migration { diff --git a/src/NzbDrone.Core/Datastore/Migration/051_download_client_import.cs b/src/NzbDrone.Core/Datastore/Migration/051_download_client_import.cs index 549b92e59..e4cbfd7c8 100644 --- a/src/NzbDrone.Core/Datastore/Migration/051_download_client_import.cs +++ b/src/NzbDrone.Core/Datastore/Migration/051_download_client_import.cs @@ -1,13 +1,13 @@ using System; -using System.Data; -using System.Linq; using System.Collections.Generic; +using System.Data; +using System.IO; +using System.Linq; using FluentMigrator; using Newtonsoft.Json; using NzbDrone.Common.Extensions; using NzbDrone.Common.Serializer; using NzbDrone.Core.Datastore.Migration.Framework; -using System.IO; namespace NzbDrone.Core.Datastore.Migration { @@ -180,12 +180,19 @@ private void AssociateImportedHistoryItems(IDbConnection conn, IDbTransaction tr for (int i = 0; i < list.Count - 1; i++) { var grabbedEvent = list[i]; - if (grabbedEvent.EventType != MigrationHistoryEventType.Grabbed) continue; - if (grabbedEvent.Data.GetValueOrDefault("downloadClient") == null || grabbedEvent.Data.GetValueOrDefault("downloadClientId") == null) continue; + if (grabbedEvent.EventType != MigrationHistoryEventType.Grabbed) + { + continue; + } + + if (grabbedEvent.Data.GetValueOrDefault("downloadClient") == null || grabbedEvent.Data.GetValueOrDefault("downloadClientId") == null) + { + continue; + } // Check if it is already associated with a failed/imported event. int j; - for (j = i + 1; j < list.Count;j++) + for (j = i + 1; j < list.Count; j++) { if (list[j].EventType != MigrationHistoryEventType.DownloadFolderImported && list[j].EventType != MigrationHistoryEventType.DownloadFailed) @@ -208,7 +215,10 @@ private void AssociateImportedHistoryItems(IDbConnection conn, IDbTransaction tr } var importedEvent = list[i + 1]; - if (importedEvent.EventType != MigrationHistoryEventType.DownloadFolderImported) continue; + if (importedEvent.EventType != MigrationHistoryEventType.DownloadFolderImported) + { + continue; + } var droppedPath = importedEvent.Data.GetValueOrDefault("droppedPath"); if (droppedPath != null && new FileInfo(droppedPath).Directory.Name == grabbedEvent.SourceTitle) @@ -236,7 +246,7 @@ private void AssociateImportedHistoryItems(IDbConnection conn, IDbTransaction tr updateHistoryCmd.ExecuteNonQuery(); } } - + _logger.Info("Updated old History items. {0}/{1} old ImportedEvents were associated with GrabbedEvents.", historyItemsToAssociate.Count, numHistoryItemsNotAssociated); } } diff --git a/src/NzbDrone.Core/Datastore/Migration/052_add_columns_for_anime.cs b/src/NzbDrone.Core/Datastore/Migration/052_add_columns_for_anime.cs index e781ca010..e0dba2496 100644 --- a/src/NzbDrone.Core/Datastore/Migration/052_add_columns_for_anime.cs +++ b/src/NzbDrone.Core/Datastore/Migration/052_add_columns_for_anime.cs @@ -1,5 +1,5 @@ -using NzbDrone.Core.Datastore.Migration.Framework; -using FluentMigrator; +using FluentMigrator; +using NzbDrone.Core.Datastore.Migration.Framework; namespace NzbDrone.Core.Datastore.Migration { diff --git a/src/NzbDrone.Core/Datastore/Migration/062_convert_quality_models.cs b/src/NzbDrone.Core/Datastore/Migration/062_convert_quality_models.cs index cc9cea68a..0087345db 100644 --- a/src/NzbDrone.Core/Datastore/Migration/062_convert_quality_models.cs +++ b/src/NzbDrone.Core/Datastore/Migration/062_convert_quality_models.cs @@ -46,7 +46,10 @@ private void ConvertQualityModelsOnTable(IDbConnection conn, IDbTransaction tran var newQualityModel = new QualityModel062 { Quality = quality.Quality, Revision = new Revision() }; if (quality.Proper) + { newQualityModel.Revision.Version = 2; + } + var newQualityJson = newQualityModel.ToJson(); qualitiesToUpdate.Add(qualityJson, newQualityJson); diff --git a/src/NzbDrone.Core/Datastore/Migration/069_quality_proper.cs b/src/NzbDrone.Core/Datastore/Migration/069_quality_proper.cs index 9db5f2955..3dc644c9e 100644 --- a/src/NzbDrone.Core/Datastore/Migration/069_quality_proper.cs +++ b/src/NzbDrone.Core/Datastore/Migration/069_quality_proper.cs @@ -1,4 +1,4 @@ -using System.Data; +using System.Data; using System.Linq; using System.Text.RegularExpressions; using FluentMigrator; @@ -60,7 +60,7 @@ private string GetNewFormat(string currentFormat) foreach (Match match in matches) { var tokenMatch = GetTokenMatch(match); - var qualityFullToken = string.Format("Quality{0}Full", tokenMatch.Separator); ; + var qualityFullToken = string.Format("Quality{0}Full", tokenMatch.Separator); if (tokenMatch.Token.All(t => !char.IsLetter(t) || char.IsLower(t))) { diff --git a/src/NzbDrone.Core/Datastore/Migration/070_delay_profile.cs b/src/NzbDrone.Core/Datastore/Migration/070_delay_profile.cs index 1c9c7e58b..e3d7e6202 100644 --- a/src/NzbDrone.Core/Datastore/Migration/070_delay_profile.cs +++ b/src/NzbDrone.Core/Datastore/Migration/070_delay_profile.cs @@ -48,7 +48,10 @@ private void ConvertProfile(IDbConnection conn, IDbTransaction tran) foreach (var profileClosure in profiles.DistinctBy(p => p.GrabDelay)) { var profile = profileClosure; - if (profile.GrabDelay == 0) continue; + if (profile.GrabDelay == 0) + { + continue; + } var tag = string.Format("delay-{0}", profile.GrabDelay); var tagId = InsertTag(conn, tran, tag); @@ -82,7 +85,7 @@ private List GetProfiles(IDbConnection conn, IDbTransaction tran) { getProfilesCmd.Transaction = tran; getProfilesCmd.CommandText = @"SELECT Id, GrabDelay FROM Profiles"; - + using (IDataReader profileReader = getProfilesCmd.ExecuteReader()) { while (profileReader.Read()) diff --git a/src/NzbDrone.Core/Datastore/Migration/071_unknown_quality_in_profile.cs b/src/NzbDrone.Core/Datastore/Migration/071_unknown_quality_in_profile.cs index cc1f10fe1..f75bd01e6 100644 --- a/src/NzbDrone.Core/Datastore/Migration/071_unknown_quality_in_profile.cs +++ b/src/NzbDrone.Core/Datastore/Migration/071_unknown_quality_in_profile.cs @@ -81,7 +81,10 @@ public void PrependQuality(int quality) { foreach (var profile in _profiles) { - if (profile.Items.Any(v => v.Quality == quality)) continue; + if (profile.Items.Any(v => v.Quality == quality)) + { + continue; + } profile.Items.Insert(0, new ProfileItem71 { @@ -97,7 +100,10 @@ public void AppendQuality(int quality) { foreach (var profile in _profiles) { - if (profile.Items.Any(v => v.Quality == quality)) continue; + if (profile.Items.Any(v => v.Quality == quality)) + { + continue; + } profile.Items.Add(new ProfileItem71 { @@ -113,7 +119,10 @@ public void SplitQualityPrepend(int find, int quality) { foreach (var profile in _profiles) { - if (profile.Items.Any(v => v.Quality == quality)) continue; + if (profile.Items.Any(v => v.Quality == quality)) + { + continue; + } var findIndex = profile.Items.FindIndex(v => v.Quality == find); @@ -136,7 +145,10 @@ public void SplitQualityAppend(int find, int quality) { foreach (var profile in _profiles) { - if (profile.Items.Any(v => v.Quality == quality)) continue; + if (profile.Items.Any(v => v.Quality == quality)) + { + continue; + } var findIndex = profile.Items.FindIndex(v => v.Quality == find); diff --git a/src/NzbDrone.Core/Datastore/Migration/072_history_grabid.cs b/src/NzbDrone.Core/Datastore/Migration/072_history_grabid.cs index 23523808f..40eece1a0 100644 --- a/src/NzbDrone.Core/Datastore/Migration/072_history_grabid.cs +++ b/src/NzbDrone.Core/Datastore/Migration/072_history_grabid.cs @@ -57,7 +57,6 @@ private void UpdateHistory(IDbTransaction tran, IDbConnection conn, int id, stri updateHistoryCmd.AddParameter(id); updateHistoryCmd.ExecuteNonQuery(); - } } } diff --git a/src/NzbDrone.Core/Datastore/Migration/073_clear_ratings.cs b/src/NzbDrone.Core/Datastore/Migration/073_clear_ratings.cs index ef9c4074f..b1b547b60 100644 --- a/src/NzbDrone.Core/Datastore/Migration/073_clear_ratings.cs +++ b/src/NzbDrone.Core/Datastore/Migration/073_clear_ratings.cs @@ -9,7 +9,7 @@ public class clear_ratings : NzbDroneMigrationBase protected override void MainDbUpgrade() { Update.Table("Series") - .Set(new {Ratings = "{}"}) + .Set(new { Ratings = "{}" }) .AllRows(); Update.Table("Episodes") diff --git a/src/NzbDrone.Core/Datastore/Migration/085_expand_transmission_urlbase.cs b/src/NzbDrone.Core/Datastore/Migration/085_expand_transmission_urlbase.cs index 956f87bcd..981e90799 100644 --- a/src/NzbDrone.Core/Datastore/Migration/085_expand_transmission_urlbase.cs +++ b/src/NzbDrone.Core/Datastore/Migration/085_expand_transmission_urlbase.cs @@ -32,7 +32,7 @@ private void UpdateTransmissionSettings(IDbConnection conn, IDbTransaction tran) var settings = Json.Deserialize>(settingsJson); var urlBase = settings.GetValueOrDefault("urlBase", "") as string; - + if (urlBase.IsNullOrWhiteSpace()) { settings["urlBase"] = "/transmission/"; diff --git a/src/NzbDrone.Core/Datastore/Migration/088_pushbullet_devices_channels_list.cs b/src/NzbDrone.Core/Datastore/Migration/088_pushbullet_devices_channels_list.cs index b219dfd59..9991b42e0 100644 --- a/src/NzbDrone.Core/Datastore/Migration/088_pushbullet_devices_channels_list.cs +++ b/src/NzbDrone.Core/Datastore/Migration/088_pushbullet_devices_channels_list.cs @@ -49,7 +49,7 @@ private void UpdateTransmissionSettings(IDbConnection conn, IDbTransaction tran) if (channelTagsString.IsNotNullOrWhiteSpace()) { - var channelTags = channelTagsString.Split(new[] {","}, StringSplitOptions.RemoveEmptyEntries); + var channelTags = channelTagsString.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries); settings["channelTags"] = channelTags; } diff --git a/src/NzbDrone.Core/Datastore/Migration/090_update_kickass_url.cs b/src/NzbDrone.Core/Datastore/Migration/090_update_kickass_url.cs index ec96f48dc..bc22b3258 100644 --- a/src/NzbDrone.Core/Datastore/Migration/090_update_kickass_url.cs +++ b/src/NzbDrone.Core/Datastore/Migration/090_update_kickass_url.cs @@ -12,8 +12,7 @@ protected override void MainDbUpgrade() Execute.Sql( "UPDATE Indexers SET Settings = Replace(Settings, 'kickass.so', 'kat.cr') WHERE Implementation = 'KickassTorrents';" + "UPDATE Indexers SET Settings = Replace(Settings, 'kickass.to', 'kat.cr') WHERE Implementation = 'KickassTorrents';" + - "UPDATE Indexers SET Settings = Replace(Settings, 'http://', 'https://') WHERE Implementation = 'KickassTorrents';" - ); + "UPDATE Indexers SET Settings = Replace(Settings, 'http://', 'https://') WHERE Implementation = 'KickassTorrents';"); } } diff --git a/src/NzbDrone.Core/Datastore/Migration/102_add_language_to_episodeFiles_history_and_blacklist.cs b/src/NzbDrone.Core/Datastore/Migration/102_add_language_to_episodeFiles_history_and_blacklist.cs index 59320f805..9527b7204 100644 --- a/src/NzbDrone.Core/Datastore/Migration/102_add_language_to_episodeFiles_history_and_blacklist.cs +++ b/src/NzbDrone.Core/Datastore/Migration/102_add_language_to_episodeFiles_history_and_blacklist.cs @@ -4,8 +4,8 @@ using System.Linq; using FluentMigrator; using NzbDrone.Common.Extensions; -using NzbDrone.Core.Datastore.Migration.Framework; using NzbDrone.Core.Datastore.Converters; +using NzbDrone.Core.Datastore.Migration.Framework; using NzbDrone.Core.Languages; namespace NzbDrone.Core.Datastore.Migration @@ -29,7 +29,7 @@ protected override void MainDbUpgrade() private void UpdateLanguage(IDbConnection conn, IDbTransaction tran) { - var LanguageConverter = new EmbeddedDocumentConverter(new LanguageIntConverter()); + var languageConverter = new EmbeddedDocumentConverter(new LanguageIntConverter()); var profileLanguages = new Dictionary(); using (IDbCommand getProfileCmd = conn.CreateCommand()) @@ -74,7 +74,7 @@ private void UpdateLanguage(IDbConnection conn, IDbTransaction tran) foreach (var group in seriesLanguages.GroupBy(v => v.Value, v => v.Key)) { - var languageJson = LanguageConverter.ToDB(Language.FindById(group.Key)); + var languageJson = languageConverter.ToDB(Language.FindById(group.Key)); var seriesIds = group.Select(v => v.ToString()).Join(","); diff --git a/src/NzbDrone.Core/Datastore/Migration/108_fix_extra_file_extension.cs b/src/NzbDrone.Core/Datastore/Migration/108_fix_extra_file_extension.cs index bce22cb6c..6d5225349 100644 --- a/src/NzbDrone.Core/Datastore/Migration/108_fix_extra_file_extension.cs +++ b/src/NzbDrone.Core/Datastore/Migration/108_fix_extra_file_extension.cs @@ -25,7 +25,6 @@ private void FixExtraFileExtension(IDbConnection conn, IDbTransaction tran) private void FixExtraFileExtensionForTable(IDbConnection conn, IDbTransaction tran, string table) { - using (var cmd = conn.CreateCommand()) { cmd.Transaction = tran; diff --git a/src/NzbDrone.Core/Datastore/Migration/109_import_extra_files.cs b/src/NzbDrone.Core/Datastore/Migration/109_import_extra_files.cs index e92e00a78..e78e2c6a3 100644 --- a/src/NzbDrone.Core/Datastore/Migration/109_import_extra_files.cs +++ b/src/NzbDrone.Core/Datastore/Migration/109_import_extra_files.cs @@ -15,7 +15,6 @@ protected override void MainDbUpgrade() private void ImportExtraFiles(IDbConnection conn, IDbTransaction tran) { - using (var cmd = conn.CreateCommand()) { cmd.Transaction = tran; diff --git a/src/NzbDrone.Core/Datastore/Migration/111_create_language_profiles.cs b/src/NzbDrone.Core/Datastore/Migration/111_create_language_profiles.cs index 6f1835a72..dec330ed3 100644 --- a/src/NzbDrone.Core/Datastore/Migration/111_create_language_profiles.cs +++ b/src/NzbDrone.Core/Datastore/Migration/111_create_language_profiles.cs @@ -1,12 +1,12 @@ -using FluentMigrator; -using NzbDrone.Core.Datastore.Converters; -using NzbDrone.Core.Datastore.Migration.Framework; -using NzbDrone.Core.Languages; using System; using System.Collections.Generic; using System.Data; using System.Linq; +using FluentMigrator; using NzbDrone.Common.Extensions; +using NzbDrone.Core.Datastore.Converters; +using NzbDrone.Core.Datastore.Migration.Framework; +using NzbDrone.Core.Languages; namespace NzbDrone.Core.Datastore.Migration { @@ -23,7 +23,7 @@ protected override void MainDbUpgrade() Execute.WithConnection(InsertDefaultLanguages); - Delete.Column("Language").FromTable("Profiles"); + Delete.Column("Language").FromTable("Profiles"); } private void InsertDefaultLanguages(IDbConnection conn, IDbTransaction tran) @@ -76,7 +76,6 @@ private List GetDefaultLanguageProfiles() }); return profiles; - } private List GetLanguageProfiles(IDbConnection conn, IDbTransaction tran) @@ -105,7 +104,7 @@ private List GetLanguageProfiles(IDbConnection conn, IDbTran { _logger.Debug("Language field not found in Profiles, using English as default." + e.Message); } - + if (profiles.None(p => p.Cutoff.Id == lang)) { var language = Language.FindById(lang); @@ -165,7 +164,7 @@ private class LanguageProfile111 public Language Cutoff { get; set; } public List Languages { get; set; } - public LanguageProfile111 () + public LanguageProfile111() { ProfileIds = new List(); } diff --git a/src/NzbDrone.Core/Datastore/Migration/117_add_webrip_and_br480_qualites_in_profile.cs b/src/NzbDrone.Core/Datastore/Migration/117_add_webrip_and_br480_qualites_in_profile.cs index e56c9ddd2..b4391928d 100644 --- a/src/NzbDrone.Core/Datastore/Migration/117_add_webrip_and_br480_qualites_in_profile.cs +++ b/src/NzbDrone.Core/Datastore/Migration/117_add_webrip_and_br480_qualites_in_profile.cs @@ -20,11 +20,11 @@ private void ConvertProfile(IDbConnection conn, IDbTransaction tran) { var updater = new ProfileUpdater117(conn, tran); - updater.CreateGroupAt(8, 1000, "WEB 480p", new[] {12, 8}); // Group WEBRip480p with WEBDL480p - updater.CreateGroupAt(2, 1001, "DVD", new[] {2, 13}); // Group Bluray480p with DVD - updater.CreateGroupAt(5, 1002, "WEB 720p", new[] {14, 5}); // Group WEBRip720p with WEBDL720p - updater.CreateGroupAt(3, 1003, "WEB 1080p", new[] {15, 3}); // Group WEBRip1080p with WEBDL1080p - updater.CreateGroupAt(18, 1004, "WEB 2160p", new[] {17, 18}); // Group WEBRip2160p with WEBDL2160p + updater.CreateGroupAt(8, 1000, "WEB 480p", new[] { 12, 8 }); // Group WEBRip480p with WEBDL480p + updater.CreateGroupAt(2, 1001, "DVD", new[] { 2, 13 }); // Group Bluray480p with DVD + updater.CreateGroupAt(5, 1002, "WEB 720p", new[] { 14, 5 }); // Group WEBRip720p with WEBDL720p + updater.CreateGroupAt(3, 1003, "WEB 1080p", new[] { 15, 3 }); // Group WEBRip1080p with WEBDL1080p + updater.CreateGroupAt(18, 1004, "WEB 2160p", new[] { 17, 18 }); // Group WEBRip2160p with WEBDL2160p updater.Commit(); } diff --git a/src/NzbDrone.Core/Datastore/Migration/122_add_remux_qualities_in_profile.cs b/src/NzbDrone.Core/Datastore/Migration/122_add_remux_qualities_in_profile.cs index a4fa59f90..db8bf89bd 100644 --- a/src/NzbDrone.Core/Datastore/Migration/122_add_remux_qualities_in_profile.cs +++ b/src/NzbDrone.Core/Datastore/Migration/122_add_remux_qualities_in_profile.cs @@ -23,7 +23,7 @@ private void ConvertProfile(IDbConnection conn, IDbTransaction tran) // Insert 2060p, in case the user grouped Bluray 1080p and 2160p together. updater.SplitQualityAppend(19, 21); // Bluray2160pRemux after Bluray2160p - updater.SplitQualityAppend(7, 20); // Bluray1080pRemux after Bluray1080p + updater.SplitQualityAppend(7, 20); // Bluray1080pRemux after Bluray1080p updater.Commit(); } @@ -90,7 +90,10 @@ public void SplitQualityAppend(int find, int quality) { foreach (var profile in _profiles) { - if (profile.Items.Any(v => v.Quality == quality)) continue; + if (profile.Items.Any(v => v.Quality == quality)) + { + continue; + } var findIndex = profile.Items.FindIndex(v => { diff --git a/src/NzbDrone.Core/Datastore/Migration/132_add_download_client_priority.cs b/src/NzbDrone.Core/Datastore/Migration/132_add_download_client_priority.cs index 8de02bf2b..9430b59f1 100644 --- a/src/NzbDrone.Core/Datastore/Migration/132_add_download_client_priority.cs +++ b/src/NzbDrone.Core/Datastore/Migration/132_add_download_client_priority.cs @@ -18,7 +18,6 @@ protected override void MainDbUpgrade() { Alter.Table("DownloadClients").AddColumn("Priority").AsInt32().WithDefaultValue(1); Execute.WithConnection(InitPriorityForBackwardCompatibility); - } private void InitPriorityForBackwardCompatibility(IDbConnection conn, IDbTransaction tran) diff --git a/src/NzbDrone.Core/Datastore/Migration/135_health_issue_notification.cs b/src/NzbDrone.Core/Datastore/Migration/135_health_issue_notification.cs index 15cda4db6..2bd945dd7 100644 --- a/src/NzbDrone.Core/Datastore/Migration/135_health_issue_notification.cs +++ b/src/NzbDrone.Core/Datastore/Migration/135_health_issue_notification.cs @@ -12,4 +12,4 @@ protected override void MainDbUpgrade() Alter.Table("Notifications").AddColumn("IncludeHealthWarnings").AsBoolean().WithDefaultValue(0); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Datastore/Migration/139_add_download_history.cs b/src/NzbDrone.Core/Datastore/Migration/139_add_download_history.cs index 9294f5aa3..b1e039153 100644 --- a/src/NzbDrone.Core/Datastore/Migration/139_add_download_history.cs +++ b/src/NzbDrone.Core/Datastore/Migration/139_add_download_history.cs @@ -34,13 +34,16 @@ protected override void MainDbUpgrade() private static readonly Dictionary EventTypeMap = new Dictionary() { // EpisodeHistoryType.Grabbed -> DownloadHistoryType.Grabbed - {1, 1}, + { 1, 1 }, + // EpisodeHistoryType.DownloadFolderImported -> DownloadHistoryType.DownloadImported - {3, 2}, + { 3, 2 }, + // EpisodeHistoryType.DownloadFailed -> DownloadHistoryType.DownloadFailed - {4, 3}, + { 4, 3 }, + // EpisodeHistoryType.DownloadIgnored -> DownloadHistoryType.DownloadIgnored - {7, 4} + { 7, 4 } }; private void InitialImportedDownloadHistory(IDbConnection conn, IDbTransaction tran) diff --git a/src/NzbDrone.Core/Datastore/Migration/140_remove_chown_and_folderchmod_config.cs b/src/NzbDrone.Core/Datastore/Migration/140_remove_chown_and_folderchmod_config.cs index ba5235f96..c26f4a765 100644 --- a/src/NzbDrone.Core/Datastore/Migration/140_remove_chown_and_folderchmod_config.cs +++ b/src/NzbDrone.Core/Datastore/Migration/140_remove_chown_and_folderchmod_config.cs @@ -10,6 +10,7 @@ public class remove_chown_and_folderchmod_config_v2 : NzbDroneMigrationBase protected override void MainDbUpgrade() { Execute.Sql("DELETE FROM config WHERE Key IN ('folderchmod', 'chownuser')"); + // Note: v1 version of migration removed 'chowngroup' } } diff --git a/src/NzbDrone.Core/Datastore/Migration/142_import_lists.cs b/src/NzbDrone.Core/Datastore/Migration/142_import_lists.cs index 1351a852c..5b1703615 100644 --- a/src/NzbDrone.Core/Datastore/Migration/142_import_lists.cs +++ b/src/NzbDrone.Core/Datastore/Migration/142_import_lists.cs @@ -33,4 +33,4 @@ protected override void MainDbUpgrade() .WithColumn("Title").AsString().NotNullable(); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Datastore/Migration/144_import_lists_series_type_and_season_folder.cs b/src/NzbDrone.Core/Datastore/Migration/144_import_lists_series_type_and_season_folder.cs index 66939a6d5..db0c4fcac 100644 --- a/src/NzbDrone.Core/Datastore/Migration/144_import_lists_series_type_and_season_folder.cs +++ b/src/NzbDrone.Core/Datastore/Migration/144_import_lists_series_type_and_season_folder.cs @@ -12,4 +12,4 @@ protected override void MainDbUpgrade() Alter.Table("ImportLists").AddColumn("SeasonFolder").AsBoolean().WithDefaultValue(true); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Datastore/Migration/145_remove_growl.cs b/src/NzbDrone.Core/Datastore/Migration/145_remove_growl.cs index f04bfe163..d613eb0f2 100644 --- a/src/NzbDrone.Core/Datastore/Migration/145_remove_growl.cs +++ b/src/NzbDrone.Core/Datastore/Migration/145_remove_growl.cs @@ -11,4 +11,4 @@ protected override void MainDbUpgrade() Delete.FromTable("Notifications").Row(new { Implementation = "Growl" }); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Datastore/Migration/146_cleanup_duplicates_updatehistory.cs b/src/NzbDrone.Core/Datastore/Migration/146_cleanup_duplicates_updatehistory.cs index 4eeeb717f..7a7d8feb4 100644 --- a/src/NzbDrone.Core/Datastore/Migration/146_cleanup_duplicates_updatehistory.cs +++ b/src/NzbDrone.Core/Datastore/Migration/146_cleanup_duplicates_updatehistory.cs @@ -56,4 +56,4 @@ private void CleanupUpdateHistory(IDbConnection conn, IDbTransaction tran) } } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Datastore/Migration/147_swap_filechmod_for_folderchmod.cs b/src/NzbDrone.Core/Datastore/Migration/147_swap_filechmod_for_folderchmod.cs index 67b2c4366..202a7c735 100644 --- a/src/NzbDrone.Core/Datastore/Migration/147_swap_filechmod_for_folderchmod.cs +++ b/src/NzbDrone.Core/Datastore/Migration/147_swap_filechmod_for_folderchmod.cs @@ -12,9 +12,10 @@ public class swap_filechmod_for_folderchmod : NzbDroneMigrationBase { protected override void MainDbUpgrade() { - // Reverts part of migration 140, note that the v1 of migration140 also removed chowngroup + // Reverts part of migration 140, note that the v1 of migration140 also removed chowngroup Execute.WithConnection(ConvertFileChmodToFolderChmod); } + private void ConvertFileChmodToFolderChmod(IDbConnection conn, IDbTransaction tran) { using (IDbCommand getFileChmodCmd = conn.CreateCommand()) diff --git a/src/NzbDrone.Core/Datastore/Migration/149_add_on_delete_to_notifications.cs b/src/NzbDrone.Core/Datastore/Migration/149_add_on_delete_to_notifications.cs index 7b1574a7d..70906256f 100644 --- a/src/NzbDrone.Core/Datastore/Migration/149_add_on_delete_to_notifications.cs +++ b/src/NzbDrone.Core/Datastore/Migration/149_add_on_delete_to_notifications.cs @@ -13,4 +13,3 @@ protected override void MainDbUpgrade() } } } - diff --git a/src/NzbDrone.Core/Datastore/Migration/151_remove_custom_filter_type.cs b/src/NzbDrone.Core/Datastore/Migration/151_remove_custom_filter_type.cs index a7bceab5d..875dba7c1 100644 --- a/src/NzbDrone.Core/Datastore/Migration/151_remove_custom_filter_type.cs +++ b/src/NzbDrone.Core/Datastore/Migration/151_remove_custom_filter_type.cs @@ -14,4 +14,3 @@ protected override void MainDbUpgrade() } } } - diff --git a/src/NzbDrone.Core/Datastore/Migration/153_add_on_episodefiledelete_for_upgrade.cs b/src/NzbDrone.Core/Datastore/Migration/153_add_on_episodefiledelete_for_upgrade.cs index d006e2429..e7463e5e2 100644 --- a/src/NzbDrone.Core/Datastore/Migration/153_add_on_episodefiledelete_for_upgrade.cs +++ b/src/NzbDrone.Core/Datastore/Migration/153_add_on_episodefiledelete_for_upgrade.cs @@ -12,4 +12,3 @@ protected override void MainDbUpgrade() } } } - diff --git a/src/NzbDrone.Core/Datastore/Migration/155_add_arabic_and_hindi_languages.cs b/src/NzbDrone.Core/Datastore/Migration/155_add_arabic_and_hindi_languages.cs index 7b603caa6..581c01eeb 100644 --- a/src/NzbDrone.Core/Datastore/Migration/155_add_arabic_and_hindi_languages.cs +++ b/src/NzbDrone.Core/Datastore/Migration/155_add_arabic_and_hindi_languages.cs @@ -40,7 +40,6 @@ public class LanguageProfileItem128 public bool Allowed { get; set; } } - public class LanguageProfileUpdater128 { private readonly IDbConnection _connection; diff --git a/src/NzbDrone.Core/Datastore/Migration/156_add_bypass_to_delay_profile.cs b/src/NzbDrone.Core/Datastore/Migration/156_add_bypass_to_delay_profile.cs index c53fb895e..bcb49c5ab 100644 --- a/src/NzbDrone.Core/Datastore/Migration/156_add_bypass_to_delay_profile.cs +++ b/src/NzbDrone.Core/Datastore/Migration/156_add_bypass_to_delay_profile.cs @@ -10,6 +10,7 @@ public class add_bypass_to_delay_profile : NzbDroneMigrationBase protected override void MainDbUpgrade() { Alter.Table("DelayProfiles").AddColumn("BypassIfHighestQuality").AsBoolean().WithDefaultValue(false); + // Set to true for existing Delay Profiles to keep behavior the same. Execute.Sql("UPDATE DelayProfiles SET BypassIfHighestQuality = 1;"); } diff --git a/src/NzbDrone.Core/Datastore/Migration/157_email_multiple_addresses.cs b/src/NzbDrone.Core/Datastore/Migration/157_email_multiple_addresses.cs index a3070699e..1001ccbd3 100644 --- a/src/NzbDrone.Core/Datastore/Migration/157_email_multiple_addresses.cs +++ b/src/NzbDrone.Core/Datastore/Migration/157_email_multiple_addresses.cs @@ -17,7 +17,6 @@ protected override void MainDbUpgrade() private void ChangeEmailAddressType(IDbConnection conn, IDbTransaction tran) { - using (var getEmailCmd = conn.CreateCommand()) { getEmailCmd.Transaction = tran; diff --git a/src/NzbDrone.Core/Datastore/Migration/158_cdh_per_downloadclient.cs b/src/NzbDrone.Core/Datastore/Migration/158_cdh_per_downloadclient.cs index 14cb67df5..55a7ee277 100644 --- a/src/NzbDrone.Core/Datastore/Migration/158_cdh_per_downloadclient.cs +++ b/src/NzbDrone.Core/Datastore/Migration/158_cdh_per_downloadclient.cs @@ -26,22 +26,27 @@ private void MoveRemoveSettings(IDbConnection conn, IDbTransaction tran) using (var removeCompletedDownloadsCmd = conn.CreateCommand(tran, "SELECT Value FROM Config WHERE Key = 'removecompleteddownloads'")) { - if ("true" == (removeCompletedDownloadsCmd.ExecuteScalar() as string)?.ToLower()) + if ((removeCompletedDownloadsCmd.ExecuteScalar() as string)?.ToLower() == "true") + { removeCompletedDownloads = true; + } } using (var removeFailedDownloadsCmd = conn.CreateCommand(tran, "SELECT Value FROM Config WHERE Key = 'removefaileddownloads'")) { - if ("false" == (removeFailedDownloadsCmd.ExecuteScalar() as string)?.ToLower()) + if ((removeFailedDownloadsCmd.ExecuteScalar() as string)?.ToLower() == "false") + { removeFailedDownloads = false; + } } - + using (var updateClientCmd = conn.CreateCommand(tran, $"UPDATE DownloadClients SET RemoveCompletedDownloads = (CASE WHEN Implementation IN (\"RTorrent\", \"Flood\") THEN 0 ELSE ? END), RemoveFailedDownloads = ?")) { updateClientCmd.AddParameter(removeCompletedDownloads ? 1 : 0); updateClientCmd.AddParameter(removeFailedDownloads ? 1 : 0); updateClientCmd.ExecuteNonQuery(); } + using (var removeConfigCmd = conn.CreateCommand(tran, $"DELETE FROM Config WHERE Key IN ('removecompleteddownloads', 'removefaileddownloads')")) { removeConfigCmd.ExecuteNonQuery(); diff --git a/src/NzbDrone.Core/Datastore/Migration/161_remove_plex_hometheater.cs b/src/NzbDrone.Core/Datastore/Migration/161_remove_plex_hometheater.cs index 6fb359685..5829089ee 100644 --- a/src/NzbDrone.Core/Datastore/Migration/161_remove_plex_hometheater.cs +++ b/src/NzbDrone.Core/Datastore/Migration/161_remove_plex_hometheater.cs @@ -12,4 +12,4 @@ protected override void MainDbUpgrade() Delete.FromTable("Notifications").Row(new { Implementation = "PlexClient" }); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Datastore/Migration/162_release_profile_to_array.cs b/src/NzbDrone.Core/Datastore/Migration/162_release_profile_to_array.cs index 3f87202ce..e88c4c44f 100644 --- a/src/NzbDrone.Core/Datastore/Migration/162_release_profile_to_array.cs +++ b/src/NzbDrone.Core/Datastore/Migration/162_release_profile_to_array.cs @@ -32,7 +32,7 @@ private void ChangeRequiredIgnoredTypes(IDbConnection conn, IDbTransaction tran) var required = requiredObj == DBNull.Value ? Enumerable.Empty() - : requiredObj.ToString().Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries); + : requiredObj.ToString().Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); var ignored = ignoredObj == DBNull.Value ? Enumerable.Empty() diff --git a/src/NzbDrone.Core/Datastore/Migration/164_download_client_per_indexer.cs b/src/NzbDrone.Core/Datastore/Migration/164_download_client_per_indexer.cs index 44f4c5b1d..aed15fa20 100644 --- a/src/NzbDrone.Core/Datastore/Migration/164_download_client_per_indexer.cs +++ b/src/NzbDrone.Core/Datastore/Migration/164_download_client_per_indexer.cs @@ -11,4 +11,4 @@ protected override void MainDbUpgrade() Alter.Table("Indexers").AddColumn("DownloadClientId").AsInt32().WithDefaultValue(0); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Datastore/Migration/169_add_malayalam _and_ukrainian_languages.cs b/src/NzbDrone.Core/Datastore/Migration/169_add_malayalam _and_ukrainian_languages.cs index bee950a7d..a578ad743 100644 --- a/src/NzbDrone.Core/Datastore/Migration/169_add_malayalam _and_ukrainian_languages.cs +++ b/src/NzbDrone.Core/Datastore/Migration/169_add_malayalam _and_ukrainian_languages.cs @@ -40,7 +40,6 @@ public class LanguageProfileItem169 public bool Allowed { get; set; } } - public class LanguageProfileUpdater169 { private readonly IDbConnection _connection; diff --git a/src/NzbDrone.Core/Datastore/Migration/Framework/MigrationExtension.cs b/src/NzbDrone.Core/Datastore/Migration/Framework/MigrationExtension.cs index e159135d1..9883978c6 100644 --- a/src/NzbDrone.Core/Datastore/Migration/Framework/MigrationExtension.cs +++ b/src/NzbDrone.Core/Datastore/Migration/Framework/MigrationExtension.cs @@ -1,4 +1,5 @@ -using FluentMigrator; +using System.Data; +using FluentMigrator; using FluentMigrator.Builders.Create; using FluentMigrator.Builders.Create.Table; using FluentMigrator.Runner; @@ -6,7 +7,6 @@ using FluentMigrator.Runner.Generators.SQLite; using FluentMigrator.Runner.Processors.SQLite; using Microsoft.Extensions.DependencyInjection; -using System.Data; namespace NzbDrone.Core.Datastore.Migration.Framework { diff --git a/src/NzbDrone.Core/Datastore/Migration/Framework/NzbDroneSqliteProcessor.cs b/src/NzbDrone.Core/Datastore/Migration/Framework/NzbDroneSqliteProcessor.cs index 507f5fc3d..e757a9d2b 100644 --- a/src/NzbDrone.Core/Datastore/Migration/Framework/NzbDroneSqliteProcessor.cs +++ b/src/NzbDrone.Core/Datastore/Migration/Framework/NzbDroneSqliteProcessor.cs @@ -24,7 +24,6 @@ public NzbDroneSQLiteProcessor(SQLiteDbFactory factory, SQLiteQuoter quoter) : base(factory, generator, logger, options, connectionStringAccessor, serviceProvider, quoter) { - } public override void Process(AlterColumnExpression expression) diff --git a/src/NzbDrone.Core/Datastore/Migration/Framework/SqliteSchemaDumper.cs b/src/NzbDrone.Core/Datastore/Migration/Framework/SqliteSchemaDumper.cs index 042b124bc..3f9129c20 100644 --- a/src/NzbDrone.Core/Datastore/Migration/Framework/SqliteSchemaDumper.cs +++ b/src/NzbDrone.Core/Datastore/Migration/Framework/SqliteSchemaDumper.cs @@ -80,6 +80,7 @@ protected virtual TableDefinition ParseCreateTableStatement(SqliteSyntaxReader r { pk.IsIdentity = true; } + continue; } } @@ -204,6 +205,7 @@ public virtual IList ReadDbSchema() foreach (var table in tables) { table.Indexes = ReadIndexes(table.SchemaName, table.Name); + //table.ForeignKeys = ReadForeignKeys(table.SchemaName, table.Name); } @@ -229,6 +231,7 @@ protected virtual IList ReadTables() tableDefinitionList.Add(table); } + return tableDefinitionList; } @@ -271,6 +274,7 @@ protected virtual IList ReadIndexes(string schemaName, string t var index = ReadIndexSchema(sql); indexes.Add(index); } + return indexes; } } diff --git a/src/NzbDrone.Core/Datastore/Migration/Framework/SqliteSyntaxReader.cs b/src/NzbDrone.Core/Datastore/Migration/Framework/SqliteSyntaxReader.cs index d77c84439..315f02e43 100644 --- a/src/NzbDrone.Core/Datastore/Migration/Framework/SqliteSyntaxReader.cs +++ b/src/NzbDrone.Core/Datastore/Migration/Framework/SqliteSyntaxReader.cs @@ -5,7 +5,6 @@ namespace NzbDrone.Core.Datastore.Migration.Framework { - public class SqliteSyntaxReader { public string Buffer { get; private set; } @@ -174,6 +173,7 @@ public TokenType Read() { throw CreateSyntaxException("Unexpected sequence."); } + Type = TokenType.StringToken; Value = Buffer.Substring(start, end - start); return Type; @@ -201,6 +201,7 @@ public List ReadList() { throw CreateSyntaxException("Expected ListEnd first"); } + if (Type == TokenType.ListStart) { SkipTillToken(TokenType.ListEnd); diff --git a/src/NzbDrone.Core/Datastore/ModelConflictException.cs b/src/NzbDrone.Core/Datastore/ModelConflictException.cs index 66c7f94ff..f313e3444 100644 --- a/src/NzbDrone.Core/Datastore/ModelConflictException.cs +++ b/src/NzbDrone.Core/Datastore/ModelConflictException.cs @@ -8,13 +8,11 @@ public class ModelConflictException : NzbDroneException public ModelConflictException(Type modelType, int modelId) : base("{0} with ID {1} cannot be modified", modelType.Name, modelId) { - } public ModelConflictException(Type modelType, int modelId, string message) : base("{0} with ID {1} {2}", modelType.Name, modelId, message) { - } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Datastore/ModelNotFoundException.cs b/src/NzbDrone.Core/Datastore/ModelNotFoundException.cs index 8241fd344..b9ad28da9 100644 --- a/src/NzbDrone.Core/Datastore/ModelNotFoundException.cs +++ b/src/NzbDrone.Core/Datastore/ModelNotFoundException.cs @@ -8,7 +8,6 @@ public class ModelNotFoundException : NzbDroneException public ModelNotFoundException(Type modelType, int modelId) : base("{0} with ID {1} does not exist", modelType.Name, modelId) { - } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Datastore/ResultSet.cs b/src/NzbDrone.Core/Datastore/ResultSet.cs index 2bb2b4169..7e67fff09 100644 --- a/src/NzbDrone.Core/Datastore/ResultSet.cs +++ b/src/NzbDrone.Core/Datastore/ResultSet.cs @@ -3,4 +3,4 @@ public class ResultSet { } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Datastore/TableMapping.cs b/src/NzbDrone.Core/Datastore/TableMapping.cs index 0eee0b275..19bbb463c 100644 --- a/src/NzbDrone.Core/Datastore/TableMapping.cs +++ b/src/NzbDrone.Core/Datastore/TableMapping.cs @@ -2,46 +2,46 @@ using System.Collections.Generic; using Marr.Data; using Marr.Data.Mapping; +using NzbDrone.Common.Disk; using NzbDrone.Common.Reflection; +using NzbDrone.Core.Authentication; using NzbDrone.Core.Blocklisting; using NzbDrone.Core.Configuration; +using NzbDrone.Core.CustomFilters; using NzbDrone.Core.DataAugmentation.Scene; using NzbDrone.Core.Datastore.Converters; using NzbDrone.Core.Datastore.Extensions; using NzbDrone.Core.Download; -using NzbDrone.Core.Download.Pending; -using NzbDrone.Core.Indexers; -using NzbDrone.Core.Instrumentation; -using NzbDrone.Core.Jobs; -using NzbDrone.Core.MediaFiles; -using NzbDrone.Core.Profiles.Delay; -using NzbDrone.Core.RemotePathMappings; -using NzbDrone.Core.Notifications; -using NzbDrone.Core.Organizer; -using NzbDrone.Core.Parser.Model; -using NzbDrone.Core.Profiles.Qualities; -using NzbDrone.Core.Qualities; -using NzbDrone.Core.RootFolders; -using NzbDrone.Core.SeriesStats; -using NzbDrone.Core.Tags; -using NzbDrone.Core.ThingiProvider; -using NzbDrone.Core.Tv; -using NzbDrone.Common.Disk; -using NzbDrone.Core.Authentication; -using NzbDrone.Core.CustomFilters; using NzbDrone.Core.Download.History; +using NzbDrone.Core.Download.Pending; using NzbDrone.Core.Extras.Metadata; using NzbDrone.Core.Extras.Metadata.Files; using NzbDrone.Core.Extras.Others; using NzbDrone.Core.Extras.Subtitles; using NzbDrone.Core.History; -using NzbDrone.Core.Messaging.Commands; -using NzbDrone.Core.Languages; -using NzbDrone.Core.Profiles.Languages; -using NzbDrone.Core.Profiles.Releases; -using NzbDrone.Core.Update.History; -using NzbDrone.Core.ImportLists.Exclusions; using NzbDrone.Core.ImportLists; +using NzbDrone.Core.ImportLists.Exclusions; +using NzbDrone.Core.Indexers; +using NzbDrone.Core.Instrumentation; +using NzbDrone.Core.Jobs; +using NzbDrone.Core.Languages; +using NzbDrone.Core.MediaFiles; +using NzbDrone.Core.Messaging.Commands; +using NzbDrone.Core.Notifications; +using NzbDrone.Core.Organizer; +using NzbDrone.Core.Parser.Model; +using NzbDrone.Core.Profiles.Delay; +using NzbDrone.Core.Profiles.Languages; +using NzbDrone.Core.Profiles.Qualities; +using NzbDrone.Core.Profiles.Releases; +using NzbDrone.Core.Qualities; +using NzbDrone.Core.RemotePathMappings; +using NzbDrone.Core.RootFolders; +using NzbDrone.Core.SeriesStats; +using NzbDrone.Core.Tags; +using NzbDrone.Core.ThingiProvider; +using NzbDrone.Core.Tv; +using NzbDrone.Core.Update.History; namespace NzbDrone.Core.Datastore { diff --git a/src/NzbDrone.Core/DecisionEngine/DownloadDecision.cs b/src/NzbDrone.Core/DecisionEngine/DownloadDecision.cs index cad8177cb..01aa647cf 100644 --- a/src/NzbDrone.Core/DecisionEngine/DownloadDecision.cs +++ b/src/NzbDrone.Core/DecisionEngine/DownloadDecision.cs @@ -32,7 +32,7 @@ public DownloadDecision(RemoteEpisode episode, params Rejection[] rejections) RemoteEpisode = episode; Rejections = rejections.ToList(); } - + public override string ToString() { if (Approved) @@ -43,4 +43,4 @@ public override string ToString() return "[Rejected " + Rejections.Count() + "]" + RemoteEpisode; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/DecisionEngine/DownloadDecisionComparer.cs b/src/NzbDrone.Core/DecisionEngine/DownloadDecisionComparer.cs index 89728774b..86ae5a738 100644 --- a/src/NzbDrone.Core/DecisionEngine/DownloadDecisionComparer.cs +++ b/src/NzbDrone.Core/DecisionEngine/DownloadDecisionComparer.cs @@ -55,7 +55,7 @@ private int CompareBy(TSubject left, TSubject right, Func(TSubject left, TSubject right, Func funcValue) where TValue : IComparable { - return CompareBy(left, right, funcValue)*-1; + return CompareBy(left, right, funcValue) * -1; } private int CompareAll(params int[] comparers) @@ -77,8 +77,7 @@ private int CompareQuality(DownloadDecision x, DownloadDecision y) return CompareAll( CompareBy(x.RemoteEpisode, y.RemoteEpisode, remoteEpisode => remoteEpisode.Series.QualityProfile.Value.GetIndex(remoteEpisode.ParsedEpisodeInfo.Quality.Quality)), - CompareBy(x.RemoteEpisode, y.RemoteEpisode, remoteEpisode => remoteEpisode.ParsedEpisodeInfo.Quality.Revision) - ); + CompareBy(x.RemoteEpisode, y.RemoteEpisode, remoteEpisode => remoteEpisode.ParsedEpisodeInfo.Quality.Revision)); } private int CompareLanguage(DownloadDecision x, DownloadDecision y) @@ -105,7 +104,8 @@ private int CompareProtocol(DownloadDecision x, DownloadDecision y) private int CompareEpisodeCount(DownloadDecision x, DownloadDecision y) { - var seasonPackCompare = CompareBy(x.RemoteEpisode, y.RemoteEpisode, + var seasonPackCompare = CompareBy(x.RemoteEpisode, + y.RemoteEpisode, remoteEpisode => remoteEpisode.ParsedEpisodeInfo.FullSeason); if (seasonPackCompare != 0) diff --git a/src/NzbDrone.Core/DecisionEngine/DownloadDecisionMaker.cs b/src/NzbDrone.Core/DecisionEngine/DownloadDecisionMaker.cs index d32ff0b5c..532b157e1 100644 --- a/src/NzbDrone.Core/DecisionEngine/DownloadDecisionMaker.cs +++ b/src/NzbDrone.Core/DecisionEngine/DownloadDecisionMaker.cs @@ -57,7 +57,6 @@ private IEnumerable GetDecisions(List reports, Se { _logger.ProgressInfo("Processing {0} releases", reports.Count); } - else { _logger.ProgressInfo("No results found"); @@ -153,7 +152,6 @@ private IEnumerable GetDecisions(List reports, Se { _logger.Debug("Release rejected for the following reasons: {0}", string.Join(", ", decision.Rejections)); } - else { _logger.Debug("Release accepted"); @@ -174,7 +172,10 @@ private DownloadDecision GetDecisionForReport(RemoteEpisode remoteEpisode, Searc .Where(c => c != null) .ToArray(); - if (reasons.Any()) break; + if (reasons.Any()) + { + break; + } } return new DownloadDecision(remoteEpisode, reasons.ToArray()); diff --git a/src/NzbDrone.Core/DecisionEngine/DownloadDecisionPriorizationService.cs b/src/NzbDrone.Core/DecisionEngine/DownloadDecisionPriorizationService.cs index ce3365471..af399a838 100644 --- a/src/NzbDrone.Core/DecisionEngine/DownloadDecisionPriorizationService.cs +++ b/src/NzbDrone.Core/DecisionEngine/DownloadDecisionPriorizationService.cs @@ -1,5 +1,5 @@ -using System.Linq; -using System.Collections.Generic; +using System.Collections.Generic; +using System.Linq; using NzbDrone.Core.Configuration; using NzbDrone.Core.Profiles.Delay; diff --git a/src/NzbDrone.Core/DecisionEngine/Specifications/AcceptableSizeSpecification.cs b/src/NzbDrone.Core/DecisionEngine/Specifications/AcceptableSizeSpecification.cs index b5403b58b..4e2367f99 100644 --- a/src/NzbDrone.Core/DecisionEngine/Specifications/AcceptableSizeSpecification.cs +++ b/src/NzbDrone.Core/DecisionEngine/Specifications/AcceptableSizeSpecification.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.Linq; using NLog; using NzbDrone.Common.Extensions; @@ -6,7 +7,6 @@ using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Qualities; using NzbDrone.Core.Tv; -using System.Collections.Generic; namespace NzbDrone.Core.DecisionEngine.Specifications { @@ -90,6 +90,7 @@ public Decision IsSatisfiedBy(RemoteEpisode subject, SearchCriteriaBase searchCr return Decision.Reject("{0} is smaller than minimum allowed {1} (for {2})", subject.Release.Size.SizeSuffix(), minSize.SizeSuffix(), runtimeMessage); } } + if (!qualityDefinition.MaxSize.HasValue || qualityDefinition.MaxSize.Value == 0) { _logger.Debug("Max size is unlimited, skipping size check"); diff --git a/src/NzbDrone.Core/DecisionEngine/Specifications/CutoffSpecification.cs b/src/NzbDrone.Core/DecisionEngine/Specifications/CutoffSpecification.cs index 758c70ab8..07305d9be 100644 --- a/src/NzbDrone.Core/DecisionEngine/Specifications/CutoffSpecification.cs +++ b/src/NzbDrone.Core/DecisionEngine/Specifications/CutoffSpecification.cs @@ -40,7 +40,7 @@ public virtual Decision IsSatisfiedBy(RemoteEpisode subject, SearchCriteriaBase if (!_upgradableSpecification.CutoffNotMet(qualityProfile, languageProfile, - file.Quality, + file.Quality, file.Language, _episodeFilePreferredWordCalculator.Calculate(subject.Series, file), subject.ParsedEpisodeInfo.Quality, diff --git a/src/NzbDrone.Core/DecisionEngine/Specifications/FullSeasonSpecification.cs b/src/NzbDrone.Core/DecisionEngine/Specifications/FullSeasonSpecification.cs index 63ecdffc8..12762aa79 100644 --- a/src/NzbDrone.Core/DecisionEngine/Specifications/FullSeasonSpecification.cs +++ b/src/NzbDrone.Core/DecisionEngine/Specifications/FullSeasonSpecification.cs @@ -1,9 +1,9 @@ using System; +using System.Linq; using NLog; +using NzbDrone.Common.Extensions; using NzbDrone.Core.IndexerSearch.Definitions; using NzbDrone.Core.Parser.Model; -using NzbDrone.Common.Extensions; -using System.Linq; namespace NzbDrone.Core.DecisionEngine.Specifications { diff --git a/src/NzbDrone.Core/DecisionEngine/Specifications/LanguageSpecification.cs b/src/NzbDrone.Core/DecisionEngine/Specifications/LanguageSpecification.cs index cf32e6e33..5a98fb28b 100644 --- a/src/NzbDrone.Core/DecisionEngine/Specifications/LanguageSpecification.cs +++ b/src/NzbDrone.Core/DecisionEngine/Specifications/LanguageSpecification.cs @@ -1,5 +1,5 @@ -using NLog; using System.Linq; +using NLog; using NzbDrone.Core.IndexerSearch.Definitions; using NzbDrone.Core.Parser.Model; @@ -20,14 +20,14 @@ public LanguageSpecification(Logger logger) public virtual Decision IsSatisfiedBy(RemoteEpisode subject, SearchCriteriaBase searchCriteria) { var wantedLanguage = subject.Series.LanguageProfile.Value.Languages; - var _language = subject.ParsedEpisodeInfo.Language; + var language = subject.ParsedEpisodeInfo.Language; _logger.Debug("Checking if report meets language requirements. {0}", subject.ParsedEpisodeInfo.Language); - - if (!wantedLanguage.Exists(v => v.Allowed && v.Language == _language)) + + if (!wantedLanguage.Exists(v => v.Allowed && v.Language == language)) { - _logger.Debug("Report Language: {0} rejected because it is not wanted in profile {1}", _language, subject.Series.LanguageProfile.Value.Name); - return Decision.Reject("{0} is not allowed in profile {1}", _language, subject.Series.LanguageProfile.Value.Name); + _logger.Debug("Report Language: {0} rejected because it is not wanted in profile {1}", language, subject.Series.LanguageProfile.Value.Name); + return Decision.Reject("{0} is not allowed in profile {1}", language, subject.Series.LanguageProfile.Value.Name); } return Decision.Accept(); diff --git a/src/NzbDrone.Core/DecisionEngine/Specifications/MinimumAgeSpecification.cs b/src/NzbDrone.Core/DecisionEngine/Specifications/MinimumAgeSpecification.cs index 48d2bfa98..854e4e5ed 100644 --- a/src/NzbDrone.Core/DecisionEngine/Specifications/MinimumAgeSpecification.cs +++ b/src/NzbDrone.Core/DecisionEngine/Specifications/MinimumAgeSpecification.cs @@ -38,7 +38,6 @@ public virtual Decision IsSatisfiedBy(RemoteEpisode subject, SearchCriteriaBase return Decision.Accept(); } - _logger.Debug("Checking if report meets minimum age requirements. {0}", ageRounded); if (age < minimumAge) diff --git a/src/NzbDrone.Core/DecisionEngine/Specifications/QueueSpecification.cs b/src/NzbDrone.Core/DecisionEngine/Specifications/QueueSpecification.cs index 0a3f8776e..7be492c56 100644 --- a/src/NzbDrone.Core/DecisionEngine/Specifications/QueueSpecification.cs +++ b/src/NzbDrone.Core/DecisionEngine/Specifications/QueueSpecification.cs @@ -56,12 +56,12 @@ public Decision IsSatisfiedBy(RemoteEpisode subject, SearchCriteriaBase searchCr var queuedItemPreferredWordScore = _preferredWordServiceCalculator.Calculate(subject.Series, queueItem.Title, subject.Release?.IndexerId ?? 0); if (!_upgradableSpecification.CutoffNotMet(qualityProfile, - languageProfile, - remoteEpisode.ParsedEpisodeInfo.Quality, - remoteEpisode.ParsedEpisodeInfo.Language, - queuedItemPreferredWordScore, - subject.ParsedEpisodeInfo.Quality, - subject.PreferredWordScore)) + languageProfile, + remoteEpisode.ParsedEpisodeInfo.Quality, + remoteEpisode.ParsedEpisodeInfo.Language, + queuedItemPreferredWordScore, + subject.ParsedEpisodeInfo.Quality, + subject.PreferredWordScore)) { return Decision.Reject("Release in queue already meets cutoff: {0} - {1}", remoteEpisode.ParsedEpisodeInfo.Quality, remoteEpisode.ParsedEpisodeInfo.Language); } @@ -69,8 +69,8 @@ public Decision IsSatisfiedBy(RemoteEpisode subject, SearchCriteriaBase searchCr _logger.Debug("Checking if release is higher quality than queued release. Queued: {0} - {1}", remoteEpisode.ParsedEpisodeInfo.Quality, remoteEpisode.ParsedEpisodeInfo.Language); if (!_upgradableSpecification.IsUpgradable(qualityProfile, - languageProfile, - remoteEpisode.ParsedEpisodeInfo.Quality, + languageProfile, + remoteEpisode.ParsedEpisodeInfo.Quality, remoteEpisode.ParsedEpisodeInfo.Language, queuedItemPreferredWordScore, subject.ParsedEpisodeInfo.Quality, diff --git a/src/NzbDrone.Core/DecisionEngine/Specifications/RepackSpecification.cs b/src/NzbDrone.Core/DecisionEngine/Specifications/RepackSpecification.cs index aa1c048a9..a721a85f0 100644 --- a/src/NzbDrone.Core/DecisionEngine/Specifications/RepackSpecification.cs +++ b/src/NzbDrone.Core/DecisionEngine/Specifications/RepackSpecification.cs @@ -49,10 +49,12 @@ public Decision IsSatisfiedBy(RemoteEpisode subject, SearchCriteriaBase searchCr { _logger.Debug( "Release is a repack for a different release group. Release Group: {0}. File release group: {1}", - releaseGroup, fileReleaseGroup); + releaseGroup, + fileReleaseGroup); return Decision.Reject( "Release is a repack for a different release group. Release Group: {0}. File release group: {1}", - releaseGroup, fileReleaseGroup); + releaseGroup, + fileReleaseGroup); } } } diff --git a/src/NzbDrone.Core/DecisionEngine/Specifications/RssSync/DelaySpecification.cs b/src/NzbDrone.Core/DecisionEngine/Specifications/RssSync/DelaySpecification.cs index 8819ba686..45b5637cc 100644 --- a/src/NzbDrone.Core/DecisionEngine/Specifications/RssSync/DelaySpecification.cs +++ b/src/NzbDrone.Core/DecisionEngine/Specifications/RssSync/DelaySpecification.cs @@ -2,10 +2,10 @@ using NLog; using NzbDrone.Core.Download.Pending; using NzbDrone.Core.IndexerSearch.Definitions; +using NzbDrone.Core.Languages; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Profiles.Delay; using NzbDrone.Core.Qualities; -using NzbDrone.Core.Languages; namespace NzbDrone.Core.DecisionEngine.Specifications.RssSync { diff --git a/src/NzbDrone.Core/DecisionEngine/Specifications/Search/EpisodeRequestedSpecification.cs b/src/NzbDrone.Core/DecisionEngine/Specifications/Search/EpisodeRequestedSpecification.cs index 18c59a061..65677471d 100644 --- a/src/NzbDrone.Core/DecisionEngine/Specifications/Search/EpisodeRequestedSpecification.cs +++ b/src/NzbDrone.Core/DecisionEngine/Specifications/Search/EpisodeRequestedSpecification.cs @@ -3,7 +3,6 @@ using NzbDrone.Core.IndexerSearch.Definitions; using NzbDrone.Core.Parser.Model; - namespace NzbDrone.Core.DecisionEngine.Specifications.Search { public class EpisodeRequestedSpecification : IDecisionEngineSpecification @@ -49,7 +48,6 @@ public Decision IsSatisfiedBy(RemoteEpisode remoteEpisode, SearchCriteriaBase se { return Decision.Reject("Episode wasn't requested"); } - } return Decision.Accept(); diff --git a/src/NzbDrone.Core/DecisionEngine/Specifications/Search/SceneMappingSpecification.cs b/src/NzbDrone.Core/DecisionEngine/Specifications/Search/SceneMappingSpecification.cs index e06e05365..3fd5f3868 100644 --- a/src/NzbDrone.Core/DecisionEngine/Specifications/Search/SceneMappingSpecification.cs +++ b/src/NzbDrone.Core/DecisionEngine/Specifications/Search/SceneMappingSpecification.cs @@ -33,10 +33,9 @@ public Decision IsSatisfiedBy(RemoteEpisode remoteEpisode, SearchCriteriaBase se return Decision.Accept(); } - var split = remoteEpisode.SceneMapping.SceneOrigin.Split(':'); - var isInteractive = (searchCriteria != null && searchCriteria.InteractiveSearch); + var isInteractive = searchCriteria != null && searchCriteria.InteractiveSearch; if (remoteEpisode.SceneMapping.Comment.IsNotNullOrWhiteSpace()) { diff --git a/src/NzbDrone.Core/DecisionEngine/Specifications/Search/SeasonMatchSpecification.cs b/src/NzbDrone.Core/DecisionEngine/Specifications/Search/SeasonMatchSpecification.cs index 155e3c41f..1acfd44f9 100644 --- a/src/NzbDrone.Core/DecisionEngine/Specifications/Search/SeasonMatchSpecification.cs +++ b/src/NzbDrone.Core/DecisionEngine/Specifications/Search/SeasonMatchSpecification.cs @@ -27,7 +27,10 @@ public Decision IsSatisfiedBy(RemoteEpisode remoteEpisode, SearchCriteriaBase se } var singleEpisodeSpec = searchCriteria as SeasonSearchCriteria; - if (singleEpisodeSpec == null) return Decision.Accept(); + if (singleEpisodeSpec == null) + { + return Decision.Accept(); + } if (singleEpisodeSpec.SeasonNumber != remoteEpisode.ParsedEpisodeInfo.SeasonNumber) { diff --git a/src/NzbDrone.Core/DecisionEngine/Specifications/Search/SingleEpisodeSearchMatchSpecification.cs b/src/NzbDrone.Core/DecisionEngine/Specifications/Search/SingleEpisodeSearchMatchSpecification.cs index 3cc0a3ea1..1aa995ef7 100644 --- a/src/NzbDrone.Core/DecisionEngine/Specifications/Search/SingleEpisodeSearchMatchSpecification.cs +++ b/src/NzbDrone.Core/DecisionEngine/Specifications/Search/SingleEpisodeSearchMatchSpecification.cs @@ -28,10 +28,16 @@ public Decision IsSatisfiedBy(RemoteEpisode remoteEpisode, SearchCriteriaBase se } var singleEpisodeSpec = searchCriteria as SingleEpisodeSearchCriteria; - if (singleEpisodeSpec != null) return IsSatisfiedBy(remoteEpisode, singleEpisodeSpec); + if (singleEpisodeSpec != null) + { + return IsSatisfiedBy(remoteEpisode, singleEpisodeSpec); + } var animeEpisodeSpec = searchCriteria as AnimeEpisodeSearchCriteria; - if (animeEpisodeSpec != null) return IsSatisfiedBy(remoteEpisode, animeEpisodeSpec); + if (animeEpisodeSpec != null) + { + return IsSatisfiedBy(remoteEpisode, animeEpisodeSpec); + } return Decision.Accept(); } diff --git a/src/NzbDrone.Core/DecisionEngine/Specifications/SeasonPackOnlySpecification.cs b/src/NzbDrone.Core/DecisionEngine/Specifications/SeasonPackOnlySpecification.cs index ccc690dba..02e3fc9c0 100644 --- a/src/NzbDrone.Core/DecisionEngine/Specifications/SeasonPackOnlySpecification.cs +++ b/src/NzbDrone.Core/DecisionEngine/Specifications/SeasonPackOnlySpecification.cs @@ -1,10 +1,10 @@ -using System; +using System; +using System.Linq; using NLog; +using NzbDrone.Common.Extensions; using NzbDrone.Core.Configuration; using NzbDrone.Core.IndexerSearch.Definitions; using NzbDrone.Core.Parser.Model; -using NzbDrone.Common.Extensions; -using System.Linq; using NzbDrone.Core.Tv; namespace NzbDrone.Core.DecisionEngine.Specifications diff --git a/src/NzbDrone.Core/DecisionEngine/Specifications/TorrentSeedingSpecification.cs b/src/NzbDrone.Core/DecisionEngine/Specifications/TorrentSeedingSpecification.cs index 7caabeed5..be0de3fdb 100644 --- a/src/NzbDrone.Core/DecisionEngine/Specifications/TorrentSeedingSpecification.cs +++ b/src/NzbDrone.Core/DecisionEngine/Specifications/TorrentSeedingSpecification.cs @@ -20,7 +20,6 @@ public TorrentSeedingSpecification(IIndexerFactory indexerFactory, Logger logger public SpecificationPriority Priority => SpecificationPriority.Default; public RejectionType Type => RejectionType.Permanent; - public Decision IsSatisfiedBy(RemoteEpisode remoteEpisode, SearchCriteriaBase searchCriteria) { var torrentInfo = remoteEpisode.Release as TorrentInfo; diff --git a/src/NzbDrone.Core/DecisionEngine/Specifications/UpgradableSpecification.cs b/src/NzbDrone.Core/DecisionEngine/Specifications/UpgradableSpecification.cs index 71f9bb384..03917818f 100644 --- a/src/NzbDrone.Core/DecisionEngine/Specifications/UpgradableSpecification.cs +++ b/src/NzbDrone.Core/DecisionEngine/Specifications/UpgradableSpecification.cs @@ -85,7 +85,7 @@ public bool IsUpgradable(QualityProfile qualityProfile, LanguageProfile language _logger.Debug("Existing item has better language, skipping"); return false; } - + if (!IsPreferredWordUpgradable(currentScore, newScore)) { _logger.Debug("Existing item has an equal or better preferred word score, skipping"); @@ -168,8 +168,8 @@ public bool IsUpgradeAllowed(QualityProfile qualityProfile, LanguageProfile lang var isQualityUpgrade = new QualityModelComparer(qualityProfile).Compare(newQuality, currentQuality) > 0; var isLanguageUpgrade = new LanguageComparer(languageProfile).Compare(newLanguage, currentLanguage) > 0; - if (isQualityUpgrade && qualityProfile.UpgradeAllowed || - isLanguageUpgrade && languageProfile.UpgradeAllowed) + if ((isQualityUpgrade && qualityProfile.UpgradeAllowed) || + (isLanguageUpgrade && languageProfile.UpgradeAllowed)) { _logger.Debug("At least one profile allows upgrading"); return true; diff --git a/src/NzbDrone.Core/DecisionEngine/Specifications/UpgradeAllowedSpecification.cs b/src/NzbDrone.Core/DecisionEngine/Specifications/UpgradeAllowedSpecification.cs index 63fc1b989..a77feddde 100644 --- a/src/NzbDrone.Core/DecisionEngine/Specifications/UpgradeAllowedSpecification.cs +++ b/src/NzbDrone.Core/DecisionEngine/Specifications/UpgradeAllowedSpecification.cs @@ -35,8 +35,8 @@ public virtual Decision IsSatisfiedBy(RemoteEpisode subject, SearchCriteriaBase _logger.Debug("Comparing file quality and language with report. Existing file is {0} - {1}", file.Quality, file.Language); if (!_upgradableSpecification.IsUpgradeAllowed(qualityProfile, - languageProfile, - file.Quality, + languageProfile, + file.Quality, file.Language, subject.ParsedEpisodeInfo.Quality, subject.ParsedEpisodeInfo.Language)) diff --git a/src/NzbDrone.Core/DecisionEngine/Specifications/UpgradeDiskSpecification.cs b/src/NzbDrone.Core/DecisionEngine/Specifications/UpgradeDiskSpecification.cs index 9e386277a..35ee34ae7 100644 --- a/src/NzbDrone.Core/DecisionEngine/Specifications/UpgradeDiskSpecification.cs +++ b/src/NzbDrone.Core/DecisionEngine/Specifications/UpgradeDiskSpecification.cs @@ -35,12 +35,12 @@ public virtual Decision IsSatisfiedBy(RemoteEpisode subject, SearchCriteriaBase _logger.Debug("Comparing file quality and language with report. Existing file is {0} - {1}", file.Quality, file.Language); - if (!_upgradableSpecification.IsUpgradable(subject.Series.QualityProfile, - subject.Series.LanguageProfile, - file.Quality, + if (!_upgradableSpecification.IsUpgradable(subject.Series.QualityProfile, + subject.Series.LanguageProfile, + file.Quality, file.Language, _episodeFilePreferredWordCalculator.Calculate(subject.Series, file), - subject.ParsedEpisodeInfo.Quality, + subject.ParsedEpisodeInfo.Quality, subject.ParsedEpisodeInfo.Language, subject.PreferredWordScore)) { diff --git a/src/NzbDrone.Core/Download/Aggregation/RemoteEpisodeAggregationService.cs b/src/NzbDrone.Core/Download/Aggregation/RemoteEpisodeAggregationService.cs index 770ac0ae5..a2c2ae081 100644 --- a/src/NzbDrone.Core/Download/Aggregation/RemoteEpisodeAggregationService.cs +++ b/src/NzbDrone.Core/Download/Aggregation/RemoteEpisodeAggregationService.cs @@ -37,7 +37,6 @@ public RemoteEpisode Augment(RemoteEpisode remoteEpisode) } } - return remoteEpisode; } } diff --git a/src/NzbDrone.Core/Download/Clients/Aria2/Aria2.cs b/src/NzbDrone.Core/Download/Clients/Aria2/Aria2.cs index fb8ae5f21..3b51add84 100644 --- a/src/NzbDrone.Core/Download/Clients/Aria2/Aria2.cs +++ b/src/NzbDrone.Core/Download/Clients/Aria2/Aria2.cs @@ -74,11 +74,12 @@ public override IEnumerable GetItems() { var torrents = _proxy.GetTorrents(Settings); - foreach(var torrent in torrents) + foreach (var torrent in torrents) { var firstFile = torrent.Files?.FirstOrDefault(); - if (firstFile?.Path?.Contains("[METADATA]") == true) //skip metadata download + //skip metadata download + if (firstFile?.Path?.Contains("[METADATA]") == true) { continue; } @@ -91,7 +92,7 @@ public override IEnumerable GetItems() var status = DownloadItemStatus.Failed; var title = ""; - if(torrent.Bittorrent?.ContainsKey("info") == true && ((XmlRpcStruct)torrent.Bittorrent["info"]).ContainsKey("name")) + if (torrent.Bittorrent?.ContainsKey("info") == true && ((XmlRpcStruct)torrent.Bittorrent["info"]).ContainsKey("name")) { title = ((XmlRpcStruct)torrent.Bittorrent["info"])["name"].ToString(); } @@ -141,13 +142,13 @@ public override IEnumerable GetItems() Message = torrent.ErrorMessage, OutputPath = outputPath, RemainingSize = totalLength - completedLength, - RemainingTime = downloadSpeed == 0 ? (TimeSpan?)null : new TimeSpan(0,0, (int)((totalLength - completedLength) / downloadSpeed)), + RemainingTime = downloadSpeed == 0 ? (TimeSpan?)null : new TimeSpan(0, 0, (int)((totalLength - completedLength) / downloadSpeed)), Removed = torrent.Status == "removed", SeedRatio = totalLength > 0 ? (double)uploadedLength / totalLength : 0, Status = status, Title = title, TotalSize = totalLength, - }; + }; } } @@ -157,7 +158,7 @@ public override void RemoveItem(DownloadClientItem item, bool deleteData) var hash = item.DownloadId.ToLower(); var aria2Item = _proxy.GetTorrents(Settings).FirstOrDefault(t => t.InfoHash?.ToLower() == hash); - if(aria2Item == null) + if (aria2Item == null) { _logger.Error($"Aria2 could not find infoHash '{hash}' for deletion."); return; diff --git a/src/NzbDrone.Core/Download/Clients/Aria2/Aria2Containers.cs b/src/NzbDrone.Core/Download/Clients/Aria2/Aria2Containers.cs index 028919ef3..d4ab5a49c 100644 --- a/src/NzbDrone.Core/Download/Clients/Aria2/Aria2Containers.cs +++ b/src/NzbDrone.Core/Download/Clients/Aria2/Aria2Containers.cs @@ -1,4 +1,4 @@ -using CookComputing.XmlRpc; +using CookComputing.XmlRpc; namespace NzbDrone.Core.Download.Clients.Aria2 { @@ -109,4 +109,3 @@ public class Aria2Status public string ErrorMessage; } } - diff --git a/src/NzbDrone.Core/Download/Clients/Aria2/Aria2Proxy.cs b/src/NzbDrone.Core/Download/Clients/Aria2/Aria2Proxy.cs index e67e5062b..3e7b5a6be 100644 --- a/src/NzbDrone.Core/Download/Clients/Aria2/Aria2Proxy.cs +++ b/src/NzbDrone.Core/Download/Clients/Aria2/Aria2Proxy.cs @@ -1,9 +1,9 @@ -using CookComputing.XmlRpc; -using NLog; using System; using System.Collections; using System.Collections.Generic; using System.Net; +using CookComputing.XmlRpc; +using NLog; namespace NzbDrone.Core.Download.Clients.Aria2 { @@ -32,7 +32,7 @@ public interface IAria2 : IXmlRpcProxy [XmlRpcMethod("aria2.forceRemove")] string Remove(string token, string gid); - + [XmlRpcMethod("aria2.removeDownloadResult")] string RemoveResult(string token, string gid); @@ -49,7 +49,7 @@ public interface IAria2 : IXmlRpcProxy Aria2Status[] GetWaiting(string token, int offset, int num); [XmlRpcMethod("aria2.tellStopped")] - Aria2Status[] GetStopped(string token, int offset, int num); + Aria2Status[] GetStopped(string token, int offset, int num); } public class Aria2Proxy : IAria2Proxy @@ -95,7 +95,6 @@ public Aria2Status GetFromGID(Aria2Settings settings, string gid) return found; } - public List GetTorrents(Aria2Settings settings) { _logger.Trace("> aria2.tellActive"); @@ -108,13 +107,13 @@ public List GetTorrents(Aria2Settings settings) _logger.Trace("> aria2.tellWaiting"); - var waiting = ExecuteRequest(() => client.GetWaiting(GetToken(settings), 0, 10*1024)); + var waiting = ExecuteRequest(() => client.GetWaiting(GetToken(settings), 0, 10 * 1024)); _logger.Trace("< aria2.tellWaiting"); _logger.Trace("> aria2.tellStopped"); - var stopped = ExecuteRequest(() => client.GetStopped(GetToken(settings), 0, 10*1024)); + var stopped = ExecuteRequest(() => client.GetStopped(GetToken(settings), 0, 10 * 1024)); _logger.Trace("< aria2.tellStopped"); @@ -123,7 +122,7 @@ public List GetTorrents(Aria2Settings settings) items.AddRange(active); items.AddRange(waiting); items.AddRange(stopped); - + return items; } @@ -138,8 +137,8 @@ public Dictionary GetGlobals(Aria2Settings settings) var ret = new Dictionary(); - foreach(DictionaryEntry option in options) - { + foreach (DictionaryEntry option in options) + { ret.Add(option.Key.ToString(), option.Value?.ToString()); } @@ -181,7 +180,7 @@ public bool RemoveTorrent(Aria2Settings settings, string gid) return gid == gidres; } - + public bool RemoveCompletedTorrent(Aria2Settings settings, string gid) { _logger.Trace("> aria2.removeDownloadResult"); diff --git a/src/NzbDrone.Core/Download/Clients/Aria2/Aria2Settings.cs b/src/NzbDrone.Core/Download/Clients/Aria2/Aria2Settings.cs index dbee57f2c..e88bc4cc1 100644 --- a/src/NzbDrone.Core/Download/Clients/Aria2/Aria2Settings.cs +++ b/src/NzbDrone.Core/Download/Clients/Aria2/Aria2Settings.cs @@ -1,4 +1,4 @@ -using FluentValidation; +using FluentValidation; using NzbDrone.Core.Annotations; using NzbDrone.Core.ThingiProvider; using NzbDrone.Core.Validation; @@ -41,7 +41,6 @@ public Aria2Settings() [FieldDefinition(4, Label = "Secret token", Type = FieldType.Password, Privacy = PrivacyLevel.Password)] public string SecretToken { get; set; } - public NzbDroneValidationResult Validate() { return new NzbDroneValidationResult(Validator.Validate(this)); diff --git a/src/NzbDrone.Core/Download/Clients/Blackhole/WatchFolderItem.cs b/src/NzbDrone.Core/Download/Clients/Blackhole/WatchFolderItem.cs index 554aa82b5..bba855d0d 100644 --- a/src/NzbDrone.Core/Download/Clients/Blackhole/WatchFolderItem.cs +++ b/src/NzbDrone.Core/Download/Clients/Blackhole/WatchFolderItem.cs @@ -1,9 +1,8 @@ -using NzbDrone.Common.Disk; -using System; +using System; +using NzbDrone.Common.Disk; namespace NzbDrone.Core.Download.Clients.Blackhole { - public class WatchFolderItem { public string DownloadId { get; set; } diff --git a/src/NzbDrone.Core/Download/Clients/Deluge/Deluge.cs b/src/NzbDrone.Core/Download/Clients/Deluge/Deluge.cs index 5e7c9954c..d07b1137a 100644 --- a/src/NzbDrone.Core/Download/Clients/Deluge/Deluge.cs +++ b/src/NzbDrone.Core/Download/Clients/Deluge/Deluge.cs @@ -1,17 +1,17 @@ using System; -using System.Linq; using System.Collections.Generic; +using System.Linq; +using System.Net; +using FluentValidation.Results; +using NLog; using NzbDrone.Common.Disk; -using NzbDrone.Common.Http; using NzbDrone.Common.Extensions; +using NzbDrone.Common.Http; +using NzbDrone.Core.Configuration; using NzbDrone.Core.MediaFiles.TorrentInfo; using NzbDrone.Core.Parser.Model; -using NzbDrone.Core.Configuration; -using NzbDrone.Core.Validation; -using NLog; -using FluentValidation.Results; -using System.Net; using NzbDrone.Core.RemotePathMappings; +using NzbDrone.Core.Validation; namespace NzbDrone.Core.Download.Clients.Deluge { @@ -44,7 +44,8 @@ public override void MarkItemAsImported(DownloadClientItem downloadClientItem) catch (DownloadClientUnavailableException) { _logger.Warn("Failed to set torrent post-import label \"{0}\" for {1} in Deluge. Does the label exist?", - Settings.TvImportedCategory, downloadClientItem.Title); + Settings.TvImportedCategory, + downloadClientItem.Title); } } } @@ -67,8 +68,8 @@ protected override string AddFromMagnetLink(RemoteEpisode remoteEpisode, string var isRecentEpisode = remoteEpisode.IsRecentEpisode(); - if (isRecentEpisode && Settings.RecentTvPriority == (int)DelugePriority.First || - !isRecentEpisode && Settings.OlderTvPriority == (int)DelugePriority.First) + if ((isRecentEpisode && Settings.RecentTvPriority == (int)DelugePriority.First) || + (!isRecentEpisode && Settings.OlderTvPriority == (int)DelugePriority.First)) { _proxy.MoveTorrentToTopInQueue(actualHash, Settings); } @@ -94,8 +95,8 @@ protected override string AddFromTorrentFile(RemoteEpisode remoteEpisode, string var isRecentEpisode = remoteEpisode.IsRecentEpisode(); - if (isRecentEpisode && Settings.RecentTvPriority == (int)DelugePriority.First || - !isRecentEpisode && Settings.OlderTvPriority == (int)DelugePriority.First) + if ((isRecentEpisode && Settings.RecentTvPriority == (int)DelugePriority.First) || + (!isRecentEpisode && Settings.OlderTvPriority == (int)DelugePriority.First)) { _proxy.MoveTorrentToTopInQueue(actualHash, Settings); } @@ -122,7 +123,10 @@ public override IEnumerable GetItems() foreach (var torrent in torrents) { - if (torrent.Hash == null) continue; + if (torrent.Hash == null) + { + continue; + } var item = new DownloadClientItem(); item.DownloadId = torrent.Hash.ToUpper(); @@ -216,7 +220,11 @@ public override DownloadClientInfo GetStatus() protected override void Test(List failures) { failures.AddIfNotNull(TestConnection()); - if (failures.HasErrors()) return; + if (failures.HasErrors()) + { + return; + } + failures.AddIfNotNull(TestCategory()); failures.AddIfNotNull(TestGetTorrents()); } diff --git a/src/NzbDrone.Core/Download/Clients/Deluge/DelugeException.cs b/src/NzbDrone.Core/Download/Clients/Deluge/DelugeException.cs index 764662547..fb6ca2a8a 100644 --- a/src/NzbDrone.Core/Download/Clients/Deluge/DelugeException.cs +++ b/src/NzbDrone.Core/Download/Clients/Deluge/DelugeException.cs @@ -1,11 +1,11 @@ -namespace NzbDrone.Core.Download.Clients.Deluge +namespace NzbDrone.Core.Download.Clients.Deluge { public class DelugeException : DownloadClientException { public int Code { get; set; } public DelugeException(string message, int code) - :base (message + " (code " + code + ")") + : base(message + " (code " + code + ")") { Code = code; } diff --git a/src/NzbDrone.Core/Download/Clients/Deluge/DelugePriority.cs b/src/NzbDrone.Core/Download/Clients/Deluge/DelugePriority.cs index e5cf2924c..741392e88 100644 --- a/src/NzbDrone.Core/Download/Clients/Deluge/DelugePriority.cs +++ b/src/NzbDrone.Core/Download/Clients/Deluge/DelugePriority.cs @@ -5,4 +5,4 @@ public enum DelugePriority Last = 0, First = 1 } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Download/Clients/Deluge/DelugeProxy.cs b/src/NzbDrone.Core/Download/Clients/Deluge/DelugeProxy.cs index abd6c8ba7..9158a4408 100644 --- a/src/NzbDrone.Core/Download/Clients/Deluge/DelugeProxy.cs +++ b/src/NzbDrone.Core/Download/Clients/Deluge/DelugeProxy.cs @@ -31,7 +31,7 @@ public interface IDelugeProxy public class DelugeProxy : IDelugeProxy { - private static readonly string[] requiredProperties = new string[] { "hash", "name", "state", "progress", "eta", "message", "is_finished", "save_path", "total_size", "total_done", "time_added", "active_time", "ratio", "is_auto_managed", "stop_at_ratio", "remove_at_ratio", "stop_ratio" }; + private static readonly string[] RequiredProperties = new string[] { "hash", "name", "state", "progress", "eta", "message", "is_finished", "save_path", "total_size", "total_done", "time_added", "active_time", "ratio", "is_auto_managed", "stop_at_ratio", "remove_at_ratio", "stop_ratio" }; private readonly IHttpClient _httpClient; private readonly Logger _logger; @@ -82,7 +82,7 @@ public DelugeTorrent[] GetTorrents(DelugeSettings settings) // TODO: get_torrents_status returns the files as well, which starts to cause deluge timeouts when you get enough season packs. //var response = ProcessRequest>(settings, "core.get_torrents_status", filter, new String[0]); - var response = ProcessRequest(settings, "web.update_ui", requiredProperties, filter); + var response = ProcessRequest(settings, "web.update_ui", RequiredProperties, filter); return GetTorrents(response); } @@ -93,7 +93,7 @@ public DelugeTorrent[] GetTorrentsByLabel(string label, DelugeSettings settings) filter.Add("label", label); //var response = ProcessRequest>(settings, "core.get_torrents_status", filter, new String[0]); - var response = ProcessRequest(settings, "web.update_ui", requiredProperties, filter); + var response = ProcessRequest(settings, "web.update_ui", RequiredProperties, filter); return GetTorrents(response); } @@ -167,7 +167,10 @@ public void SetTorrentConfiguration(string hash, string key, object value, Delug public void SetTorrentSeedingConfiguration(string hash, TorrentSeedConfiguration seedConfiguration, DelugeSettings settings) { - if (seedConfiguration == null) return; + if (seedConfiguration == null) + { + return; + } var ratioArguments = new Dictionary(); @@ -224,6 +227,7 @@ protected TResult ProcessRequest(DelugeSettings settings, string method { return response.Result; } + error = response.Error.ToObject(); throw new DownloadClientAuthenticationException(error.Message); @@ -299,6 +303,7 @@ private void AuthenticateClient(JsonRpcRequestBuilder requestBuilder, DelugeSett _logger.Debug("Deluge authentication failed."); throw new DownloadClientAuthenticationException("Failed to authenticate with Deluge."); } + _logger.Debug("Deluge authentication succeeded."); cookies = response.GetCookies(); @@ -331,7 +336,7 @@ private void ConnectDaemon(JsonRpcRequestBuilder requestBuilder) if (resultHosts.Result != null) { // The returned list contains the id, ip, port and status of each available connection. We want the 127.0.0.1 - var connection = resultHosts.Result.FirstOrDefault(v => "127.0.0.1" == (v[1] as string)); + var connection = resultHosts.Result.FirstOrDefault(v => (v[1] as string) == "127.0.0.1"); if (connection != null) { @@ -342,7 +347,7 @@ private void ConnectDaemon(JsonRpcRequestBuilder requestBuilder) } } - throw new DownloadClientException("Failed to connect to Deluge daemon."); + throw new DownloadClientException("Failed to connect to Deluge daemon."); } private DelugeTorrent[] GetTorrents(DelugeUpdateUIResult result) diff --git a/src/NzbDrone.Core/Download/Clients/Deluge/DelugeTorrent.cs b/src/NzbDrone.Core/Download/Clients/Deluge/DelugeTorrent.cs index 898c425b4..4c7315cc9 100644 --- a/src/NzbDrone.Core/Download/Clients/Deluge/DelugeTorrent.cs +++ b/src/NzbDrone.Core/Download/Clients/Deluge/DelugeTorrent.cs @@ -16,9 +16,9 @@ public class DelugeTorrent // Other paths: What is the difference between 'move_completed_path' and 'move_on_completed_path'? /* - [JsonProperty(PropertyName = "move_completed_path")] + [JsonProperty(PropertyName = "move_completed_path")] public String DownloadPathMoveCompleted { get; set; } - [JsonProperty(PropertyName = "move_on_completed_path")] + [JsonProperty(PropertyName = "move_on_completed_path")] public String DownloadPathMoveOnCompleted { get; set; } */ diff --git a/src/NzbDrone.Core/Download/Clients/DownloadClientAuthenticationException.cs b/src/NzbDrone.Core/Download/Clients/DownloadClientAuthenticationException.cs index 38c956479..6d27bb9bd 100644 --- a/src/NzbDrone.Core/Download/Clients/DownloadClientAuthenticationException.cs +++ b/src/NzbDrone.Core/Download/Clients/DownloadClientAuthenticationException.cs @@ -7,19 +7,16 @@ public class DownloadClientAuthenticationException : DownloadClientException public DownloadClientAuthenticationException(string message, params object[] args) : base(message, args) { - } public DownloadClientAuthenticationException(string message) : base(message) { - } public DownloadClientAuthenticationException(string message, Exception innerException, params object[] args) : base(message, innerException, args) { - } public DownloadClientAuthenticationException(string message, Exception innerException) diff --git a/src/NzbDrone.Core/Download/Clients/DownloadStation/DiskStationApiInfo.cs b/src/NzbDrone.Core/Download/Clients/DownloadStation/DiskStationApiInfo.cs index c2a6667ab..b507747b3 100644 --- a/src/NzbDrone.Core/Download/Clients/DownloadStation/DiskStationApiInfo.cs +++ b/src/NzbDrone.Core/Download/Clients/DownloadStation/DiskStationApiInfo.cs @@ -1,7 +1,7 @@ -namespace NzbDrone.Core.Download.Clients.DownloadStation +namespace NzbDrone.Core.Download.Clients.DownloadStation { public class DiskStationApiInfo - { + { private string _path; public int MaxVersion { get; set; } @@ -16,7 +16,10 @@ public class DiskStationApiInfo public string Path { - get { return _path; } + get + { + return _path; + } set { diff --git a/src/NzbDrone.Core/Download/Clients/DownloadStation/DownloadStationTask.cs b/src/NzbDrone.Core/Download/Clients/DownloadStation/DownloadStationTask.cs index 5b4a61253..1246a6a83 100644 --- a/src/NzbDrone.Core/Download/Clients/DownloadStation/DownloadStationTask.cs +++ b/src/NzbDrone.Core/Download/Clients/DownloadStation/DownloadStationTask.cs @@ -1,4 +1,4 @@ -using System.Collections.Generic; +using System.Collections.Generic; using Newtonsoft.Json; using NzbDrone.Common.Serializer; @@ -35,7 +35,12 @@ public override string ToString() public enum DownloadStationTaskType { - BT, NZB, http, ftp, eMule, https + BT, + NZB, + http, + ftp, + eMule, + https } public enum DownloadStationTaskStatus diff --git a/src/NzbDrone.Core/Download/Clients/DownloadStation/DownloadStationTaskAdditional.cs b/src/NzbDrone.Core/Download/Clients/DownloadStation/DownloadStationTaskAdditional.cs index 45c9fd137..81e55569e 100644 --- a/src/NzbDrone.Core/Download/Clients/DownloadStation/DownloadStationTaskAdditional.cs +++ b/src/NzbDrone.Core/Download/Clients/DownloadStation/DownloadStationTaskAdditional.cs @@ -1,5 +1,5 @@ -using Newtonsoft.Json; -using System.Collections.Generic; +using System.Collections.Generic; +using Newtonsoft.Json; namespace NzbDrone.Core.Download.Clients.DownloadStation { diff --git a/src/NzbDrone.Core/Download/Clients/DownloadStation/DownloadStationTaskFile.cs b/src/NzbDrone.Core/Download/Clients/DownloadStation/DownloadStationTaskFile.cs index d49c5d7dd..3e22560a2 100644 --- a/src/NzbDrone.Core/Download/Clients/DownloadStation/DownloadStationTaskFile.cs +++ b/src/NzbDrone.Core/Download/Clients/DownloadStation/DownloadStationTaskFile.cs @@ -1,9 +1,9 @@ -using Newtonsoft.Json; -using Newtonsoft.Json.Converters; -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Text; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; using static NzbDrone.Core.Download.Clients.DownloadStation.DownloadStationTask; namespace NzbDrone.Core.Download.Clients.DownloadStation diff --git a/src/NzbDrone.Core/Download/Clients/DownloadStation/Proxies/DSMInfoProxy.cs b/src/NzbDrone.Core/Download/Clients/DownloadStation/Proxies/DSMInfoProxy.cs index 9c18d5702..8e0c0c362 100644 --- a/src/NzbDrone.Core/Download/Clients/DownloadStation/Proxies/DSMInfoProxy.cs +++ b/src/NzbDrone.Core/Download/Clients/DownloadStation/Proxies/DSMInfoProxy.cs @@ -14,8 +14,8 @@ public interface IDSMInfoProxy public class DSMInfoProxy : DiskStationProxyBase, IDSMInfoProxy { - public DSMInfoProxy(IHttpClient httpClient, ICacheManager cacheManager, Logger logger) : - base(DiskStationApi.DSMInfo, "SYNO.DSM.Info", httpClient, cacheManager, logger) + public DSMInfoProxy(IHttpClient httpClient, ICacheManager cacheManager, Logger logger) + : base(DiskStationApi.DSMInfo, "SYNO.DSM.Info", httpClient, cacheManager, logger) { } diff --git a/src/NzbDrone.Core/Download/Clients/DownloadStation/Proxies/DiskStationProxyBase.cs b/src/NzbDrone.Core/Download/Clients/DownloadStation/Proxies/DiskStationProxyBase.cs index e8271618c..023e06ee4 100644 --- a/src/NzbDrone.Core/Download/Clients/DownloadStation/Proxies/DiskStationProxyBase.cs +++ b/src/NzbDrone.Core/Download/Clients/DownloadStation/Proxies/DiskStationProxyBase.cs @@ -61,7 +61,8 @@ private string GenerateSessionCacheKey(DownloadStationSettings settings) protected DiskStationResponse ProcessRequest(HttpRequestBuilder requestBuilder, string operation, - DownloadStationSettings settings) where T : new() + DownloadStationSettings settings) + where T : new() { return ProcessRequest(requestBuilder, operation, _apiType, settings); } @@ -69,7 +70,8 @@ protected DiskStationResponse ProcessRequest(HttpRequestBuilder requestBui private DiskStationResponse ProcessRequest(HttpRequestBuilder requestBuilder, string operation, DiskStationApi api, - DownloadStationSettings settings) where T : new() + DownloadStationSettings settings) + where T : new() { var request = requestBuilder.Build(); HttpResponse response; diff --git a/src/NzbDrone.Core/Download/Clients/DownloadStation/Proxies/DownloadStationInfoProxy.cs b/src/NzbDrone.Core/Download/Clients/DownloadStation/Proxies/DownloadStationInfoProxy.cs index 9b0cb00ed..6b9b24847 100644 --- a/src/NzbDrone.Core/Download/Clients/DownloadStation/Proxies/DownloadStationInfoProxy.cs +++ b/src/NzbDrone.Core/Download/Clients/DownloadStation/Proxies/DownloadStationInfoProxy.cs @@ -1,7 +1,7 @@ -using NLog; -using NzbDrone.Common.Http; -using System.Collections.Generic; +using System.Collections.Generic; +using NLog; using NzbDrone.Common.Cache; +using NzbDrone.Common.Http; namespace NzbDrone.Core.Download.Clients.DownloadStation.Proxies { @@ -12,8 +12,8 @@ public interface IDownloadStationInfoProxy : IDiskStationProxy public class DownloadStationInfoProxy : DiskStationProxyBase, IDownloadStationInfoProxy { - public DownloadStationInfoProxy(IHttpClient httpClient, ICacheManager cacheManager, Logger logger) : - base(DiskStationApi.DownloadStationInfo, "SYNO.DownloadStation.Info", httpClient, cacheManager, logger) + public DownloadStationInfoProxy(IHttpClient httpClient, ICacheManager cacheManager, Logger logger) + : base(DiskStationApi.DownloadStationInfo, "SYNO.DownloadStation.Info", httpClient, cacheManager, logger) { } diff --git a/src/NzbDrone.Core/Download/Clients/DownloadStation/Proxies/DownloadStationTaskProxyV2.cs b/src/NzbDrone.Core/Download/Clients/DownloadStation/Proxies/DownloadStationTaskProxyV2.cs index e8a7aaa0b..0484db83e 100644 --- a/src/NzbDrone.Core/Download/Clients/DownloadStation/Proxies/DownloadStationTaskProxyV2.cs +++ b/src/NzbDrone.Core/Download/Clients/DownloadStation/Proxies/DownloadStationTaskProxyV2.cs @@ -72,7 +72,7 @@ public IEnumerable GetTasks(DownloadStationSettings setting if (responseTransfer.Success) { - foreach(var task in response.Data.Task) + foreach (var task in response.Data.Task) { var taskTransfer = responseTransfer.Data.Task.Where(t => t.Id == task.Id).First(); diff --git a/src/NzbDrone.Core/Download/Clients/DownloadStation/Proxies/FileStationProxy.cs b/src/NzbDrone.Core/Download/Clients/DownloadStation/Proxies/FileStationProxy.cs index 29031e0eb..91a0cf198 100644 --- a/src/NzbDrone.Core/Download/Clients/DownloadStation/Proxies/FileStationProxy.cs +++ b/src/NzbDrone.Core/Download/Clients/DownloadStation/Proxies/FileStationProxy.cs @@ -22,7 +22,7 @@ public FileStationProxy(IHttpClient httpClient, ICacheManager cacheManager, Logg : base(DiskStationApi.FileStationList, "SYNO.FileStation.List", httpClient, cacheManager, logger) { } - + public SharedFolderMapping GetSharedFolderMapping(string sharedFolder, DownloadStationSettings settings) { var info = GetInfoFileOrDirectory(sharedFolder, settings); diff --git a/src/NzbDrone.Core/Download/Clients/DownloadStation/Responses/DiskStationError.cs b/src/NzbDrone.Core/Download/Clients/DownloadStation/Responses/DiskStationError.cs index cd29a8815..506b7a75a 100644 --- a/src/NzbDrone.Core/Download/Clients/DownloadStation/Responses/DiskStationError.cs +++ b/src/NzbDrone.Core/Download/Clients/DownloadStation/Responses/DiskStationError.cs @@ -53,7 +53,7 @@ static DiskStationError() FileStationMessages = new Dictionary { - { 160, "Permission denied. Give your user access to FileStation."}, + { 160, "Permission denied. Give your user access to FileStation." }, { 400, "Invalid parameter of file operation" }, { 401, "Unknown error of file operation" }, { 402, "System is too busy" }, @@ -106,7 +106,7 @@ public string GetMessage(DiskStationApi api) return CommonMessages[Code]; } - return $"{ Code } - Unknown error"; + return $"{Code} - Unknown error"; } } } diff --git a/src/NzbDrone.Core/Download/Clients/DownloadStation/Responses/DiskStationInfoResponse.cs b/src/NzbDrone.Core/Download/Clients/DownloadStation/Responses/DiskStationInfoResponse.cs index 54ac7dc8b..6c40ae75c 100644 --- a/src/NzbDrone.Core/Download/Clients/DownloadStation/Responses/DiskStationInfoResponse.cs +++ b/src/NzbDrone.Core/Download/Clients/DownloadStation/Responses/DiskStationInfoResponse.cs @@ -4,6 +4,5 @@ namespace NzbDrone.Core.Download.Clients.DownloadStation.Responses { public class DiskStationApiInfoResponse : Dictionary { - } } diff --git a/src/NzbDrone.Core/Download/Clients/DownloadStation/Responses/DiskStationResponse.cs b/src/NzbDrone.Core/Download/Clients/DownloadStation/Responses/DiskStationResponse.cs index de7aadfc6..43c981669 100644 --- a/src/NzbDrone.Core/Download/Clients/DownloadStation/Responses/DiskStationResponse.cs +++ b/src/NzbDrone.Core/Download/Clients/DownloadStation/Responses/DiskStationResponse.cs @@ -1,6 +1,7 @@ namespace NzbDrone.Core.Download.Clients.DownloadStation.Responses { - public class DiskStationResponse where T:new() + public class DiskStationResponse + where T : new() { public bool Success { get; set; } diff --git a/src/NzbDrone.Core/Download/Clients/DownloadStation/Responses/DownloadStation2TaskInfoResponse.cs b/src/NzbDrone.Core/Download/Clients/DownloadStation/Responses/DownloadStation2TaskInfoResponse.cs index d8d6b2e33..ee705b7ac 100644 --- a/src/NzbDrone.Core/Download/Clients/DownloadStation/Responses/DownloadStation2TaskInfoResponse.cs +++ b/src/NzbDrone.Core/Download/Clients/DownloadStation/Responses/DownloadStation2TaskInfoResponse.cs @@ -5,7 +5,7 @@ namespace NzbDrone.Core.Download.Clients.DownloadStation.Responses public class DownloadStation2TaskInfoResponse { public int Offset { get; set; } - public List Task {get;set;} + public List Task { get; set; } public int Total { get; set; } } } diff --git a/src/NzbDrone.Core/Download/Clients/DownloadStation/Responses/DownloadStationTaskInfoResponse.cs b/src/NzbDrone.Core/Download/Clients/DownloadStation/Responses/DownloadStationTaskInfoResponse.cs index 1d974b913..ebd79f3d7 100644 --- a/src/NzbDrone.Core/Download/Clients/DownloadStation/Responses/DownloadStationTaskInfoResponse.cs +++ b/src/NzbDrone.Core/Download/Clients/DownloadStation/Responses/DownloadStationTaskInfoResponse.cs @@ -5,7 +5,7 @@ namespace NzbDrone.Core.Download.Clients.DownloadStation.Responses public class DownloadStationTaskInfoResponse { public int Offset { get; set; } - public List Tasks {get;set;} + public List Tasks { get; set; } public int Total { get; set; } } } diff --git a/src/NzbDrone.Core/Download/Clients/DownloadStation/Responses/FileStationListFileInfoResponse.cs b/src/NzbDrone.Core/Download/Clients/DownloadStation/Responses/FileStationListFileInfoResponse.cs index 2f689a48b..927fd242b 100644 --- a/src/NzbDrone.Core/Download/Clients/DownloadStation/Responses/FileStationListFileInfoResponse.cs +++ b/src/NzbDrone.Core/Download/Clients/DownloadStation/Responses/FileStationListFileInfoResponse.cs @@ -1,4 +1,4 @@ -using System.Collections.Generic; +using System.Collections.Generic; namespace NzbDrone.Core.Download.Clients.DownloadStation.Responses { @@ -7,6 +7,6 @@ public class FileStationListFileInfoResponse public bool IsDir { get; set; } public string Name { get; set; } public string Path { get; set; } - public Dictionary Additional { get; set; } + public Dictionary Additional { get; set; } } } diff --git a/src/NzbDrone.Core/Download/Clients/DownloadStation/SerialNumberProvider.cs b/src/NzbDrone.Core/Download/Clients/DownloadStation/SerialNumberProvider.cs index ddf971384..dfeb227a2 100644 --- a/src/NzbDrone.Core/Download/Clients/DownloadStation/SerialNumberProvider.cs +++ b/src/NzbDrone.Core/Download/Clients/DownloadStation/SerialNumberProvider.cs @@ -1,4 +1,4 @@ -using System; +using System; using NLog; using NzbDrone.Common.Cache; using NzbDrone.Common.Crypto; @@ -15,9 +15,10 @@ public interface ISerialNumberProvider public class SerialNumberProvider : ISerialNumberProvider { private readonly IDSMInfoProxy _proxy; - private ICached _cache; private readonly ILogger _logger; + private ICached _cache; + public SerialNumberProvider(ICacheManager cacheManager, IDSMInfoProxy proxy, Logger logger) diff --git a/src/NzbDrone.Core/Download/Clients/DownloadStation/SharedFolderResolver.cs b/src/NzbDrone.Core/Download/Clients/DownloadStation/SharedFolderResolver.cs index d1db18db0..b5a308a37 100644 --- a/src/NzbDrone.Core/Download/Clients/DownloadStation/SharedFolderResolver.cs +++ b/src/NzbDrone.Core/Download/Clients/DownloadStation/SharedFolderResolver.cs @@ -1,4 +1,4 @@ -using System; +using System; using NLog; using NzbDrone.Common.Cache; using NzbDrone.Common.Disk; @@ -14,9 +14,10 @@ public interface ISharedFolderResolver public class SharedFolderResolver : ISharedFolderResolver { private readonly IFileStationProxy _proxy; - private ICached _cache; private readonly ILogger _logger; + private ICached _cache; + public SharedFolderResolver(ICacheManager cacheManager, IFileStationProxy proxy, Logger logger) diff --git a/src/NzbDrone.Core/Download/Clients/DownloadStation/TorrentDownloadStation.cs b/src/NzbDrone.Core/Download/Clients/DownloadStation/TorrentDownloadStation.cs index d416c1927..0da7ce22f 100644 --- a/src/NzbDrone.Core/Download/Clients/DownloadStation/TorrentDownloadStation.cs +++ b/src/NzbDrone.Core/Download/Clients/DownloadStation/TorrentDownloadStation.cs @@ -202,7 +202,11 @@ protected override string AddFromTorrentFile(RemoteEpisode remoteEpisode, string protected override void Test(List failures) { failures.AddIfNotNull(TestConnection()); - if (failures.HasErrors()) return; + if (failures.HasErrors()) + { + return; + } + failures.AddIfNotNull(TestOutputPath()); failures.AddIfNotNull(TestGetTorrents()); } @@ -345,8 +349,9 @@ protected ValidationFailure TestOutputPath() return null; } - catch (DownloadClientAuthenticationException ex) // User could not have permission to access to downloadstation + catch (DownloadClientAuthenticationException ex) { + // User could not have permission to access to downloadstation _logger.Error(ex, ex.Message); return new NzbDroneValidationFailure(string.Empty, ex.Message); } @@ -382,6 +387,7 @@ protected ValidationFailure TestConnection() DetailedDescription = "Please verify the hostname and port." }; } + return new NzbDroneValidationFailure(string.Empty, $"Unknown exception: {ex.Message}"); } catch (Exception ex) @@ -447,7 +453,7 @@ protected string GetDownloadDirectory() { return Settings.TvDirectory.TrimStart('/'); } - + var destDir = GetDefaultDir(); if (Settings.TvCategory.IsNotNullOrWhiteSpace()) diff --git a/src/NzbDrone.Core/Download/Clients/DownloadStation/UsenetDownloadStation.cs b/src/NzbDrone.Core/Download/Clients/DownloadStation/UsenetDownloadStation.cs index 51b01adbf..54fd328e0 100644 --- a/src/NzbDrone.Core/Download/Clients/DownloadStation/UsenetDownloadStation.cs +++ b/src/NzbDrone.Core/Download/Clients/DownloadStation/UsenetDownloadStation.cs @@ -34,8 +34,7 @@ public UsenetDownloadStation(ISharedFolderResolver sharedFolderResolver, IDiskProvider diskProvider, IRemotePathMappingService remotePathMappingService, IValidateNzbs nzbValidationService, - Logger logger - ) + Logger logger) : base(httpClient, configService, diskProvider, remotePathMappingService, nzbValidationService, logger) { _dsInfoProxy = dsInfoProxy; @@ -197,7 +196,11 @@ protected override string AddFromNzbFile(RemoteEpisode remoteEpisode, string fil protected override void Test(List failures) { failures.AddIfNotNull(TestConnection()); - if (failures.HasErrors()) return; + if (failures.HasErrors()) + { + return; + } + failures.AddIfNotNull(TestOutputPath()); failures.AddIfNotNull(TestGetNZB()); } @@ -244,8 +247,9 @@ protected ValidationFailure TestOutputPath() return null; } - catch (DownloadClientAuthenticationException ex) // User could not have permission to access to downloadstation + catch (DownloadClientAuthenticationException ex) { + // User could not have permission to access to downloadstation _logger.Error(ex, ex.Message); return new NzbDroneValidationFailure(string.Empty, ex.Message); } @@ -281,6 +285,7 @@ protected ValidationFailure TestConnection() DetailedDescription = "Please verify the hostname and port." }; } + return new NzbDroneValidationFailure(string.Empty, "Unknown exception: " + ex.Message); } catch (Exception ex) diff --git a/src/NzbDrone.Core/Download/Clients/Hadouken/Hadouken.cs b/src/NzbDrone.Core/Download/Clients/Hadouken/Hadouken.cs index 3f37addca..d0f1cb479 100644 --- a/src/NzbDrone.Core/Download/Clients/Hadouken/Hadouken.cs +++ b/src/NzbDrone.Core/Download/Clients/Hadouken/Hadouken.cs @@ -64,7 +64,7 @@ public override IEnumerable GetItems() Title = torrent.Name, TotalSize = torrent.TotalSize, SeedRatio = torrent.DownloadedBytes <= 0 ? 0 : - (double) torrent.UploadedBytes / torrent.DownloadedBytes + (double)torrent.UploadedBytes / torrent.DownloadedBytes }; if (!string.IsNullOrEmpty(torrent.Error)) @@ -89,7 +89,7 @@ public override IEnumerable GetItems() item.Status = DownloadItemStatus.Downloading; } - item.CanMoveFiles = item.CanBeRemoved = (torrent.IsFinished && torrent.State == HadoukenTorrentState.Paused); + item.CanMoveFiles = item.CanBeRemoved = torrent.IsFinished && torrent.State == HadoukenTorrentState.Paused; items.Add(item); } @@ -130,7 +130,11 @@ public override DownloadClientInfo GetStatus() protected override void Test(List failures) { failures.AddIfNotNull(TestConnection()); - if (failures.HasErrors()) return; + if (failures.HasErrors()) + { + return; + } + failures.AddIfNotNull(TestGetTorrents()); } @@ -185,7 +189,7 @@ private ValidationFailure TestGetTorrents() catch (Exception ex) { _logger.Error(ex, ex.Message); - return new NzbDroneValidationFailure(String.Empty, "Failed to get the list of torrents: " + ex.Message); + return new NzbDroneValidationFailure(string.Empty, "Failed to get the list of torrents: " + ex.Message); } return null; diff --git a/src/NzbDrone.Core/Download/Clients/Hadouken/HadoukenProxy.cs b/src/NzbDrone.Core/Download/Clients/Hadouken/HadoukenProxy.cs index 1b34d4455..42fcede8f 100644 --- a/src/NzbDrone.Core/Download/Clients/Hadouken/HadoukenProxy.cs +++ b/src/NzbDrone.Core/Download/Clients/Hadouken/HadoukenProxy.cs @@ -38,7 +38,7 @@ public HadoukenSystemInfo GetSystemInfo(HadoukenSettings settings) public HadoukenTorrent[] GetTorrents(HadoukenSettings settings) { var result = ProcessRequest(settings, "webui.list"); - + return GetTorrents(result.Torrents); } @@ -151,7 +151,7 @@ private HadoukenTorrent MapTorrent(object[] item) SavePath = Convert.ToString(item[26]) }; } - catch(Exception ex) + catch (Exception ex) { _logger.Error(ex, "Failed to map Hadouken torrent data."); } diff --git a/src/NzbDrone.Core/Download/Clients/NzbVortex/NzbVortex.cs b/src/NzbDrone.Core/Download/Clients/NzbVortex/NzbVortex.cs index c47d819ca..64150f07f 100644 --- a/src/NzbDrone.Core/Download/Clients/NzbVortex/NzbVortex.cs +++ b/src/NzbDrone.Core/Download/Clients/NzbVortex/NzbVortex.cs @@ -9,8 +9,8 @@ using NzbDrone.Common.Http; using NzbDrone.Core.Configuration; using NzbDrone.Core.Parser.Model; -using NzbDrone.Core.Validation; using NzbDrone.Core.RemotePathMappings; +using NzbDrone.Core.Validation; namespace NzbDrone.Core.Download.Clients.NzbVortex { @@ -70,7 +70,9 @@ public override IEnumerable GetItems() { queueItem.Status = DownloadItemStatus.Paused; } - else switch (vortexQueueItem.State) + else + { + switch (vortexQueueItem.State) { case NzbVortexStateType.Waiting: queueItem.Status = DownloadItemStatus.Queued; @@ -87,6 +89,7 @@ public override IEnumerable GetItems() queueItem.Status = DownloadItemStatus.Downloading; break; } + } queueItem.OutputPath = GetOutputPath(vortexQueueItem, queueItem); @@ -115,7 +118,6 @@ public override void RemoveItem(DownloadClientItem item, bool deleteData) { _proxy.Remove(id, deleteData, Settings); } - else { var queue = _proxy.GetQueue(30, Settings); diff --git a/src/NzbDrone.Core/Download/Clients/NzbVortex/NzbVortexAuthenticationException.cs b/src/NzbDrone.Core/Download/Clients/NzbVortex/NzbVortexAuthenticationException.cs index 149829a0e..6922dd171 100644 --- a/src/NzbDrone.Core/Download/Clients/NzbVortex/NzbVortexAuthenticationException.cs +++ b/src/NzbDrone.Core/Download/Clients/NzbVortex/NzbVortexAuthenticationException.cs @@ -4,19 +4,23 @@ namespace NzbDrone.Core.Download.Clients.NzbVortex { public class NzbVortexAuthenticationException : DownloadClientException { - public NzbVortexAuthenticationException(string message, params object[] args) : base(message, args) + public NzbVortexAuthenticationException(string message, params object[] args) + : base(message, args) { } - public NzbVortexAuthenticationException(string message) : base(message) + public NzbVortexAuthenticationException(string message) + : base(message) { } - public NzbVortexAuthenticationException(string message, Exception innerException, params object[] args) : base(message, innerException, args) + public NzbVortexAuthenticationException(string message, Exception innerException, params object[] args) + : base(message, innerException, args) { } - public NzbVortexAuthenticationException(string message, Exception innerException) : base(message, innerException) + public NzbVortexAuthenticationException(string message, Exception innerException) + : base(message, innerException) { } } diff --git a/src/NzbDrone.Core/Download/Clients/NzbVortex/NzbVortexNotLoggedInException.cs b/src/NzbDrone.Core/Download/Clients/NzbVortex/NzbVortexNotLoggedInException.cs index 55b8271e6..90b3db938 100644 --- a/src/NzbDrone.Core/Download/Clients/NzbVortex/NzbVortexNotLoggedInException.cs +++ b/src/NzbDrone.Core/Download/Clients/NzbVortex/NzbVortexNotLoggedInException.cs @@ -4,23 +4,28 @@ namespace NzbDrone.Core.Download.Clients.NzbVortex { public class NzbVortexNotLoggedInException : DownloadClientException { - public NzbVortexNotLoggedInException() : this("Authentication is required") + public NzbVortexNotLoggedInException() + : this("Authentication is required") { } - public NzbVortexNotLoggedInException(string message, params object[] args) : base(message, args) + public NzbVortexNotLoggedInException(string message, params object[] args) + : base(message, args) { } - public NzbVortexNotLoggedInException(string message) : base(message) + public NzbVortexNotLoggedInException(string message) + : base(message) { } - public NzbVortexNotLoggedInException(string message, Exception innerException, params object[] args) : base(message, innerException, args) + public NzbVortexNotLoggedInException(string message, Exception innerException, params object[] args) + : base(message, innerException, args) { } - public NzbVortexNotLoggedInException(string message, Exception innerException) : base(message, innerException) + public NzbVortexNotLoggedInException(string message, Exception innerException) + : base(message, innerException) { } } diff --git a/src/NzbDrone.Core/Download/Clients/NzbVortex/NzbVortexPriority.cs b/src/NzbDrone.Core/Download/Clients/NzbVortex/NzbVortexPriority.cs index eb24f9afa..44e18b54e 100644 --- a/src/NzbDrone.Core/Download/Clients/NzbVortex/NzbVortexPriority.cs +++ b/src/NzbDrone.Core/Download/Clients/NzbVortex/NzbVortexPriority.cs @@ -6,4 +6,4 @@ public enum NzbVortexPriority Normal = 0, High = 1, } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Download/Clients/NzbVortex/NzbVortexProxy.cs b/src/NzbDrone.Core/Download/Clients/NzbVortex/NzbVortexProxy.cs index 299fa7f9d..3b7187a63 100644 --- a/src/NzbDrone.Core/Download/Clients/NzbVortex/NzbVortexProxy.cs +++ b/src/NzbDrone.Core/Download/Clients/NzbVortex/NzbVortexProxy.cs @@ -42,12 +42,12 @@ public string DownloadNzb(byte[] nzbData, string filename, int priority, NzbVort var requestBuilder = BuildRequest(settings).Resource("nzb/add") .Post() .AddQueryParam("priority", priority.ToString()); - + if (settings.TvCategory.IsNotNullOrWhiteSpace()) { requestBuilder.AddQueryParam("groupname", settings.TvCategory); } - + requestBuilder.AddFormUpload("name", filename, nzbData, "application/x-nzb"); var response = ProcessRequest(requestBuilder, true, settings); @@ -91,7 +91,6 @@ public List GetGroups(NzbVortexSettings settings) public List GetQueue(int doneLimit, NzbVortexSettings settings) { var requestBuilder = BuildRequest(settings).Resource("nzb"); - if (settings.TvCategory.IsNotNullOrWhiteSpace()) { @@ -113,7 +112,7 @@ public List GetFiles(int id, NzbVortexSettings settings) return response.Files; } - + private HttpRequestBuilder BuildRequest(NzbVortexSettings settings) { var baseUrl = HttpRequestBuilder.BuildBaseUrl(true, settings.Host, settings.Port, settings.UrlBase); diff --git a/src/NzbDrone.Core/Download/Clients/Nzbget/Nzbget.cs b/src/NzbDrone.Core/Download/Clients/Nzbget/Nzbget.cs index 7a46c0a31..929aba342 100644 --- a/src/NzbDrone.Core/Download/Clients/Nzbget/Nzbget.cs +++ b/src/NzbDrone.Core/Download/Clients/Nzbget/Nzbget.cs @@ -75,7 +75,7 @@ private IEnumerable GetQueue() queueItem.CanMoveFiles = true; queueItem.CanBeRemoved = true; - if (globalStatus.DownloadPaused || remainingSize == pausedSize && remainingSize != 0) + if (globalStatus.DownloadPaused || (remainingSize == pausedSize && remainingSize != 0)) { queueItem.Status = DownloadItemStatus.Paused; queueItem.RemainingSize = remainingSize; @@ -226,7 +226,10 @@ protected IEnumerable GetCategories(Dictionary c { var name = config.GetValueOrDefault("Category" + i + ".Name"); - if (name == null) yield break; + if (name == null) + { + yield break; + } var destDir = config.GetValueOrDefault("Category" + i + ".DestDir"); @@ -276,6 +279,7 @@ private ValidationFailure TestConnection() { return new ValidationFailure("Username", "Authentication failed"); } + _logger.Error(ex, "Unable to connect to NZBGet"); return new ValidationFailure("Host", "Unable to connect to NZBGet"); } diff --git a/src/NzbDrone.Core/Download/Clients/Nzbget/NzbgetProxy.cs b/src/NzbDrone.Core/Download/Clients/Nzbget/NzbgetProxy.cs index 89fc35049..30c874656 100644 --- a/src/NzbDrone.Core/Download/Clients/Nzbget/NzbgetProxy.cs +++ b/src/NzbDrone.Core/Download/Clients/Nzbget/NzbgetProxy.cs @@ -1,11 +1,11 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Net; using NLog; +using NzbDrone.Common.Cache; using NzbDrone.Common.Http; using NzbDrone.Common.Serializer; -using System.Net; -using NzbDrone.Common.Cache; namespace NzbDrone.Core.Download.Clients.Nzbget { @@ -102,6 +102,7 @@ private string DownloadNzbLegacy13(byte[] nzbData, string title, string category return droneId; } + private string DownloadNzbLegacy12(byte[] nzbData, string title, string category, int priority, NzbgetSettings settings) { var response = ProcessRequest(settings, "append", title, category, priority, false, nzbData); @@ -158,7 +159,6 @@ public Dictionary GetConfig(NzbgetSettings settings) return ProcessRequest>(settings, "config").ToDictionary(v => v.Name, v => v.Value); } - public void RemoveItem(string id, NzbgetSettings settings) { var queue = GetQueue(settings); @@ -187,7 +187,6 @@ public void RemoveItem(string id, NzbgetSettings settings) _logger.Warn("Failed to remove item from nzbget queue, {0} [{1}]", queueItem.NzbName, queueItem.NzbId); } } - else if (historyItem != null) { if (!EditQueue("HistoryDelete", 0, "", historyItem.Id, settings)) @@ -195,7 +194,6 @@ public void RemoveItem(string id, NzbgetSettings settings) _logger.Warn("Failed to remove item from nzbget history, {0} [{1}]", historyItem.Name, historyItem.Id); } } - else { _logger.Warn("Unable to remove item from nzbget, Unknown ID: {0}", id); diff --git a/src/NzbDrone.Core/Download/Clients/Nzbget/NzbgetResponse.cs b/src/NzbDrone.Core/Download/Clients/Nzbget/NzbgetResponse.cs index f1546593e..adec59ebc 100644 --- a/src/NzbDrone.Core/Download/Clients/Nzbget/NzbgetResponse.cs +++ b/src/NzbDrone.Core/Download/Clients/Nzbget/NzbgetResponse.cs @@ -5,6 +5,5 @@ public class NzbgetResponse public string Version { get; set; } public T Result { get; set; } - } } diff --git a/src/NzbDrone.Core/Download/Clients/Pneumatic/Pneumatic.cs b/src/NzbDrone.Core/Download/Clients/Pneumatic/Pneumatic.cs index 97730ee74..de3ab59e9 100644 --- a/src/NzbDrone.Core/Download/Clients/Pneumatic/Pneumatic.cs +++ b/src/NzbDrone.Core/Download/Clients/Pneumatic/Pneumatic.cs @@ -8,9 +8,9 @@ using NzbDrone.Common.Http; using NzbDrone.Core.Configuration; using NzbDrone.Core.Indexers; -using NzbDrone.Core.RemotePathMappings; using NzbDrone.Core.Organizer; using NzbDrone.Core.Parser.Model; +using NzbDrone.Core.RemotePathMappings; namespace NzbDrone.Core.Download.Clients.Pneumatic { @@ -54,7 +54,6 @@ public override string Download(RemoteEpisode remoteEpisode) var strmFile = WriteStrmFile(title, nzbFile); - return GetDownloadClientId(strmFile); } diff --git a/src/NzbDrone.Core/Download/Clients/QBittorrent/QBittorrent.cs b/src/NzbDrone.Core/Download/Clients/QBittorrent/QBittorrent.cs index 02f9a8543..60dae33c6 100644 --- a/src/NzbDrone.Core/Download/Clients/QBittorrent/QBittorrent.cs +++ b/src/NzbDrone.Core/Download/Clients/QBittorrent/QBittorrent.cs @@ -1,6 +1,6 @@ using System; -using System.Linq; using System.Collections.Generic; +using System.Linq; using System.Net; using FluentValidation.Results; using NLog; @@ -10,9 +10,9 @@ using NzbDrone.Common.Http; using NzbDrone.Core.Configuration; using NzbDrone.Core.MediaFiles.TorrentInfo; -using NzbDrone.Core.Validation; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.RemotePathMappings; +using NzbDrone.Core.Validation; namespace NzbDrone.Core.Download.Clients.QBittorrent { @@ -58,7 +58,8 @@ public override void MarkItemAsImported(DownloadClientItem downloadClientItem) catch (DownloadClientException) { _logger.Warn("Failed to set post-import torrent label \"{0}\" for {1} in qBittorrent. Does the label exist?", - Settings.TvImportedCategory, downloadClientItem.Title); + Settings.TvImportedCategory, + downloadClientItem.Title); } } } @@ -73,14 +74,13 @@ protected override string AddFromMagnetLink(RemoteEpisode remoteEpisode, string var setShareLimits = remoteEpisode.SeedConfiguration != null && (remoteEpisode.SeedConfiguration.Ratio.HasValue || remoteEpisode.SeedConfiguration.SeedTime.HasValue); var addHasSetShareLimits = setShareLimits && ProxyApiVersion >= new Version(2, 8, 1); var isRecentEpisode = remoteEpisode.IsRecentEpisode(); - var moveToTop = (isRecentEpisode && Settings.RecentTvPriority == (int)QBittorrentPriority.First || !isRecentEpisode && Settings.OlderTvPriority == (int)QBittorrentPriority.First); + var moveToTop = (isRecentEpisode && Settings.RecentTvPriority == (int)QBittorrentPriority.First) || (!isRecentEpisode && Settings.OlderTvPriority == (int)QBittorrentPriority.First); var forceStart = (QBittorrentState)Settings.InitialState == QBittorrentState.ForceStart; Proxy.AddTorrentFromUrl(magnetLink, addHasSetShareLimits && setShareLimits ? remoteEpisode.SeedConfiguration : null, Settings); - if (!addHasSetShareLimits && setShareLimits || moveToTop || forceStart) + if ((!addHasSetShareLimits && setShareLimits) || moveToTop || forceStart) { - if (!WaitForTorrent(hash)) { return hash; @@ -126,19 +126,18 @@ protected override string AddFromMagnetLink(RemoteEpisode remoteEpisode, string return hash; } - protected override string AddFromTorrentFile(RemoteEpisode remoteEpisode, string hash, string filename, Byte[] fileContent) + protected override string AddFromTorrentFile(RemoteEpisode remoteEpisode, string hash, string filename, byte[] fileContent) { var setShareLimits = remoteEpisode.SeedConfiguration != null && (remoteEpisode.SeedConfiguration.Ratio.HasValue || remoteEpisode.SeedConfiguration.SeedTime.HasValue); var addHasSetShareLimits = setShareLimits && ProxyApiVersion >= new Version(2, 8, 1); var isRecentEpisode = remoteEpisode.IsRecentEpisode(); - var moveToTop = (isRecentEpisode && Settings.RecentTvPriority == (int)QBittorrentPriority.First || !isRecentEpisode && Settings.OlderTvPriority == (int)QBittorrentPriority.First); + var moveToTop = (isRecentEpisode && Settings.RecentTvPriority == (int)QBittorrentPriority.First) || (!isRecentEpisode && Settings.OlderTvPriority == (int)QBittorrentPriority.First); var forceStart = (QBittorrentState)Settings.InitialState == QBittorrentState.ForceStart; Proxy.AddTorrentFromFile(filename, fileContent, addHasSetShareLimits ? remoteEpisode.SeedConfiguration : null, Settings); - if (!addHasSetShareLimits && setShareLimits || moveToTop || forceStart) + if ((!addHasSetShareLimits && setShareLimits) || moveToTop || forceStart) { - if (!WaitForTorrent(hash)) { return hash; @@ -236,7 +235,7 @@ public override IEnumerable GetItems() // Avoid removing torrents that haven't reached the global max ratio. // Removal also requires the torrent to be paused, in case a higher max ratio was set on the torrent itself (which is not exposed by the api). - item.CanMoveFiles = item.CanBeRemoved = (torrent.State == "pausedUP" && HasReachedSeedLimit(torrent, config)); + item.CanMoveFiles = item.CanBeRemoved = torrent.State == "pausedUP" && HasReachedSeedLimit(torrent, config); switch (torrent.State) { @@ -284,6 +283,7 @@ public override IEnumerable GetItems() item.Status = DownloadItemStatus.Warning; item.Message = "qBittorrent cannot resolve magnet link with DHT disabled"; } + break; case "forcedDL": // torrent is being downloaded, and was forced started @@ -374,7 +374,11 @@ public override DownloadClientInfo GetStatus() protected override void Test(List failures) { failures.AddIfNotNull(TestConnection()); - if (failures.HasErrors()) return; + if (failures.HasErrors()) + { + return; + } + failures.AddIfNotNull(TestCategory()); failures.AddIfNotNull(TestPrioritySupport()); failures.AddIfNotNull(TestGetTorrents()); @@ -418,7 +422,7 @@ private ValidationFailure TestConnection() var config = Proxy.GetConfig(Settings); if ((config.MaxRatioEnabled || config.MaxSeedingTimeEnabled) && (config.MaxRatioAction == QBittorrentMaxRatioAction.Remove || config.MaxRatioAction == QBittorrentMaxRatioAction.DeleteFiles)) { - return new NzbDroneValidationFailure(String.Empty, "qBittorrent is configured to remove torrents when they reach their Share Ratio Limit") + return new NzbDroneValidationFailure(string.Empty, "qBittorrent is configured to remove torrents when they reach their Share Ratio Limit") { DetailedDescription = "Sonarr will be unable to perform Completed Download Handling as configured. You can fix this in qBittorrent ('Tools -> Options...' in the menu) by changing 'Options -> BitTorrent -> Share Ratio Limiting' from 'Remove them' to 'Pause them'." }; @@ -442,7 +446,8 @@ private ValidationFailure TestConnection() DetailedDescription = "Please verify the hostname and port." }; } - return new NzbDroneValidationFailure(String.Empty, "Unknown exception: " + ex.Message); + + return new NzbDroneValidationFailure(string.Empty, "Unknown exception: " + ex.Message); } catch (Exception ex) { @@ -533,7 +538,7 @@ private ValidationFailure TestPrioritySupport() catch (Exception ex) { _logger.Error(ex, "Failed to test qBittorrent"); - return new NzbDroneValidationFailure(String.Empty, "Unknown exception: " + ex.Message); + return new NzbDroneValidationFailure(string.Empty, "Unknown exception: " + ex.Message); } return null; @@ -548,7 +553,7 @@ private ValidationFailure TestGetTorrents() catch (Exception ex) { _logger.Error(ex, "Failed to get torrents"); - return new NzbDroneValidationFailure(String.Empty, "Failed to get the list of torrents: " + ex.Message); + return new NzbDroneValidationFailure(string.Empty, "Failed to get the list of torrents: " + ex.Message); } return null; @@ -574,15 +579,23 @@ protected bool HasReachedSeedLimit(QBittorrentTorrent torrent, QBittorrentPrefer { if (torrent.RatioLimit >= 0) { - if (torrent.Ratio >= torrent.RatioLimit) return true; + if (torrent.Ratio >= torrent.RatioLimit) + { + return true; + } } else if (torrent.RatioLimit == -2 && config.MaxRatioEnabled) { - if (torrent.Ratio >= config.MaxRatio) return true; + if (torrent.Ratio >= config.MaxRatio) + { + return true; + } } - if (HasReachedSeedingTimeLimit(torrent, config)) return true; - + if (HasReachedSeedingTimeLimit(torrent, config)) + { + return true; + } return false; } diff --git a/src/NzbDrone.Core/Download/Clients/QBittorrent/QBittorrentProxySelector.cs b/src/NzbDrone.Core/Download/Clients/QBittorrent/QBittorrentProxySelector.cs index 6b175c027..c8bfe31cb 100644 --- a/src/NzbDrone.Core/Download/Clients/QBittorrent/QBittorrentProxySelector.cs +++ b/src/NzbDrone.Core/Download/Clients/QBittorrent/QBittorrentProxySelector.cs @@ -6,7 +6,6 @@ using NzbDrone.Common.Http; - namespace NzbDrone.Core.Download.Clients.QBittorrent { public interface IQBittorrentProxy @@ -21,9 +20,9 @@ public interface IQBittorrentProxy List GetTorrentFiles(string hash, QBittorrentSettings settings); void AddTorrentFromUrl(string torrentUrl, TorrentSeedConfiguration seedConfiguration, QBittorrentSettings settings); - void AddTorrentFromFile(string fileName, Byte[] fileContent, TorrentSeedConfiguration seedConfiguration, QBittorrentSettings settings); + void AddTorrentFromFile(string fileName, byte[] fileContent, TorrentSeedConfiguration seedConfiguration, QBittorrentSettings settings); - void RemoveTorrent(string hash, Boolean removeData, QBittorrentSettings settings); + void RemoveTorrent(string hash, bool removeData, QBittorrentSettings settings); void SetTorrentLabel(string hash, string label, QBittorrentSettings settings); void AddLabel(string label, QBittorrentSettings settings); Dictionary GetLabels(QBittorrentSettings settings); diff --git a/src/NzbDrone.Core/Download/Clients/QBittorrent/QBittorrentProxyV1.cs b/src/NzbDrone.Core/Download/Clients/QBittorrent/QBittorrentProxyV1.cs index 4bb25d602..6cc87bfb6 100644 --- a/src/NzbDrone.Core/Download/Clients/QBittorrent/QBittorrentProxyV1.cs +++ b/src/NzbDrone.Core/Download/Clients/QBittorrent/QBittorrentProxyV1.cs @@ -22,7 +22,6 @@ public QBittorrentProxyV1(IHttpClient httpClient, ICacheManager cacheManager, Lo _httpClient = httpClient; _logger = logger; _authCookieCache = cacheManager.GetCache>(GetType(), "authCookies"); - } public bool IsApiSupported(QBittorrentSettings settings) @@ -93,6 +92,7 @@ public List GetTorrents(QBittorrentSettings settings) request.AddQueryParam("label", settings.TvCategory); request.AddQueryParam("category", settings.TvCategory); } + var response = ProcessRequest>(request, settings); return response; @@ -161,7 +161,7 @@ public void AddTorrentFromUrl(string torrentUrl, TorrentSeedConfiguration seedCo } } - public void AddTorrentFromFile(string fileName, Byte[] fileContent, TorrentSeedConfiguration seedConfiguration, QBittorrentSettings settings) + public void AddTorrentFromFile(string fileName, byte[] fileContent, TorrentSeedConfiguration seedConfiguration, QBittorrentSettings settings) { var request = BuildRequest(settings).Resource("/command/upload") .Post() @@ -191,7 +191,7 @@ public void AddTorrentFromFile(string fileName, Byte[] fileContent, TorrentSeedC } } - public void RemoveTorrent(string hash, Boolean removeData, QBittorrentSettings settings) + public void RemoveTorrent(string hash, bool removeData, QBittorrentSettings settings) { var request = BuildRequest(settings).Resource(removeData ? "/command/deletePerm" : "/command/delete") .Post() @@ -262,7 +262,6 @@ public void MoveTorrentToTopInQueue(string hash, QBittorrentSettings settings) throw; } - } public void PauseTorrent(string hash, QBittorrentSettings settings) @@ -359,7 +358,7 @@ private void AuthenticateClient(HttpRequestBuilder requestBuilder, QBittorrentSe { _authCookieCache.Remove(authKey); - var authLoginRequest = BuildRequest(settings).Resource( "/login") + var authLoginRequest = BuildRequest(settings).Resource("/login") .Post() .AddFormParameter("username", settings.Username ?? string.Empty) .AddFormParameter("password", settings.Password ?? string.Empty) @@ -385,8 +384,9 @@ private void AuthenticateClient(HttpRequestBuilder requestBuilder, QBittorrentSe throw new DownloadClientUnavailableException("Failed to connect to qBittorrent, please check your settings.", ex); } - if (response.Content != "Ok.") // returns "Fails." on bad login + if (response.Content != "Ok.") { + // returns "Fails." on bad login _logger.Debug("qbitTorrent authentication failed."); throw new DownloadClientAuthenticationException("Failed to authenticate with qBittorrent."); } diff --git a/src/NzbDrone.Core/Download/Clients/QBittorrent/QBittorrentProxyV2.cs b/src/NzbDrone.Core/Download/Clients/QBittorrent/QBittorrentProxyV2.cs index f25ba291d..e1ea0aa93 100644 --- a/src/NzbDrone.Core/Download/Clients/QBittorrent/QBittorrentProxyV2.cs +++ b/src/NzbDrone.Core/Download/Clients/QBittorrent/QBittorrentProxyV2.cs @@ -96,6 +96,7 @@ public List GetTorrents(QBittorrentSettings settings) { request.AddQueryParam("category", settings.TvCategory); } + var response = ProcessRequest>(request, settings); return response; @@ -159,7 +160,7 @@ public void AddTorrentFromUrl(string torrentUrl, TorrentSeedConfiguration seedCo } } - public void AddTorrentFromFile(string fileName, Byte[] fileContent, TorrentSeedConfiguration seedConfiguration, QBittorrentSettings settings) + public void AddTorrentFromFile(string fileName, byte[] fileContent, TorrentSeedConfiguration seedConfiguration, QBittorrentSettings settings) { var request = BuildRequest(settings).Resource("/api/v2/torrents/add") .Post() @@ -181,7 +182,7 @@ public void AddTorrentFromFile(string fileName, Byte[] fileContent, TorrentSeedC } } - public void RemoveTorrent(string hash, Boolean removeData, QBittorrentSettings settings) + public void RemoveTorrent(string hash, bool removeData, QBittorrentSettings settings) { var request = BuildRequest(settings).Resource("/api/v2/torrents/delete") .Post() @@ -306,7 +307,6 @@ public void MoveTorrentToTopInQueue(string hash, QBittorrentSettings settings) throw; } - } public void PauseTorrent(string hash, QBittorrentSettings settings) @@ -396,6 +396,7 @@ private void AuthenticateClient(HttpRequestBuilder requestBuilder, QBittorrentSe { throw new DownloadClientAuthenticationException("Failed to authenticate with qBittorrent."); } + return; } @@ -433,8 +434,9 @@ private void AuthenticateClient(HttpRequestBuilder requestBuilder, QBittorrentSe throw new DownloadClientUnavailableException("Failed to connect to qBittorrent, please check your settings.", ex); } - if (response.Content != "Ok.") // returns "Fails." on bad login + if (response.Content != "Ok.") { + // returns "Fails." on bad login _logger.Debug("qbitTorrent authentication failed."); throw new DownloadClientAuthenticationException("Failed to authenticate with qBittorrent."); } diff --git a/src/NzbDrone.Core/Download/Clients/Sabnzbd/JsonConverters/SabnzbdPriorityTypeConverter.cs b/src/NzbDrone.Core/Download/Clients/Sabnzbd/JsonConverters/SabnzbdPriorityTypeConverter.cs index 17557abcc..246b5b558 100644 --- a/src/NzbDrone.Core/Download/Clients/Sabnzbd/JsonConverters/SabnzbdPriorityTypeConverter.cs +++ b/src/NzbDrone.Core/Download/Clients/Sabnzbd/JsonConverters/SabnzbdPriorityTypeConverter.cs @@ -8,7 +8,7 @@ public class SabnzbdPriorityTypeConverter : JsonConverter public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { var priorityType = (SabnzbdPriority)value; - writer.WriteValue(priorityType.ToString()); + writer.WriteValue(priorityType.ToString()); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) diff --git a/src/NzbDrone.Core/Download/Clients/Sabnzbd/JsonConverters/SabnzbdQueueTimeConverter.cs b/src/NzbDrone.Core/Download/Clients/Sabnzbd/JsonConverters/SabnzbdQueueTimeConverter.cs index c5274efb1..10efa12b2 100644 --- a/src/NzbDrone.Core/Download/Clients/Sabnzbd/JsonConverters/SabnzbdQueueTimeConverter.cs +++ b/src/NzbDrone.Core/Download/Clients/Sabnzbd/JsonConverters/SabnzbdQueueTimeConverter.cs @@ -9,7 +9,7 @@ public class SabnzbdQueueTimeConverter : JsonConverter public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { var ts = (TimeSpan)value; - writer.WriteValue(ts.ToString()); + writer.WriteValue(ts.ToString()); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) @@ -19,7 +19,7 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist switch (split.Count()) { case 4: - return new TimeSpan(split[0] * 24 + split[1], split[2], split[3]); + return new TimeSpan((split[0] * 24) + split[1], split[2], split[3]); case 3: return new TimeSpan(split[0], split[1], split[2]); default: diff --git a/src/NzbDrone.Core/Download/Clients/Sabnzbd/Sabnzbd.cs b/src/NzbDrone.Core/Download/Clients/Sabnzbd/Sabnzbd.cs index 8f8fbf5c0..3c1056385 100644 --- a/src/NzbDrone.Core/Download/Clients/Sabnzbd/Sabnzbd.cs +++ b/src/NzbDrone.Core/Download/Clients/Sabnzbd/Sabnzbd.cs @@ -11,8 +11,8 @@ using NzbDrone.Core.Configuration; using NzbDrone.Core.Exceptions; using NzbDrone.Core.Parser.Model; -using NzbDrone.Core.Validation; using NzbDrone.Core.RemotePathMappings; +using NzbDrone.Core.Validation; namespace NzbDrone.Core.Download.Clients.Sabnzbd { @@ -149,8 +149,9 @@ private IEnumerable GetHistory() { historyItem.Status = DownloadItemStatus.Completed; } - else // Verifying/Moving etc + else { + // Verifying/Moving etc historyItem.Status = DownloadItemStatus.Downloading; } @@ -167,11 +168,11 @@ private IEnumerable GetHistory() { historyItem.OutputPath = parent; } + parent = parent.Directory; } } - historyItems.Add(historyItem); } @@ -184,7 +185,7 @@ public override IEnumerable GetItems() { foreach (var downloadClientItem in GetQueue().Concat(GetHistory())) { - if (downloadClientItem.Category == Settings.TvCategory || downloadClientItem.Category == "*" && Settings.TvCategory.IsNullOrWhiteSpace()) + if (downloadClientItem.Category == Settings.TvCategory || (downloadClientItem.Category == "*" && Settings.TvCategory.IsNullOrWhiteSpace())) { yield return downloadClientItem; } @@ -332,7 +333,6 @@ private Version ParseVersion(string version) minor = Convert.ToInt32(parsed.Groups["minor"].Value); patch = Convert.ToInt32(parsed.Groups["patch"].Value.Replace("x", "0")); } - else { if (!version.Equals("develop", StringComparison.InvariantCultureIgnoreCase)) @@ -403,10 +403,12 @@ private ValidationFailure TestAuthentication() { return new ValidationFailure("APIKey", "API Key Incorrect"); } + if (ex.Message.ContainsIgnoreCase("API Key Required")) { return new ValidationFailure("APIKey", "API Key Required"); } + throw; } @@ -455,6 +457,7 @@ private ValidationFailure TestCategory() }; } } + if (config.Misc.enable_tv_sorting && ContainsCategory(config.Misc.tv_categories, Settings.TvCategory)) { return new NzbDroneValidationFailure("TvCategory", "Disable TV Sorting") @@ -463,6 +466,7 @@ private ValidationFailure TestCategory() DetailedDescription = "You must disable Sabnzbd TV Sorting for the category Sonarr uses to prevent import issues. Go to Sabnzbd to fix it." }; } + if (config.Misc.enable_movie_sorting && ContainsCategory(config.Misc.movie_categories, Settings.TvCategory)) { return new NzbDroneValidationFailure("TvCategory", "Disable Movie Sorting") @@ -471,6 +475,7 @@ private ValidationFailure TestCategory() DetailedDescription = "You must disable Sabnzbd Movie Sorting for the category Sonarr uses to prevent import issues. Go to Sabnzbd to fix it." }; } + if (config.Misc.enable_date_sorting && ContainsCategory(config.Misc.date_categories, Settings.TvCategory)) { return new NzbDroneValidationFailure("TvCategory", "Disable Date Sorting") diff --git a/src/NzbDrone.Core/Download/Clients/Sabnzbd/SabnzbdPriority.cs b/src/NzbDrone.Core/Download/Clients/Sabnzbd/SabnzbdPriority.cs index b769a78db..905aea6c0 100644 --- a/src/NzbDrone.Core/Download/Clients/Sabnzbd/SabnzbdPriority.cs +++ b/src/NzbDrone.Core/Download/Clients/Sabnzbd/SabnzbdPriority.cs @@ -9,4 +9,4 @@ public enum SabnzbdPriority High = 1, Force = 2 } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Download/Clients/Sabnzbd/SabnzbdProxy.cs b/src/NzbDrone.Core/Download/Clients/Sabnzbd/SabnzbdProxy.cs index 53a1b9979..6cee2a4d1 100644 --- a/src/NzbDrone.Core/Download/Clients/Sabnzbd/SabnzbdProxy.cs +++ b/src/NzbDrone.Core/Download/Clients/Sabnzbd/SabnzbdProxy.cs @@ -1,11 +1,11 @@ using System; +using System.Net; using Newtonsoft.Json.Linq; using NLog; using NzbDrone.Common.Extensions; +using NzbDrone.Common.Http; using NzbDrone.Common.Serializer; using NzbDrone.Core.Download.Clients.Sabnzbd.Responses; -using NzbDrone.Common.Http; -using System.Net; namespace NzbDrone.Core.Download.Clients.Sabnzbd { @@ -13,7 +13,7 @@ public interface ISabnzbdProxy { string GetBaseUrl(SabnzbdSettings settings, string relativePath = null); SabnzbdAddResponse DownloadNzb(byte[] nzbData, string filename, string category, int priority, SabnzbdSettings settings); - void RemoveFrom(string source, string id,bool deleteData, SabnzbdSettings settings); + void RemoveFrom(string source, string id, bool deleteData, SabnzbdSettings settings); string GetVersion(SabnzbdSettings settings); SabnzbdConfig GetConfig(SabnzbdSettings settings); SabnzbdFullStatus GetFullStatus(SabnzbdSettings settings); @@ -166,6 +166,7 @@ private HttpRequestBuilder BuildRequest(string mode, SabnzbdSettings settings) requestBuilder.AddSuffixQueryParam("ma_username", settings.Username); requestBuilder.AddSuffixQueryParam("ma_password", settings.Password); } + requestBuilder.AddSuffixQueryParam("output", "json"); return requestBuilder; @@ -216,7 +217,6 @@ private void CheckForError(HttpResponse response) result.Status = "false"; result.Error = response.Content.Replace("error: ", ""); } - else { result.Status = "true"; diff --git a/src/NzbDrone.Core/Download/Clients/Transmission/Transmission.cs b/src/NzbDrone.Core/Download/Clients/Transmission/Transmission.cs index 058023d0c..369b9f961 100644 --- a/src/NzbDrone.Core/Download/Clients/Transmission/Transmission.cs +++ b/src/NzbDrone.Core/Download/Clients/Transmission/Transmission.cs @@ -1,10 +1,10 @@ using System; using System.Text.RegularExpressions; +using FluentValidation.Results; +using NLog; using NzbDrone.Common.Disk; using NzbDrone.Common.Http; using NzbDrone.Core.Configuration; -using NLog; -using FluentValidation.Results; using NzbDrone.Core.MediaFiles.TorrentInfo; using NzbDrone.Core.RemotePathMappings; diff --git a/src/NzbDrone.Core/Download/Clients/Transmission/TransmissionBase.cs b/src/NzbDrone.Core/Download/Clients/Transmission/TransmissionBase.cs index 2888c96a2..3d8dab109 100644 --- a/src/NzbDrone.Core/Download/Clients/Transmission/TransmissionBase.cs +++ b/src/NzbDrone.Core/Download/Clients/Transmission/TransmissionBase.cs @@ -40,18 +40,27 @@ public override IEnumerable GetItems() foreach (var torrent in torrents) { // If totalsize == 0 the torrent is a magnet downloading metadata - if (torrent.TotalSize == 0) continue; + if (torrent.TotalSize == 0) + { + continue; + } var outputPath = new OsPath(torrent.DownloadDir); if (Settings.TvDirectory.IsNotNullOrWhiteSpace()) { - if (!new OsPath(Settings.TvDirectory).Contains(outputPath)) continue; + if (!new OsPath(Settings.TvDirectory).Contains(outputPath)) + { + continue; + } } else if (Settings.TvCategory.IsNotNullOrWhiteSpace()) { var directories = outputPath.FullPath.Split('\\', '/'); - if (!directories.Contains(Settings.TvCategory)) continue; + if (!directories.Contains(Settings.TvCategory)) + { + continue; + } } outputPath = _remotePathMappingService.RemapRemoteToLocal(Settings.Host, outputPath); @@ -67,7 +76,7 @@ public override IEnumerable GetItems() item.TotalSize = torrent.TotalSize; item.RemainingSize = torrent.LeftUntilDone; item.SeedRatio = torrent.DownloadedEver <= 0 ? 0 : - (double) torrent.UploadedEver / torrent.DownloadedEver; + (double)torrent.UploadedEver / torrent.DownloadedEver; if (torrent.Eta >= 0) { @@ -112,7 +121,7 @@ protected bool HasReachedSeedLimit(TransmissionTorrent torrent, double? ratio, L { var isStopped = torrent.Status == TransmissionTorrentStatus.Stopped; var isSeeding = torrent.Status == TransmissionTorrentStatus.Seeding; - + if (torrent.SeedRatioMode == 1) { if (isStopped && ratio.HasValue && ratio >= torrent.SeedRatioLimit) @@ -177,8 +186,8 @@ protected override string AddFromMagnetLink(RemoteEpisode remoteEpisode, string var isRecentEpisode = remoteEpisode.IsRecentEpisode(); - if (isRecentEpisode && Settings.RecentTvPriority == (int)TransmissionPriority.First || - !isRecentEpisode && Settings.OlderTvPriority == (int)TransmissionPriority.First) + if ((isRecentEpisode && Settings.RecentTvPriority == (int)TransmissionPriority.First) || + (!isRecentEpisode && Settings.OlderTvPriority == (int)TransmissionPriority.First)) { _proxy.MoveTorrentToTopInQueue(hash, Settings); } @@ -193,8 +202,8 @@ protected override string AddFromTorrentFile(RemoteEpisode remoteEpisode, string var isRecentEpisode = remoteEpisode.IsRecentEpisode(); - if (isRecentEpisode && Settings.RecentTvPriority == (int)TransmissionPriority.First || - !isRecentEpisode && Settings.OlderTvPriority == (int)TransmissionPriority.First) + if ((isRecentEpisode && Settings.RecentTvPriority == (int)TransmissionPriority.First) || + (!isRecentEpisode && Settings.OlderTvPriority == (int)TransmissionPriority.First)) { _proxy.MoveTorrentToTopInQueue(hash, Settings); } @@ -205,7 +214,11 @@ protected override string AddFromTorrentFile(RemoteEpisode remoteEpisode, string protected override void Test(List failures) { failures.AddIfNotNull(TestConnection()); - if (failures.HasErrors()) return; + if (failures.HasErrors()) + { + return; + } + failures.AddIfNotNull(TestGetTorrents()); } @@ -221,7 +234,10 @@ protected string GetDownloadDirectory() return Settings.TvDirectory; } - if (!Settings.TvCategory.IsNotNullOrWhiteSpace()) return null; + if (!Settings.TvCategory.IsNotNullOrWhiteSpace()) + { + return null; + } var config = _proxy.GetConfig(Settings); var destDir = config.DownloadDir; diff --git a/src/NzbDrone.Core/Download/Clients/Transmission/TransmissionException.cs b/src/NzbDrone.Core/Download/Clients/Transmission/TransmissionException.cs index f89ee42da..3b91b4ce3 100644 --- a/src/NzbDrone.Core/Download/Clients/Transmission/TransmissionException.cs +++ b/src/NzbDrone.Core/Download/Clients/Transmission/TransmissionException.cs @@ -5,7 +5,6 @@ public class TransmissionException : DownloadClientException public TransmissionException(string message) : base(message) { - } } } diff --git a/src/NzbDrone.Core/Download/Clients/Transmission/TransmissionPriority.cs b/src/NzbDrone.Core/Download/Clients/Transmission/TransmissionPriority.cs index e5152bea6..1cf99c501 100644 --- a/src/NzbDrone.Core/Download/Clients/Transmission/TransmissionPriority.cs +++ b/src/NzbDrone.Core/Download/Clients/Transmission/TransmissionPriority.cs @@ -5,4 +5,4 @@ public enum TransmissionPriority Last = 0, First = 1 } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Download/Clients/Transmission/TransmissionProxy.cs b/src/NzbDrone.Core/Download/Clients/Transmission/TransmissionProxy.cs index 2d3aaa03a..63d3784c3 100644 --- a/src/NzbDrone.Core/Download/Clients/Transmission/TransmissionProxy.cs +++ b/src/NzbDrone.Core/Download/Clients/Transmission/TransmissionProxy.cs @@ -1,11 +1,11 @@ using System; -using System.Net; using System.Collections.Generic; -using NzbDrone.Common.Extensions; -using NLog; +using System.Net; using Newtonsoft.Json.Linq; -using NzbDrone.Common.Http; +using NLog; using NzbDrone.Common.Cache; +using NzbDrone.Common.Extensions; +using NzbDrone.Common.Http; using NzbDrone.Common.Serializer; namespace NzbDrone.Core.Download.Clients.Transmission @@ -23,7 +23,7 @@ public interface ITransmissionProxy void MoveTorrentToTopInQueue(string hashString, TransmissionSettings settings); } - public class TransmissionProxy: ITransmissionProxy + public class TransmissionProxy : ITransmissionProxy { private readonly IHttpClient _httpClient; private readonly Logger _logger; @@ -77,7 +77,10 @@ public void AddTorrentFromData(byte[] torrentData, string downloadDirectory, Tra public void SetTorrentSeedingConfiguration(string hash, TorrentSeedConfiguration seedConfiguration, TransmissionSettings settings) { - if (seedConfiguration == null) return; + if (seedConfiguration == null) + { + return; + } var arguments = new Dictionary(); arguments.Add("ids", new[] { hash }); @@ -155,7 +158,8 @@ private TransmissionResponse GetTorrentStatus(TransmissionSettings settings) private TransmissionResponse GetTorrentStatus(IEnumerable hashStrings, TransmissionSettings settings) { - var fields = new string[]{ + var fields = new string[] + { "id", "hashString", // Unique torrent ID. Use this instead of the client id? "name", diff --git a/src/NzbDrone.Core/Download/Clients/Transmission/TransmissionSettings.cs b/src/NzbDrone.Core/Download/Clients/Transmission/TransmissionSettings.cs index d185c47b0..40e2528ac 100644 --- a/src/NzbDrone.Core/Download/Clients/Transmission/TransmissionSettings.cs +++ b/src/NzbDrone.Core/Download/Clients/Transmission/TransmissionSettings.cs @@ -1,9 +1,9 @@ using System.Text.RegularExpressions; using FluentValidation; +using NzbDrone.Common.Extensions; using NzbDrone.Core.Annotations; using NzbDrone.Core.ThingiProvider; using NzbDrone.Core.Validation; -using NzbDrone.Common.Extensions; namespace NzbDrone.Core.Download.Clients.Transmission { diff --git a/src/NzbDrone.Core/Download/Clients/rTorrent/RTorrent.cs b/src/NzbDrone.Core/Download/Clients/rTorrent/RTorrent.cs index 19ec9e515..ba717ad6a 100644 --- a/src/NzbDrone.Core/Download/Clients/rTorrent/RTorrent.cs +++ b/src/NzbDrone.Core/Download/Clients/rTorrent/RTorrent.cs @@ -1,21 +1,21 @@ -using System; -using System.Linq; +using System; using System.Collections.Generic; +using System.Linq; using System.Threading; +using FluentValidation.Results; +using NLog; using NzbDrone.Common.Disk; -using NzbDrone.Common.Extensions; using NzbDrone.Common.EnvironmentInfo; +using NzbDrone.Common.Extensions; using NzbDrone.Common.Http; using NzbDrone.Core.Configuration; -using NzbDrone.Core.MediaFiles.TorrentInfo; -using NLog; -using NzbDrone.Core.Validation; -using FluentValidation.Results; using NzbDrone.Core.Download.Clients.rTorrent; using NzbDrone.Core.Exceptions; +using NzbDrone.Core.MediaFiles.TorrentInfo; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.RemotePathMappings; using NzbDrone.Core.ThingiProvider; +using NzbDrone.Core.Validation; namespace NzbDrone.Core.Download.Clients.RTorrent { @@ -24,7 +24,7 @@ public class RTorrent : TorrentClientBase private readonly IRTorrentProxy _proxy; private readonly IRTorrentDirectoryValidator _rTorrentDirectoryValidator; private readonly IDownloadSeedConfigProvider _downloadSeedConfigProvider; - private readonly string _imported_view = String.Concat(BuildInfo.AppName.ToLower(), "_imported"); + private readonly string _imported_view = string.Concat(BuildInfo.AppName.ToLower(), "_imported"); public RTorrent(IRTorrentProxy proxy, ITorrentFileInfoReader torrentFileInfoReader, @@ -54,8 +54,10 @@ public override void MarkItemAsImported(DownloadClientItem downloadClientItem) } catch (Exception ex) { - _logger.Warn(ex, "Failed to set torrent post-import label \"{0}\" for {1} in rTorrent. Does the label exist?", - Settings.TvImportedCategory, downloadClientItem.Title); + _logger.Warn(ex, + "Failed to set torrent post-import label \"{0}\" for {1} in rTorrent. Does the label exist?", + Settings.TvImportedCategory, + downloadClientItem.Title); } } @@ -66,8 +68,10 @@ public override void MarkItemAsImported(DownloadClientItem downloadClientItem) } catch (Exception ex) { - _logger.Warn(ex, "Failed to set torrent post-import view \"{0}\" for {1} in rTorrent.", - _imported_view, downloadClientItem.Title); + _logger.Warn(ex, + "Failed to set torrent post-import view \"{0}\" for {1} in rTorrent.", + _imported_view, + downloadClientItem.Title); } } @@ -123,7 +127,10 @@ public override IEnumerable GetItems() foreach (RTorrentTorrent torrent in torrents) { // Don't concern ourselves with categories other than specified - if (Settings.TvCategory.IsNotNullOrWhiteSpace() && torrent.Category != Settings.TvCategory) continue; + if (Settings.TvCategory.IsNotNullOrWhiteSpace() && torrent.Category != Settings.TvCategory) + { + continue; + } if (torrent.Path.StartsWith(".")) { @@ -171,8 +178,7 @@ public override IEnumerable GetItems() torrent.IsFinished && seedConfig != null && ( (torrent.Ratio / 1000.0) >= seedConfig.Ratio || - (DateTimeOffset.Now - DateTimeOffset.FromUnixTimeSeconds(torrent.FinishedTime)) >= seedConfig.SeedTime - ); + (DateTimeOffset.Now - DateTimeOffset.FromUnixTimeSeconds(torrent.FinishedTime)) >= seedConfig.SeedTime); items.Add(item); } @@ -205,7 +211,11 @@ public override DownloadClientInfo GetStatus() protected override void Test(List failures) { failures.AddIfNotNull(TestConnection()); - if (failures.HasErrors()) return; + if (failures.HasErrors()) + { + return; + } + failures.AddIfNotNull(TestGetTorrents()); failures.AddIfNotNull(TestDirectory()); } @@ -224,7 +234,7 @@ private ValidationFailure TestConnection() catch (Exception ex) { _logger.Error(ex, "Failed to test rTorrent"); - + return new NzbDroneValidationFailure("Host", "Unable to connect to rTorrent") { DetailedDescription = ex.Message diff --git a/src/NzbDrone.Core/Download/Clients/rTorrent/RTorrentProxy.cs b/src/NzbDrone.Core/Download/Clients/rTorrent/RTorrentProxy.cs index 91721f213..db7506471 100644 --- a/src/NzbDrone.Core/Download/Clients/rTorrent/RTorrentProxy.cs +++ b/src/NzbDrone.Core/Download/Clients/rTorrent/RTorrentProxy.cs @@ -4,9 +4,9 @@ using System.Net; using System.Net.Sockets; using System.Runtime.InteropServices.ComTypes; +using CookComputing.XmlRpc; using NLog; using NzbDrone.Common.Extensions; -using CookComputing.XmlRpc; namespace NzbDrone.Core.Download.Clients.RTorrent { @@ -80,7 +80,8 @@ public List GetTorrents(RTorrentSettings settings) _logger.Debug("Executing remote method: d.multicall2"); var client = BuildClient(settings); - var ret = ExecuteRequest(() => client.TorrentMulticall("", "", + var ret = ExecuteRequest(() => client.TorrentMulticall("", + "", "d.name=", // string "d.hash=", // string "d.base_path=", // string @@ -92,8 +93,7 @@ public List GetTorrents(RTorrentSettings settings) "d.is_open=", // long "d.is_active=", // long "d.complete=", // long - "d.timestamp.finished=") // long (unix timestamp) - ); + "d.timestamp.finished=")); // long (unix timestamp) var items = new List(); diff --git a/src/NzbDrone.Core/Download/Clients/rTorrent/RTorrentSettings.cs b/src/NzbDrone.Core/Download/Clients/rTorrent/RTorrentSettings.cs index 9ea134cc2..a05045e9c 100644 --- a/src/NzbDrone.Core/Download/Clients/rTorrent/RTorrentSettings.cs +++ b/src/NzbDrone.Core/Download/Clients/rTorrent/RTorrentSettings.cs @@ -13,7 +13,7 @@ public RTorrentSettingsValidator() RuleFor(c => c.Port).InclusiveBetween(1, 65535); RuleFor(c => c.TvCategory).NotEmpty() .WithMessage("A category is recommended") - .AsWarning(); + .AsWarning(); } } diff --git a/src/NzbDrone.Core/Download/Clients/uTorrent/UTorrent.cs b/src/NzbDrone.Core/Download/Clients/uTorrent/UTorrent.cs index 391ef1876..cd7a96a32 100644 --- a/src/NzbDrone.Core/Download/Clients/uTorrent/UTorrent.cs +++ b/src/NzbDrone.Core/Download/Clients/uTorrent/UTorrent.cs @@ -1,18 +1,18 @@ using System; -using System.Linq; using System.Collections.Generic; +using System.Linq; +using System.Net; +using FluentValidation.Results; +using NLog; +using NzbDrone.Common.Cache; using NzbDrone.Common.Disk; using NzbDrone.Common.Extensions; using NzbDrone.Common.Http; using NzbDrone.Core.Configuration; using NzbDrone.Core.MediaFiles.TorrentInfo; -using NLog; -using NzbDrone.Core.Validation; -using FluentValidation.Results; -using System.Net; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.RemotePathMappings; -using NzbDrone.Common.Cache; +using NzbDrone.Core.Validation; namespace NzbDrone.Core.Download.Clients.UTorrent { @@ -64,8 +64,8 @@ protected override string AddFromMagnetLink(RemoteEpisode remoteEpisode, string var isRecentEpisode = remoteEpisode.IsRecentEpisode(); - if (isRecentEpisode && Settings.RecentTvPriority == (int)UTorrentPriority.First || - !isRecentEpisode && Settings.OlderTvPriority == (int)UTorrentPriority.First) + if ((isRecentEpisode && Settings.RecentTvPriority == (int)UTorrentPriority.First) || + (!isRecentEpisode && Settings.OlderTvPriority == (int)UTorrentPriority.First)) { _proxy.MoveTorrentToTopInQueue(hash, Settings); } @@ -87,8 +87,8 @@ protected override string AddFromTorrentFile(RemoteEpisode remoteEpisode, string var isRecentEpisode = remoteEpisode.IsRecentEpisode(); - if (isRecentEpisode && Settings.RecentTvPriority == (int)UTorrentPriority.First || - !isRecentEpisode && Settings.OlderTvPriority == (int)UTorrentPriority.First) + if ((isRecentEpisode && Settings.RecentTvPriority == (int)UTorrentPriority.First) || + (!isRecentEpisode && Settings.OlderTvPriority == (int)UTorrentPriority.First)) { _proxy.MoveTorrentToTopInQueue(hash, Settings); } @@ -248,7 +248,11 @@ public override DownloadClientInfo GetStatus() protected override void Test(List failures) { failures.AddIfNotNull(TestConnection()); - if (failures.HasErrors()) return; + if (failures.HasErrors()) + { + return; + } + failures.AddIfNotNull(TestGetTorrents()); } @@ -281,6 +285,7 @@ private ValidationFailure TestConnection() DetailedDescription = "Please verify the hostname and port." }; } + return new NzbDroneValidationFailure(string.Empty, "Unknown exception: " + ex.Message); } catch (Exception ex) diff --git a/src/NzbDrone.Core/Download/Clients/uTorrent/UTorrentPriority.cs b/src/NzbDrone.Core/Download/Clients/uTorrent/UTorrentPriority.cs index 7173a71e4..0079da670 100644 --- a/src/NzbDrone.Core/Download/Clients/uTorrent/UTorrentPriority.cs +++ b/src/NzbDrone.Core/Download/Clients/uTorrent/UTorrentPriority.cs @@ -5,4 +5,4 @@ public enum UTorrentPriority Last = 0, First = 1 } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Download/Clients/uTorrent/UTorrentProxy.cs b/src/NzbDrone.Core/Download/Clients/uTorrent/UTorrentProxy.cs index 1f524028a..252cca7a1 100644 --- a/src/NzbDrone.Core/Download/Clients/uTorrent/UTorrentProxy.cs +++ b/src/NzbDrone.Core/Download/Clients/uTorrent/UTorrentProxy.cs @@ -107,7 +107,10 @@ public void AddTorrentFromFile(string fileName, byte[] fileContent, UTorrentSett public void SetTorrentSeedingConfiguration(string hash, TorrentSeedConfiguration seedConfiguration, UTorrentSettings settings) { - if (seedConfiguration == null) return; + if (seedConfiguration == null) + { + return; + } var requestBuilder = BuildRequest(settings) .AddQueryParam("action", "setprops") diff --git a/src/NzbDrone.Core/Download/Clients/uTorrent/UTorrentTorrent.cs b/src/NzbDrone.Core/Download/Clients/uTorrent/UTorrentTorrent.cs index 7f49de419..7cf2146bd 100644 --- a/src/NzbDrone.Core/Download/Clients/uTorrent/UTorrentTorrent.cs +++ b/src/NzbDrone.Core/Download/Clients/uTorrent/UTorrentTorrent.cs @@ -82,7 +82,7 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist if (reader.TokenType != JsonToken.EndArray) { result.DownloadUrl = (string)reader.Value; - + reader.Read(); result.RssFeedUrl = reader.Value; reader.Read(); @@ -100,9 +100,11 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist result.Unknown27 = reader.Value; reader.Read(); result.Unknown28 = reader.Value; - - while(reader.TokenType != JsonToken.EndArray) + + while (reader.TokenType != JsonToken.EndArray) + { reader.Read(); + } } return result; diff --git a/src/NzbDrone.Core/Download/Clients/uTorrent/UTorrentTorrentCache.cs b/src/NzbDrone.Core/Download/Clients/uTorrent/UTorrentTorrentCache.cs index 7f56675fe..4d9424f39 100644 --- a/src/NzbDrone.Core/Download/Clients/uTorrent/UTorrentTorrentCache.cs +++ b/src/NzbDrone.Core/Download/Clients/uTorrent/UTorrentTorrentCache.cs @@ -5,7 +5,7 @@ namespace NzbDrone.Core.Download.Clients.UTorrent public class UTorrentTorrentCache { public string CacheID { get; set; } - + public List Torrents { get; set; } } } diff --git a/src/NzbDrone.Core/Download/CompletedDownloadService.cs b/src/NzbDrone.Core/Download/CompletedDownloadService.cs index 38a42ab19..516bfa7e2 100644 --- a/src/NzbDrone.Core/Download/CompletedDownloadService.cs +++ b/src/NzbDrone.Core/Download/CompletedDownloadService.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.IO; using System.Linq; @@ -128,8 +128,10 @@ public void Import(TrackedDownload trackedDownload) trackedDownload.State = TrackedDownloadState.Importing; var outputPath = trackedDownload.ImportItem.OutputPath.FullPath; - var importResults = _downloadedEpisodesImportService.ProcessPath(outputPath, ImportMode.Auto, - trackedDownload.RemoteEpisode.Series, trackedDownload.ImportItem); + var importResults = _downloadedEpisodesImportService.ProcessPath(outputPath, + ImportMode.Auto, + trackedDownload.RemoteEpisode.Series, + trackedDownload.ImportItem); if (VerifyImport(trackedDownload, importResults)) { @@ -158,8 +160,7 @@ public void Import(TrackedDownload trackedDownload) .OrderBy(v => v.ImportDecision.LocalEpisode.Path) .Select(v => new TrackedDownloadStatusMessage(Path.GetFileName(v.ImportDecision.LocalEpisode.Path), - v.Errors)) - ); + v.Errors))); } if (statusMessages.Any()) @@ -187,7 +188,7 @@ public bool VerifyImport(TrackedDownload trackedDownload, List imp // file was imported. This will allow the decision engine to reject already imported // episode files and still mark the download complete when all files are imported. - // EDGE CASE: This process relies on EpisodeIds being consistent between executions, if a series is updated + // EDGE CASE: This process relies on EpisodeIds being consistent between executions, if a series is updated // and an episode is removed, but later comes back with a different ID then Sonarr will treat it as incomplete. // Since imports should be relatively fast and these types of data changes are infrequent this should be quite // safe, but commenting for future benefit. diff --git a/src/NzbDrone.Core/Download/DownloadCanBeRemovedEvent.cs b/src/NzbDrone.Core/Download/DownloadCanBeRemovedEvent.cs index 9c7284ad4..b852ee63d 100644 --- a/src/NzbDrone.Core/Download/DownloadCanBeRemovedEvent.cs +++ b/src/NzbDrone.Core/Download/DownloadCanBeRemovedEvent.cs @@ -12,4 +12,4 @@ public DownloadCanBeRemovedEvent(TrackedDownload trackedDownload) TrackedDownload = trackedDownload; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Download/DownloadClientBase.cs b/src/NzbDrone.Core/Download/DownloadClientBase.cs index 99c11c0d0..2abdb5207 100644 --- a/src/NzbDrone.Core/Download/DownloadClientBase.cs +++ b/src/NzbDrone.Core/Download/DownloadClientBase.cs @@ -30,12 +30,15 @@ public abstract class DownloadClientBase : IDownloadClient public ProviderDefinition Definition { get; set; } - public virtual object RequestAction(string action, IDictionary query) { return null; } + public virtual object RequestAction(string action, IDictionary query) + { + return null; + } protected TSettings Settings => (TSettings)Definition.Settings; - protected DownloadClientBase(IConfigService configService, - IDiskProvider diskProvider, + protected DownloadClientBase(IConfigService configService, + IDiskProvider diskProvider, IRemotePathMappingService remotePathMappingService, Logger logger) { diff --git a/src/NzbDrone.Core/Download/DownloadClientInfo.cs b/src/NzbDrone.Core/Download/DownloadClientInfo.cs index 987338c0d..734283ca4 100644 --- a/src/NzbDrone.Core/Download/DownloadClientInfo.cs +++ b/src/NzbDrone.Core/Download/DownloadClientInfo.cs @@ -7,7 +7,7 @@ public class DownloadClientInfo { public DownloadClientInfo() { - OutputRootFolders = new List(); + OutputRootFolders = new List(); } public bool IsLocalhost { get; set; } diff --git a/src/NzbDrone.Core/Download/DownloadClientItem.cs b/src/NzbDrone.Core/Download/DownloadClientItem.cs index 22cf2615d..671dae4ed 100644 --- a/src/NzbDrone.Core/Download/DownloadClientItem.cs +++ b/src/NzbDrone.Core/Download/DownloadClientItem.cs @@ -39,7 +39,8 @@ public class DownloadClientItemClientInfo public string Name { get; set; } public static DownloadClientItemClientInfo FromDownloadClient( - DownloadClientBase downloadClient) where TSettings : IProviderConfig, new() + DownloadClientBase downloadClient) + where TSettings : IProviderConfig, new() { return new DownloadClientItemClientInfo { diff --git a/src/NzbDrone.Core/Download/DownloadClientProvider.cs b/src/NzbDrone.Core/Download/DownloadClientProvider.cs index d778c01e1..3fa2bcc39 100644 --- a/src/NzbDrone.Core/Download/DownloadClientProvider.cs +++ b/src/NzbDrone.Core/Download/DownloadClientProvider.cs @@ -1,9 +1,9 @@ -using System.Linq; using System.Collections.Generic; -using NzbDrone.Core.Indexers; +using System.Linq; +using NLog; using NzbDrone.Common.Cache; using NzbDrone.Core.Download.Clients; -using NLog; +using NzbDrone.Core.Indexers; namespace NzbDrone.Core.Download { @@ -25,7 +25,7 @@ public class DownloadClientProvider : IProvideDownloadClient public DownloadClientProvider(IDownloadClientStatusService downloadClientStatusService, IDownloadClientFactory downloadClientFactory, IIndexerFactory indexerFactory, - ICacheManager cacheManager, + ICacheManager cacheManager, Logger logger) { _logger = logger; @@ -39,7 +39,10 @@ public IDownloadClient GetDownloadClient(DownloadProtocol downloadProtocol, int { var availableProviders = _downloadClientFactory.GetAvailableProviders().Where(v => v.Protocol == downloadProtocol).ToList(); - if (!availableProviders.Any()) return null; + if (!availableProviders.Any()) + { + return null; + } if (indexerId > 0) { diff --git a/src/NzbDrone.Core/Download/DownloadClientRepository.cs b/src/NzbDrone.Core/Download/DownloadClientRepository.cs index 9acebdeb0..704dababc 100644 --- a/src/NzbDrone.Core/Download/DownloadClientRepository.cs +++ b/src/NzbDrone.Core/Download/DownloadClientRepository.cs @@ -6,7 +6,6 @@ namespace NzbDrone.Core.Download { public interface IDownloadClientRepository : IProviderRepository { - } public class DownloadClientRepository : ProviderRepository, IDownloadClientRepository @@ -16,4 +15,4 @@ public DownloadClientRepository(IMainDatabase database, IEventAggregator eventAg { } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Download/DownloadClientStatus.cs b/src/NzbDrone.Core/Download/DownloadClientStatus.cs index 455196672..98d09a3ad 100644 --- a/src/NzbDrone.Core/Download/DownloadClientStatus.cs +++ b/src/NzbDrone.Core/Download/DownloadClientStatus.cs @@ -4,6 +4,5 @@ namespace NzbDrone.Core.Download { public class DownloadClientStatus : ProviderStatusBase { - } } diff --git a/src/NzbDrone.Core/Download/DownloadClientStatusRepository.cs b/src/NzbDrone.Core/Download/DownloadClientStatusRepository.cs index 4f6fd6dfa..f7c2b8f08 100644 --- a/src/NzbDrone.Core/Download/DownloadClientStatusRepository.cs +++ b/src/NzbDrone.Core/Download/DownloadClientStatusRepository.cs @@ -6,7 +6,6 @@ namespace NzbDrone.Core.Download { public interface IDownloadClientStatusRepository : IProviderStatusRepository { - } public class DownloadClientStatusRepository : ProviderStatusRepository, IDownloadClientStatusRepository diff --git a/src/NzbDrone.Core/Download/DownloadClientStatusService.cs b/src/NzbDrone.Core/Download/DownloadClientStatusService.cs index 11eecfe89..19f11d4b7 100644 --- a/src/NzbDrone.Core/Download/DownloadClientStatusService.cs +++ b/src/NzbDrone.Core/Download/DownloadClientStatusService.cs @@ -8,7 +8,6 @@ namespace NzbDrone.Core.Download { public interface IDownloadClientStatusService : IProviderStatusServiceBase { - } public class DownloadClientStatusService : ProviderStatusServiceBase, IDownloadClientStatusService diff --git a/src/NzbDrone.Core/Download/DownloadClientType.cs b/src/NzbDrone.Core/Download/DownloadClientType.cs index a1d67fe23..6989a34fb 100644 --- a/src/NzbDrone.Core/Download/DownloadClientType.cs +++ b/src/NzbDrone.Core/Download/DownloadClientType.cs @@ -7,4 +7,4 @@ public enum DownloadClientType Pneumatic = 2, Nzbget = 3 } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Download/DownloadCompletedEvent.cs b/src/NzbDrone.Core/Download/DownloadCompletedEvent.cs index 56ba2c842..f4debb147 100644 --- a/src/NzbDrone.Core/Download/DownloadCompletedEvent.cs +++ b/src/NzbDrone.Core/Download/DownloadCompletedEvent.cs @@ -14,4 +14,4 @@ public DownloadCompletedEvent(TrackedDownload trackedDownload, int seriesId) SeriesId = seriesId; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Download/DownloadFailedEvent.cs b/src/NzbDrone.Core/Download/DownloadFailedEvent.cs index 556f13529..4ebc84a84 100644 --- a/src/NzbDrone.Core/Download/DownloadFailedEvent.cs +++ b/src/NzbDrone.Core/Download/DownloadFailedEvent.cs @@ -1,8 +1,8 @@ using System.Collections.Generic; using NzbDrone.Common.Messaging; using NzbDrone.Core.Download.TrackedDownloads; -using NzbDrone.Core.Qualities; using NzbDrone.Core.Languages; +using NzbDrone.Core.Qualities; namespace NzbDrone.Core.Download { @@ -24,4 +24,4 @@ public DownloadFailedEvent() public TrackedDownload TrackedDownload { get; set; } public Language Language { get; set; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Download/DownloadIgnoredEvent.cs b/src/NzbDrone.Core/Download/DownloadIgnoredEvent.cs index 24f9f6ee4..ae887a87d 100644 --- a/src/NzbDrone.Core/Download/DownloadIgnoredEvent.cs +++ b/src/NzbDrone.Core/Download/DownloadIgnoredEvent.cs @@ -1,8 +1,8 @@ -using System.Collections.Generic; +using System.Collections.Generic; using NzbDrone.Common.Messaging; using NzbDrone.Core.Download.TrackedDownloads; -using NzbDrone.Core.Qualities; using NzbDrone.Core.Languages; +using NzbDrone.Core.Qualities; namespace NzbDrone.Core.Download { @@ -18,4 +18,4 @@ public class DownloadIgnoredEvent : IEvent public TrackedDownload TrackedDownload { get; set; } public string Message { get; set; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Download/DownloadSeedConfigProvider.cs b/src/NzbDrone.Core/Download/DownloadSeedConfigProvider.cs index 4c6513a42..cb5738188 100644 --- a/src/NzbDrone.Core/Download/DownloadSeedConfigProvider.cs +++ b/src/NzbDrone.Core/Download/DownloadSeedConfigProvider.cs @@ -20,7 +20,7 @@ public class DownloadSeedConfigProvider : IDownloadSeedConfigProvider private readonly ISeedConfigProvider _indexerSeedConfigProvider; private readonly IDownloadHistoryService _downloadHistoryService; - class CachedSeedConfiguration + private class CachedSeedConfiguration { public int IndexerId { get; set; } public bool FullSeason { get; set; } @@ -39,13 +39,19 @@ public DownloadSeedConfigProvider(IDownloadHistoryService downloadHistoryService public TorrentSeedConfiguration GetSeedConfiguration(string infoHash) { - if (infoHash.IsNullOrWhiteSpace()) return null; + if (infoHash.IsNullOrWhiteSpace()) + { + return null; + } infoHash = infoHash.ToUpper(); var cachedConfig = _cacheDownloads.Get(infoHash, () => FetchIndexer(infoHash)); - if (cachedConfig == null) return null; + if (cachedConfig == null) + { + return null; + } var seedConfig = _indexerSeedConfigProvider.GetSeedConfiguration(cachedConfig.IndexerId, cachedConfig.FullSeason); diff --git a/src/NzbDrone.Core/Download/DownloadService.cs b/src/NzbDrone.Core/Download/DownloadService.cs index bb09c758d..e0a05ca19 100644 --- a/src/NzbDrone.Core/Download/DownloadService.cs +++ b/src/NzbDrone.Core/Download/DownloadService.cs @@ -18,7 +18,6 @@ public interface IDownloadService void DownloadReport(RemoteEpisode remoteEpisode); } - public class DownloadService : IDownloadService { private readonly IProvideDownloadClient _downloadClientProvider; @@ -96,6 +95,7 @@ public void DownloadReport(RemoteEpisode remoteEpisode) { _indexerStatusService.RecordFailure(remoteEpisode.Release.IndexerId); } + throw; } diff --git a/src/NzbDrone.Core/Download/DownloadsProcessedEvent.cs b/src/NzbDrone.Core/Download/DownloadsProcessedEvent.cs index 4ebe4fd40..8d85fd8c5 100644 --- a/src/NzbDrone.Core/Download/DownloadsProcessedEvent.cs +++ b/src/NzbDrone.Core/Download/DownloadsProcessedEvent.cs @@ -8,4 +8,4 @@ public DownloadsProcessedEvent() { } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Download/EpisodeGrabbedEvent.cs b/src/NzbDrone.Core/Download/EpisodeGrabbedEvent.cs index 27d030844..0b8561744 100644 --- a/src/NzbDrone.Core/Download/EpisodeGrabbedEvent.cs +++ b/src/NzbDrone.Core/Download/EpisodeGrabbedEvent.cs @@ -16,4 +16,4 @@ public EpisodeGrabbedEvent(RemoteEpisode episode) Episode = episode; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Download/History/DownloadHistoryService.cs b/src/NzbDrone.Core/Download/History/DownloadHistoryService.cs index bf1b5d406..43b786152 100644 --- a/src/NzbDrone.Core/Download/History/DownloadHistoryService.cs +++ b/src/NzbDrone.Core/Download/History/DownloadHistoryService.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.IO; using System.Linq; @@ -24,7 +24,6 @@ public class DownloadHistoryService : IDownloadHistoryService, IHandle, IHandle, IHandle - { private readonly IDownloadHistoryRepository _repository; private readonly IHistoryService _historyService; diff --git a/src/NzbDrone.Core/Download/InvalidNzbException.cs b/src/NzbDrone.Core/Download/InvalidNzbException.cs index 5607590d9..5fde39c54 100644 --- a/src/NzbDrone.Core/Download/InvalidNzbException.cs +++ b/src/NzbDrone.Core/Download/InvalidNzbException.cs @@ -5,19 +5,23 @@ namespace NzbDrone.Core.Download { public class InvalidNzbException : NzbDroneException { - public InvalidNzbException(string message, params object[] args) : base(message, args) + public InvalidNzbException(string message, params object[] args) + : base(message, args) { } - public InvalidNzbException(string message) : base(message) + public InvalidNzbException(string message) + : base(message) { } - public InvalidNzbException(string message, Exception innerException, params object[] args) : base(message, innerException, args) + public InvalidNzbException(string message, Exception innerException, params object[] args) + : base(message, innerException, args) { } - public InvalidNzbException(string message, Exception innerException) : base(message, innerException) + public InvalidNzbException(string message, Exception innerException) + : base(message, innerException) { } } diff --git a/src/NzbDrone.Core/Download/Pending/PendingReleaseService.cs b/src/NzbDrone.Core/Download/Pending/PendingReleaseService.cs index 0b03c3e8c..83f062c72 100644 --- a/src/NzbDrone.Core/Download/Pending/PendingReleaseService.cs +++ b/src/NzbDrone.Core/Download/Pending/PendingReleaseService.cs @@ -289,7 +289,10 @@ private List IncludeRemoteEpisodes(List releases var series = seriesMap.GetValueOrDefault(release.SeriesId); // Just in case the series was removed, but wasn't cleaned up yet (housekeeper will clean it up) - if (series == null) return null; + if (series == null) + { + return null; + } release.RemoteEpisode = new RemoteEpisode { diff --git a/src/NzbDrone.Core/Download/ProcessDownloadDecisions.cs b/src/NzbDrone.Core/Download/ProcessDownloadDecisions.cs index 1b37954cb..1f07aec6b 100644 --- a/src/NzbDrone.Core/Download/ProcessDownloadDecisions.cs +++ b/src/NzbDrone.Core/Download/ProcessDownloadDecisions.cs @@ -64,8 +64,8 @@ public ProcessedDecisions ProcessDecisions(List decisions) continue; } - if (downloadProtocol == DownloadProtocol.Usenet && usenetFailed || - downloadProtocol == DownloadProtocol.Torrent && torrentFailed) + if ((downloadProtocol == DownloadProtocol.Usenet && usenetFailed) || + (downloadProtocol == DownloadProtocol.Torrent && torrentFailed)) { PreparePending(pendingAddQueue, grabbed, pending, report, PendingReleaseReason.DownloadClientUnavailable); continue; diff --git a/src/NzbDrone.Core/Download/TorrentClientBase.cs b/src/NzbDrone.Core/Download/TorrentClientBase.cs index 62adab041..161ee3f12 100644 --- a/src/NzbDrone.Core/Download/TorrentClientBase.cs +++ b/src/NzbDrone.Core/Download/TorrentClientBase.cs @@ -1,18 +1,18 @@ -using System; +using System; using System.Net; using MonoTorrent; +using NLog; using NzbDrone.Common.Disk; using NzbDrone.Common.Extensions; using NzbDrone.Common.Http; +using NzbDrone.Core.Configuration; using NzbDrone.Core.Exceptions; using NzbDrone.Core.Indexers; using NzbDrone.Core.MediaFiles.TorrentInfo; using NzbDrone.Core.Organizer; using NzbDrone.Core.Parser.Model; -using NzbDrone.Core.ThingiProvider; -using NzbDrone.Core.Configuration; -using NLog; using NzbDrone.Core.RemotePathMappings; +using NzbDrone.Core.ThingiProvider; namespace NzbDrone.Core.Download { @@ -193,7 +193,8 @@ private string DownloadFromWebUrl(RemoteEpisode remoteEpisode, string torrentUrl { _logger.Debug( "{0} did not return the expected InfoHash for '{1}', Sonarr could potentially lose track of the download in progress.", - Definition.Implementation, remoteEpisode.Release.DownloadUrl); + Definition.Implementation, + remoteEpisode.Release.DownloadUrl); } return actualHash; @@ -224,7 +225,8 @@ private string DownloadFromMagnetUrl(RemoteEpisode remoteEpisode, string magnetU { _logger.Debug( "{0} did not return the expected InfoHash for '{1}', Sonarr could potentially lose track of the download in progress.", - Definition.Implementation, remoteEpisode.Release.DownloadUrl); + Definition.Implementation, + remoteEpisode.Release.DownloadUrl); } return actualHash; diff --git a/src/NzbDrone.Core/Download/TrackedDownloads/DownloadMonitoringService.cs b/src/NzbDrone.Core/Download/TrackedDownloads/DownloadMonitoringService.cs index c61cecebb..70e53b369 100644 --- a/src/NzbDrone.Core/Download/TrackedDownloads/DownloadMonitoringService.cs +++ b/src/NzbDrone.Core/Download/TrackedDownloads/DownloadMonitoringService.cs @@ -136,8 +136,8 @@ private TrackedDownload ProcessClientItem(IDownloadClient downloadClient, Downlo private bool DownloadIsTrackable(TrackedDownload trackedDownload) { // If the download has already been imported, failed or the user ignored it don't track it - if (trackedDownload.State == TrackedDownloadState.Imported || - trackedDownload.State == TrackedDownloadState.Failed || + if (trackedDownload.State == TrackedDownloadState.Imported || + trackedDownload.State == TrackedDownloadState.Failed || trackedDownload.State == TrackedDownloadState.Ignored) { return false; diff --git a/src/NzbDrone.Core/Download/TrackedDownloads/TrackedDownload.cs b/src/NzbDrone.Core/Download/TrackedDownloads/TrackedDownload.cs index 45d792006..1cbf0d327 100644 --- a/src/NzbDrone.Core/Download/TrackedDownloads/TrackedDownload.cs +++ b/src/NzbDrone.Core/Download/TrackedDownloads/TrackedDownload.cs @@ -18,7 +18,7 @@ public class TrackedDownload public TrackedDownload() { - StatusMessages = new TrackedDownloadStatusMessage[] {}; + StatusMessages = new TrackedDownloadStatusMessage[] { }; } public void Warn(string message, params object[] args) diff --git a/src/NzbDrone.Core/Download/TrackedDownloads/TrackedDownloadService.cs b/src/NzbDrone.Core/Download/TrackedDownloads/TrackedDownloadService.cs index f98ce880d..0c3370d11 100644 --- a/src/NzbDrone.Core/Download/TrackedDownloads/TrackedDownloadService.cs +++ b/src/NzbDrone.Core/Download/TrackedDownloads/TrackedDownloadService.cs @@ -181,9 +181,10 @@ private void LogItemChange(TrackedDownload trackedDownload, DownloadClientItem e existingItem.CanMoveFiles != downloadItem.CanMoveFiles) { _logger.Debug("Tracking '{0}:{1}': ClientState={2}{3} SonarrStage={4} Episode='{5}' OutputPath={6}.", - downloadItem.DownloadClientInfo.Name, downloadItem.Title, - downloadItem.Status, downloadItem.CanBeRemoved ? "" : - downloadItem.CanMoveFiles ? " (busy)" : " (readonly)", + downloadItem.DownloadClientInfo.Name, + downloadItem.Title, + downloadItem.Status, + downloadItem.CanBeRemoved ? "" : downloadItem.CanMoveFiles ? " (busy)" : " (readonly)", trackedDownload.State, trackedDownload.RemoteEpisode?.ParsedEpisodeInfo, downloadItem.OutputPath); @@ -194,7 +195,7 @@ private void UpdateCachedItem(TrackedDownload trackedDownload) { var parsedEpisodeInfo = Parser.Parser.ParseTitle(trackedDownload.DownloadItem.Title); - trackedDownload.RemoteEpisode = parsedEpisodeInfo == null ? null :_parsingService.Map(parsedEpisodeInfo, 0, 0); + trackedDownload.RemoteEpisode = parsedEpisodeInfo == null ? null : _parsingService.Map(parsedEpisodeInfo, 0, 0); } private static TrackedDownloadState GetStateFromHistory(DownloadHistoryEventType eventType) diff --git a/src/NzbDrone.Core/Download/TrackedDownloads/TrackedDownloadStatusMessage.cs b/src/NzbDrone.Core/Download/TrackedDownloads/TrackedDownloadStatusMessage.cs index e0537b8c3..2d8a30cfe 100644 --- a/src/NzbDrone.Core/Download/TrackedDownloads/TrackedDownloadStatusMessage.cs +++ b/src/NzbDrone.Core/Download/TrackedDownloads/TrackedDownloadStatusMessage.cs @@ -7,7 +7,6 @@ public class TrackedDownloadStatusMessage public string Title { get; set; } public List Messages { get; set; } - public TrackedDownloadStatusMessage(string title, List messages) { Title = title; diff --git a/src/NzbDrone.Core/Download/UsenetClientBase.cs b/src/NzbDrone.Core/Download/UsenetClientBase.cs index 9dc35ce2f..929f0a20c 100644 --- a/src/NzbDrone.Core/Download/UsenetClientBase.cs +++ b/src/NzbDrone.Core/Download/UsenetClientBase.cs @@ -1,14 +1,14 @@ using System.Net; +using NLog; using NzbDrone.Common.Disk; using NzbDrone.Common.Http; +using NzbDrone.Core.Configuration; using NzbDrone.Core.Exceptions; using NzbDrone.Core.Indexers; using NzbDrone.Core.Organizer; using NzbDrone.Core.Parser.Model; -using NzbDrone.Core.ThingiProvider; -using NzbDrone.Core.Configuration; -using NLog; using NzbDrone.Core.RemotePathMappings; +using NzbDrone.Core.ThingiProvider; namespace NzbDrone.Core.Download { diff --git a/src/NzbDrone.Core/Exceptions/BadRequestException.cs b/src/NzbDrone.Core/Exceptions/BadRequestException.cs index adf8bf57f..b74559d05 100644 --- a/src/NzbDrone.Core/Exceptions/BadRequestException.cs +++ b/src/NzbDrone.Core/Exceptions/BadRequestException.cs @@ -4,11 +4,13 @@ namespace NzbDrone.Core.Exceptions { public class BadRequestException : DownstreamException { - public BadRequestException(string message) : base(HttpStatusCode.BadRequest, message) + public BadRequestException(string message) + : base(HttpStatusCode.BadRequest, message) { } - public BadRequestException(string message, params object[] args) : base(HttpStatusCode.BadRequest, message, args) + public BadRequestException(string message, params object[] args) + : base(HttpStatusCode.BadRequest, message, args) { } } diff --git a/src/NzbDrone.Core/Exceptions/DownstreamException.cs b/src/NzbDrone.Core/Exceptions/DownstreamException.cs index 0ce8f1a94..88bf850fa 100644 --- a/src/NzbDrone.Core/Exceptions/DownstreamException.cs +++ b/src/NzbDrone.Core/Exceptions/DownstreamException.cs @@ -7,7 +7,8 @@ public class DownstreamException : NzbDroneException { public HttpStatusCode StatusCode { get; private set; } - public DownstreamException(HttpStatusCode statusCode, string message, params object[] args) : base(message, args) + public DownstreamException(HttpStatusCode statusCode, string message, params object[] args) + : base(message, args) { StatusCode = statusCode; } diff --git a/src/NzbDrone.Core/Exceptions/NzbDroneClientException.cs b/src/NzbDrone.Core/Exceptions/NzbDroneClientException.cs index e0345a1b2..5c162ad4f 100644 --- a/src/NzbDrone.Core/Exceptions/NzbDroneClientException.cs +++ b/src/NzbDrone.Core/Exceptions/NzbDroneClientException.cs @@ -13,6 +13,7 @@ public NzbDroneClientException(HttpStatusCode statusCode, string message, params { StatusCode = statusCode; } + public NzbDroneClientException(HttpStatusCode statusCode, string message, Exception innerException, params object[] args) : base(message, innerException, args) { diff --git a/src/NzbDrone.Core/Exceptions/ReleaseDownloadException.cs b/src/NzbDrone.Core/Exceptions/ReleaseDownloadException.cs index c9582ddde..b891b6d3b 100644 --- a/src/NzbDrone.Core/Exceptions/ReleaseDownloadException.cs +++ b/src/NzbDrone.Core/Exceptions/ReleaseDownloadException.cs @@ -8,7 +8,8 @@ public class ReleaseDownloadException : NzbDroneException { public ReleaseInfo Release { get; set; } - public ReleaseDownloadException(ReleaseInfo release, string message, params object[] args) : base(message, args) + public ReleaseDownloadException(ReleaseInfo release, string message, params object[] args) + : base(message, args) { Release = release; } diff --git a/src/NzbDrone.Core/Exceptions/SearchFailedException.cs b/src/NzbDrone.Core/Exceptions/SearchFailedException.cs index e5f42595c..356a343df 100644 --- a/src/NzbDrone.Core/Exceptions/SearchFailedException.cs +++ b/src/NzbDrone.Core/Exceptions/SearchFailedException.cs @@ -4,7 +4,8 @@ namespace NzbDrone.Core.Exceptions { public class SearchFailedException : NzbDroneException { - public SearchFailedException(string message) : base(message) + public SearchFailedException(string message) + : base(message) { } } diff --git a/src/NzbDrone.Core/Extras/Files/ExtraFileManager.cs b/src/NzbDrone.Core/Extras/Files/ExtraFileManager.cs index e03508495..0f0c01a19 100644 --- a/src/NzbDrone.Core/Extras/Files/ExtraFileManager.cs +++ b/src/NzbDrone.Core/Extras/Files/ExtraFileManager.cs @@ -26,7 +26,6 @@ public interface IManageExtraFiles public abstract class ExtraFileManager : IManageExtraFiles where TExtraFile : ExtraFile, new() - { private readonly IConfigService _configService; private readonly IDiskProvider _diskProvider; diff --git a/src/NzbDrone.Core/Extras/Files/ExtraFileRepository.cs b/src/NzbDrone.Core/Extras/Files/ExtraFileRepository.cs index 6ea20e48b..c79801173 100644 --- a/src/NzbDrone.Core/Extras/Files/ExtraFileRepository.cs +++ b/src/NzbDrone.Core/Extras/Files/ExtraFileRepository.cs @@ -5,7 +5,8 @@ namespace NzbDrone.Core.Extras.Files { - public interface IExtraFileRepository : IBasicRepository where TExtraFile : ExtraFile, new() + public interface IExtraFileRepository : IBasicRepository + where TExtraFile : ExtraFile, new() { void DeleteForSeries(int seriesId); void DeleteForSeason(int seriesId, int seasonNumber); diff --git a/src/NzbDrone.Core/Extras/Files/ExtraFileService.cs b/src/NzbDrone.Core/Extras/Files/ExtraFileService.cs index 10faf6054..ae3f50742 100644 --- a/src/NzbDrone.Core/Extras/Files/ExtraFileService.cs +++ b/src/NzbDrone.Core/Extras/Files/ExtraFileService.cs @@ -109,7 +109,6 @@ public void Handle(EpisodeFileDeletedEvent message) { _logger.Debug("Removing episode file from DB as part of cleanup routine, not deleting extra files from disk."); } - else { var series = _seriesService.GetSeries(message.EpisodeFile.SeriesId); diff --git a/src/NzbDrone.Core/Extras/Metadata/Consumers/Roksbox/RoksboxMetadata.cs b/src/NzbDrone.Core/Extras/Metadata/Consumers/Roksbox/RoksboxMetadata.cs index 36e9e9b0d..78bc40963 100644 --- a/src/NzbDrone.Core/Extras/Metadata/Consumers/Roksbox/RoksboxMetadata.cs +++ b/src/NzbDrone.Core/Extras/Metadata/Consumers/Roksbox/RoksboxMetadata.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.IO; using System.Linq; @@ -31,8 +31,8 @@ public RoksboxMetadata(IMapCoversToLocal mediaCoverService, _logger = logger; } - private static List ValidCertification = new List { "G", "NC-17", "PG", "PG-13", "R", "UR", "UNRATED", "NR", "TV-Y", "TV-Y7", "TV-Y7-FV", "TV-G", "TV-PG", "TV-14", "TV-MA" }; private static readonly Regex SeasonImagesRegex = new Regex(@"^(season (?\d+))|(?specials)", RegexOptions.Compiled | RegexOptions.IgnoreCase); + private static List ValidCertification = new List { "G", "NC-17", "PG", "PG-13", "R", "UR", "UNRATED", "NR", "TV-Y", "TV-Y7", "TV-Y7-FV", "TV-G", "TV-PG", "TV-14", "TV-MA" }; public override string Name => "Roksbox"; @@ -58,7 +58,11 @@ public override MetadataFile FindMetadataFile(Series series, string path) { var filename = Path.GetFileName(path); - if (filename == null) return null; + if (filename == null) + { + return null; + } + var parentdir = Directory.GetParent(path); var metadata = new MetadataFile @@ -81,7 +85,6 @@ public override MetadataFile FindMetadataFile(Series series, string path) { metadata.SeasonNumber = 0; } - else { metadata.SeasonNumber = Convert.ToInt32(seasonMatch.Groups["season"].Value); @@ -114,7 +117,7 @@ public override MetadataFile FindMetadataFile(Series series, string path) metadata.Type = MetadataType.EpisodeImage; return metadata; } - } + } } return null; @@ -132,7 +135,7 @@ public override MetadataFileResult EpisodeMetadata(Series series, EpisodeFile ep { return null; } - + _logger.Debug("Generating Episode Metadata for: {0}", episodeFile.RelativePath); var xmlResult = string.Empty; @@ -161,7 +164,6 @@ public override MetadataFileResult EpisodeMetadata(Series series, EpisodeFile ep { details.Add(new XElement("mpaa", series.Certification.ToUpperInvariant())); } - else { details.Add(new XElement("mpaa", "UNRATED")); @@ -195,7 +197,7 @@ public override List SeriesImages(Series series) var source = _mediaCoverService.GetCoverPath(series.Id, image.CoverType); var destination = Path.GetFileName(series.Path) + Path.GetExtension(source); - return new List{ new ImageFileResult(destination, source) }; + return new List { new ImageFileResult(destination, source) }; } public override List SeasonImages(Series series, Season season) @@ -243,7 +245,7 @@ public override List EpisodeImages(Series series, EpisodeFile e return new List(); } - return new List {new ImageFileResult(GetEpisodeImageFilename(episodeFile.RelativePath), screenshot.Url)}; + return new List { new ImageFileResult(GetEpisodeImageFilename(episodeFile.RelativePath), screenshot.Url) }; } private string GetEpisodeMetadataFilename(string episodeFilePath) diff --git a/src/NzbDrone.Core/Extras/Metadata/Consumers/Roksbox/RoksboxMetadataSettings.cs b/src/NzbDrone.Core/Extras/Metadata/Consumers/Roksbox/RoksboxMetadataSettings.cs index 8c2bcbf64..7fdafac5b 100644 --- a/src/NzbDrone.Core/Extras/Metadata/Consumers/Roksbox/RoksboxMetadataSettings.cs +++ b/src/NzbDrone.Core/Extras/Metadata/Consumers/Roksbox/RoksboxMetadataSettings.cs @@ -35,7 +35,7 @@ public RoksboxMetadataSettings() [FieldDefinition(3, Label = "Episode Images", Type = FieldType.Checkbox, Section = MetadataSectionType.Image, HelpText = "Season##\\filename.jpg")] public bool EpisodeImages { get; set; } - + public bool IsValid => true; public NzbDroneValidationResult Validate() diff --git a/src/NzbDrone.Core/Extras/Metadata/Consumers/Wdtv/WdtvMetadata.cs b/src/NzbDrone.Core/Extras/Metadata/Consumers/Wdtv/WdtvMetadata.cs index d1846c963..ea7fc9701 100644 --- a/src/NzbDrone.Core/Extras/Metadata/Consumers/Wdtv/WdtvMetadata.cs +++ b/src/NzbDrone.Core/Extras/Metadata/Consumers/Wdtv/WdtvMetadata.cs @@ -51,14 +51,16 @@ public override string GetFilenameAfterMove(Series series, EpisodeFile episodeFi _logger.Debug("Unknown episode file metadata: {0}", metadataFile.RelativePath); return Path.Combine(series.Path, metadataFile.RelativePath); - } public override MetadataFile FindMetadataFile(Series series, string path) { var filename = Path.GetFileName(path); - if (filename == null) return null; + if (filename == null) + { + return null; + } var metadata = new MetadataFile { @@ -80,7 +82,6 @@ public override MetadataFile FindMetadataFile(Series series, string path) { metadata.SeasonNumber = 0; } - else { metadata.SeasonNumber = Convert.ToInt32(seasonMatch.Groups["season"].Value); @@ -107,7 +108,6 @@ public override MetadataFile FindMetadataFile(Series series, string path) metadata.Type = MetadataType.EpisodeImage; return metadata; } - } return null; @@ -152,7 +152,6 @@ public override MetadataFileResult EpisodeMetadata(Series series, EpisodeFile ep details.Add(new XElement("actor", string.Join(" / ", series.Actors.ConvertAll(c => c.Name + " - " + c.Character)))); details.Add(new XElement("overview", episode.Overview)); - //Todo: get guest stars, writer and director //details.Add(new XElement("credits", tvdbEpisode.Writer.FirstOrDefault())); //details.Add(new XElement("director", tvdbEpisode.Directors.FirstOrDefault())); @@ -200,7 +199,7 @@ public override List SeasonImages(Series series, Season season) { return new List(); } - + var seasonFolders = GetSeasonFolders(series); //Work out the path to this season - if we don't have a matching path then skip this season. @@ -221,7 +220,7 @@ public override List SeasonImages(Series series, Season season) var path = Path.Combine(seasonFolder, "folder.jpg"); - return new List{ new ImageFileResult(path, image.Url) }; + return new List { new ImageFileResult(path, image.Url) }; } public override List EpisodeImages(Series series, EpisodeFile episodeFile) @@ -239,7 +238,7 @@ public override List EpisodeImages(Series series, EpisodeFile e return new List(); } - return new List{ new ImageFileResult(GetEpisodeImageFilename(episodeFile.RelativePath), screenshot.Url) }; + return new List { new ImageFileResult(GetEpisodeImageFilename(episodeFile.RelativePath), screenshot.Url) }; } private string GetEpisodeMetadataFilename(string episodeFilePath) @@ -282,7 +281,6 @@ private Dictionary GetSeasonFolders(Series series) } } } - else { _logger.Debug("Rejecting folder {0} for series {1}.", Path.GetDirectoryName(folder), series.Title); diff --git a/src/NzbDrone.Core/Extras/Metadata/Consumers/Wdtv/WdtvMetadataSettings.cs b/src/NzbDrone.Core/Extras/Metadata/Consumers/Wdtv/WdtvMetadataSettings.cs index 542bea22f..4b66dc408 100644 --- a/src/NzbDrone.Core/Extras/Metadata/Consumers/Wdtv/WdtvMetadataSettings.cs +++ b/src/NzbDrone.Core/Extras/Metadata/Consumers/Wdtv/WdtvMetadataSettings.cs @@ -35,7 +35,7 @@ public WdtvMetadataSettings() [FieldDefinition(3, Label = "Episode Images", Type = FieldType.Checkbox, Section = MetadataSectionType.Image, HelpText = "Season##\\filename.metathumb")] public bool EpisodeImages { get; set; } - + public bool IsValid => true; public NzbDroneValidationResult Validate() diff --git a/src/NzbDrone.Core/Extras/Metadata/Consumers/Xbmc/XbmcMetadata.cs b/src/NzbDrone.Core/Extras/Metadata/Consumers/Xbmc/XbmcMetadata.cs index a6db71e37..d050f171f 100644 --- a/src/NzbDrone.Core/Extras/Metadata/Consumers/Xbmc/XbmcMetadata.cs +++ b/src/NzbDrone.Core/Extras/Metadata/Consumers/Xbmc/XbmcMetadata.cs @@ -67,7 +67,10 @@ public override MetadataFile FindMetadataFile(Series series, string path) { var filename = Path.GetFileName(path); - if (filename == null) return null; + if (filename == null) + { + return null; + } var metadata = new MetadataFile { @@ -95,12 +98,10 @@ public override MetadataFile FindMetadataFile(Series series, string path) { metadata.SeasonNumber = 0; } - else if (int.TryParse(seasonNumberMatch, out seasonNumber)) { metadata.SeasonNumber = seasonNumber; } - else { return null; @@ -270,7 +271,7 @@ public override MetadataFileResult EpisodeMetadata(Series series, EpisodeFile ep details.Add(new XElement("displayseason", episode.AiredBeforeSeasonNumber)); details.Add(new XElement("displayepisode", episode.AiredBeforeEpisodeNumber ?? -1)); } - + var tvdbId = new XElement("uniqueid", episode.TvdbId); tvdbId.SetAttributeValue("type", "tvdb"); tvdbId.SetAttributeValue("default", true); @@ -284,7 +285,6 @@ public override MetadataFileResult EpisodeMetadata(Series series, EpisodeFile ep { details.Add(new XElement("thumb")); } - else { details.Add(new XElement("thumb", image.Url)); diff --git a/src/NzbDrone.Core/Extras/Metadata/Consumers/Xbmc/XbmcMetadataSettings.cs b/src/NzbDrone.Core/Extras/Metadata/Consumers/Xbmc/XbmcMetadataSettings.cs index b51deae48..62e169bfe 100644 --- a/src/NzbDrone.Core/Extras/Metadata/Consumers/Xbmc/XbmcMetadataSettings.cs +++ b/src/NzbDrone.Core/Extras/Metadata/Consumers/Xbmc/XbmcMetadataSettings.cs @@ -43,7 +43,7 @@ public XbmcMetadataSettings() [FieldDefinition(5, Label = "Episode Images", Type = FieldType.Checkbox, Section = MetadataSectionType.Image, HelpText = "-thumb.jpg")] public bool EpisodeImages { get; set; } - + public bool IsValid => true; public NzbDroneValidationResult Validate() diff --git a/src/NzbDrone.Core/Extras/Metadata/Files/MetadataFileRepository.cs b/src/NzbDrone.Core/Extras/Metadata/Files/MetadataFileRepository.cs index d1f29ea75..1a8b0aae8 100644 --- a/src/NzbDrone.Core/Extras/Metadata/Files/MetadataFileRepository.cs +++ b/src/NzbDrone.Core/Extras/Metadata/Files/MetadataFileRepository.cs @@ -15,4 +15,4 @@ public MetadataFileRepository(IMainDatabase database, IEventAggregator eventAggr { } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Extras/Metadata/MetadataBase.cs b/src/NzbDrone.Core/Extras/Metadata/MetadataBase.cs index f60928703..ecfa7b855 100644 --- a/src/NzbDrone.Core/Extras/Metadata/MetadataBase.cs +++ b/src/NzbDrone.Core/Extras/Metadata/MetadataBase.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.IO; using FluentValidation.Results; @@ -9,7 +9,8 @@ namespace NzbDrone.Core.Extras.Metadata { - public abstract class MetadataBase : IMetadata where TSettings : IProviderConfig, new() + public abstract class MetadataBase : IMetadata + where TSettings : IProviderConfig, new() { public abstract string Name { get; } @@ -43,7 +44,10 @@ public virtual string GetFilenameAfterMove(Series series, EpisodeFile episodeFil public abstract List SeasonImages(Series series, Season season); public abstract List EpisodeImages(Series series, EpisodeFile episodeFile); - public virtual object RequestAction(string action, IDictionary query) { return null; } + public virtual object RequestAction(string action, IDictionary query) + { + return null; + } protected TSettings Settings => (TSettings)Definition.Settings; diff --git a/src/NzbDrone.Core/Extras/Metadata/MetadataFactory.cs b/src/NzbDrone.Core/Extras/Metadata/MetadataFactory.cs index 5fe8db3f5..b52d8a18c 100644 --- a/src/NzbDrone.Core/Extras/Metadata/MetadataFactory.cs +++ b/src/NzbDrone.Core/Extras/Metadata/MetadataFactory.cs @@ -53,4 +53,4 @@ public List Enabled() return GetAvailableProviders().Where(n => ((MetadataDefinition)n.Definition).Enable).ToList(); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Extras/Metadata/MetadataRepository.cs b/src/NzbDrone.Core/Extras/Metadata/MetadataRepository.cs index 349da708e..942a5172b 100644 --- a/src/NzbDrone.Core/Extras/Metadata/MetadataRepository.cs +++ b/src/NzbDrone.Core/Extras/Metadata/MetadataRepository.cs @@ -15,4 +15,4 @@ public MetadataRepository(IMainDatabase database, IEventAggregator eventAggregat { } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Extras/Metadata/MetadataService.cs b/src/NzbDrone.Core/Extras/Metadata/MetadataService.cs index c3305cf2d..daa0bc15a 100644 --- a/src/NzbDrone.Core/Extras/Metadata/MetadataService.cs +++ b/src/NzbDrone.Core/Extras/Metadata/MetadataService.cs @@ -416,7 +416,7 @@ private List ProcessEpisodeImages(IMetadata consumer, Series serie _diskTransferService.TransferFile(existingFullPath, fullPath, TransferMode.Move); existingMetadata.RelativePath = image.RelativePath; - return new List{ existingMetadata }; + return new List { existingMetadata }; } } @@ -454,6 +454,7 @@ private void DownloadImage(Series series, ImageFileResult image) { _diskProvider.CopyFile(image.Url, fullPath); } + _mediaFileAttributeService.SetFilePermissions(fullPath); } catch (HttpException ex) diff --git a/src/NzbDrone.Core/Extras/Others/OtherExtraFileRepository.cs b/src/NzbDrone.Core/Extras/Others/OtherExtraFileRepository.cs index 3f33a3eb8..91fbdb056 100644 --- a/src/NzbDrone.Core/Extras/Others/OtherExtraFileRepository.cs +++ b/src/NzbDrone.Core/Extras/Others/OtherExtraFileRepository.cs @@ -15,4 +15,4 @@ public OtherExtraFileRepository(IMainDatabase database, IEventAggregator eventAg { } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Extras/Subtitles/ExistingSubtitleImporter.cs b/src/NzbDrone.Core/Extras/Subtitles/ExistingSubtitleImporter.cs index 9325eef90..d46323f34 100644 --- a/src/NzbDrone.Core/Extras/Subtitles/ExistingSubtitleImporter.cs +++ b/src/NzbDrone.Core/Extras/Subtitles/ExistingSubtitleImporter.cs @@ -20,7 +20,7 @@ public class ExistingSubtitleImporter : ImportExistingExtraFilesBase subtitleFileService, IAggregationService aggregationService, Logger logger) - : base (subtitleFileService) + : base(subtitleFileService) { _subtitleFileService = subtitleFileService; _aggregationService = aggregationService; diff --git a/src/NzbDrone.Core/Extras/Subtitles/SubtitleFileRepository.cs b/src/NzbDrone.Core/Extras/Subtitles/SubtitleFileRepository.cs index 9b87fa9e0..d8dc3564e 100644 --- a/src/NzbDrone.Core/Extras/Subtitles/SubtitleFileRepository.cs +++ b/src/NzbDrone.Core/Extras/Subtitles/SubtitleFileRepository.cs @@ -15,4 +15,4 @@ public SubtitleFileRepository(IMainDatabase database, IEventAggregator eventAggr { } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Extras/Subtitles/SubtitleService.cs b/src/NzbDrone.Core/Extras/Subtitles/SubtitleService.cs index 1b4379e03..4acbc9eb8 100644 --- a/src/NzbDrone.Core/Extras/Subtitles/SubtitleService.cs +++ b/src/NzbDrone.Core/Extras/Subtitles/SubtitleService.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.IO; using System.Linq; @@ -247,7 +247,7 @@ private string GetSuffix(Language language, int copy, List languageTags, if (languageTags.Any()) { suffixBuilder.Append("."); - suffixBuilder.Append(string.Join(".", languageTags)); + suffixBuilder.Append(string.Join(".", languageTags)); } return suffixBuilder.ToString(); diff --git a/src/NzbDrone.Core/Fluent.cs b/src/NzbDrone.Core/Fluent.cs index 4e8de9c24..9d1e4dcb5 100644 --- a/src/NzbDrone.Core/Fluent.cs +++ b/src/NzbDrone.Core/Fluent.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -40,7 +40,6 @@ public static long Gigabytes(this double gigabytes) return Convert.ToInt64(gigabytes * 1024L * 1024L * 1024L); } - public static long Round(this long number, long level) { return Convert.ToInt64(Math.Floor((decimal)number / level) * level); @@ -49,16 +48,24 @@ public static long Round(this long number, long level) public static string ToBestDateString(this DateTime dateTime) { if (dateTime == DateTime.Today.AddDays(-1)) + { return "Yesterday"; + } if (dateTime == DateTime.Today) + { return "Today"; + } if (dateTime == DateTime.Today.AddDays(1)) + { return "Tomorrow"; + } if (dateTime > DateTime.Today.AddDays(1) && dateTime < DateTime.Today.AddDays(7)) + { return dateTime.DayOfWeek.ToString(); + } return dateTime.ToShortDateString(); } @@ -66,12 +73,16 @@ public static string ToBestDateString(this DateTime dateTime) public static int MaxOrDefault(this IEnumerable ints) { if (ints == null) + { return 0; + } var intList = ints.ToList(); if (!intList.Any()) + { return 0; + } return intList.Max(); } @@ -84,7 +95,10 @@ public static int GetByteCount(this string input) public static string Truncate(this string s, int maxLength) { if (Encoding.UTF8.GetByteCount(s) <= maxLength) + { return s; + } + var cs = s.ToCharArray(); int length = 0; int i = 0; @@ -92,7 +106,10 @@ public static string Truncate(this string s, int maxLength) { int charSize = 1; if (i < (cs.Length - 1) && char.IsSurrogate(cs[i])) + { charSize = 2; + } + int byteSize = Encoding.UTF8.GetByteCount(cs, i, charSize); if ((byteSize + length) <= maxLength) { @@ -100,20 +117,27 @@ public static string Truncate(this string s, int maxLength) length += byteSize; } else + { break; + } } + return s.Substring(0, i); } public static int MinOrDefault(this IEnumerable ints) { if (ints == null) + { return 0; + } var intsList = ints.ToList(); if (!intsList.Any()) + { return 0; + } return intsList.Min(); } diff --git a/src/NzbDrone.Core/HealthCheck/Checks/ImportListStatusCheck.cs b/src/NzbDrone.Core/HealthCheck/Checks/ImportListStatusCheck.cs index cf0483502..61519508c 100644 --- a/src/NzbDrone.Core/HealthCheck/Checks/ImportListStatusCheck.cs +++ b/src/NzbDrone.Core/HealthCheck/Checks/ImportListStatusCheck.cs @@ -41,4 +41,4 @@ public override HealthCheck Check() return new HealthCheck(GetType(), HealthCheckResult.Warning, string.Format("Import lists unavailable due to failures: {0}", string.Join(", ", backOffProviders.Select(v => v.ImportList.Definition.Name))), "#import-lists-are-unavailable-due-to-failures"); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/HealthCheck/Checks/ImportMechanismCheck.cs b/src/NzbDrone.Core/HealthCheck/Checks/ImportMechanismCheck.cs index 0022faf3a..64fd8e893 100644 --- a/src/NzbDrone.Core/HealthCheck/Checks/ImportMechanismCheck.cs +++ b/src/NzbDrone.Core/HealthCheck/Checks/ImportMechanismCheck.cs @@ -18,7 +18,6 @@ public class ImportMechanismCheck : HealthCheckBase private readonly IConfigService _configService; private readonly IProvideDownloadClient _provideDownloadClient; - public ImportMechanismCheck(IConfigService configService, IProvideDownloadClient provideDownloadClient) { _configService = configService; diff --git a/src/NzbDrone.Core/HealthCheck/Checks/IndexerLongTermStatusCheck.cs b/src/NzbDrone.Core/HealthCheck/Checks/IndexerLongTermStatusCheck.cs index ddffd4f27..7539a6ffd 100644 --- a/src/NzbDrone.Core/HealthCheck/Checks/IndexerLongTermStatusCheck.cs +++ b/src/NzbDrone.Core/HealthCheck/Checks/IndexerLongTermStatusCheck.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Linq; using NzbDrone.Common.Extensions; using NzbDrone.Core.Indexers; @@ -26,7 +26,7 @@ public override HealthCheck Check() var backOffProviders = enabledProviders.Join(_providerStatusService.GetBlockedProviders(), i => i.Definition.Id, s => s.ProviderId, - (i, s) => new {Provider = i, Status = s}) + (i, s) => new { Provider = i, Status = s }) .Where(p => p.Status.InitialFailure.HasValue && p.Status.InitialFailure.Value.Before( DateTime.UtcNow.AddHours(-6))) @@ -39,11 +39,14 @@ public override HealthCheck Check() if (backOffProviders.Count == enabledProviders.Count) { - return new HealthCheck(GetType(), HealthCheckResult.Error, - "All indexers are unavailable due to failures for more than 6 hours", "#indexers-are-unavailable-due-to-failures"); + return new HealthCheck(GetType(), + HealthCheckResult.Error, + "All indexers are unavailable due to failures for more than 6 hours", + "#indexers-are-unavailable-due-to-failures"); } - return new HealthCheck(GetType(), HealthCheckResult.Warning, + return new HealthCheck(GetType(), + HealthCheckResult.Warning, string.Format("Indexers unavailable due to failures for more than 6 hours: {0}", string.Join(", ", backOffProviders.Select(v => v.Provider.Definition.Name))), "#indexers-are-unavailable-due-to-failures"); diff --git a/src/NzbDrone.Core/HealthCheck/Checks/IndexerStatusCheck.cs b/src/NzbDrone.Core/HealthCheck/Checks/IndexerStatusCheck.cs index c283b525d..6b6152558 100644 --- a/src/NzbDrone.Core/HealthCheck/Checks/IndexerStatusCheck.cs +++ b/src/NzbDrone.Core/HealthCheck/Checks/IndexerStatusCheck.cs @@ -26,7 +26,7 @@ public override HealthCheck Check() var backOffProviders = enabledProviders.Join(_providerStatusService.GetBlockedProviders(), i => i.Definition.Id, s => s.ProviderId, - (i, s) => new {Provider = i, Status = s}) + (i, s) => new { Provider = i, Status = s }) .Where(p => p.Status.InitialFailure.HasValue && p.Status.InitialFailure.Value.After( DateTime.UtcNow.AddHours(-6))) diff --git a/src/NzbDrone.Core/HealthCheck/Checks/ProxyCheck.cs b/src/NzbDrone.Core/HealthCheck/Checks/ProxyCheck.cs index ea742bc6c..983958a8f 100644 --- a/src/NzbDrone.Core/HealthCheck/Checks/ProxyCheck.cs +++ b/src/NzbDrone.Core/HealthCheck/Checks/ProxyCheck.cs @@ -1,10 +1,10 @@ -using NLog; -using NzbDrone.Common.Http; -using NzbDrone.Core.Configuration; -using System; +using System; using System.Linq; using System.Net; +using NLog; using NzbDrone.Common.Cloud; +using NzbDrone.Common.Http; +using NzbDrone.Core.Configuration; using NzbDrone.Core.Configuration.Events; namespace NzbDrone.Core.HealthCheck.Checks diff --git a/src/NzbDrone.Core/HealthCheck/Checks/RemovedSeriesCheck.cs b/src/NzbDrone.Core/HealthCheck/Checks/RemovedSeriesCheck.cs index d1f325946..08901e0cd 100644 --- a/src/NzbDrone.Core/HealthCheck/Checks/RemovedSeriesCheck.cs +++ b/src/NzbDrone.Core/HealthCheck/Checks/RemovedSeriesCheck.cs @@ -30,7 +30,7 @@ public override HealthCheck Check() } var seriesText = deletedSeries.Select(s => $"{s.Title} (tvdbid {s.TvdbId})").Join(", "); - + if (deletedSeries.Count() == 1) { return new HealthCheck(GetType(), HealthCheckResult.Error, $"Series {seriesText} was removed from TheTVDB", "#series-removed-from-thetvdb"); diff --git a/src/NzbDrone.Core/HealthCheck/Checks/UpdateCheck.cs b/src/NzbDrone.Core/HealthCheck/Checks/UpdateCheck.cs index e7ed1ed44..663d2b139 100644 --- a/src/NzbDrone.Core/HealthCheck/Checks/UpdateCheck.cs +++ b/src/NzbDrone.Core/HealthCheck/Checks/UpdateCheck.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.IO; using NzbDrone.Common.Disk; using NzbDrone.Common.EnvironmentInfo; @@ -38,21 +38,24 @@ public override HealthCheck Check() { if (OsInfo.IsOsx && startupFolder.GetAncestorFolders().Contains("AppTranslocation")) { - return new HealthCheck(GetType(), HealthCheckResult.Error, + return new HealthCheck(GetType(), + HealthCheckResult.Error, string.Format("Cannot install update because startup folder '{0}' is in an App Translocation folder.", startupFolder), "#cannot-install-update-because-startup-folder-is-in-an-app-translocation-folder"); } if (!_diskProvider.FolderWritable(startupFolder)) { - return new HealthCheck(GetType(), HealthCheckResult.Error, + return new HealthCheck(GetType(), + HealthCheckResult.Error, string.Format("Cannot install update because startup folder '{0}' is not writable by the user '{1}'.", startupFolder, Environment.UserName), "#cannot-install-update-because-startup-folder-is-not-writable-by-the-user"); } if (!_diskProvider.FolderWritable(uiFolder)) { - return new HealthCheck(GetType(), HealthCheckResult.Error, + return new HealthCheck(GetType(), + HealthCheckResult.Error, string.Format("Cannot install update because UI folder '{0}' is not writable by the user '{1}'.", uiFolder, Environment.UserName), "#cannot-install-update-because-ui-folder-is-not-writable-by-the-user"); } diff --git a/src/NzbDrone.Core/HealthCheck/HealthCheckFailedEvent.cs b/src/NzbDrone.Core/HealthCheck/HealthCheckFailedEvent.cs index b4917262c..f1de9919b 100644 --- a/src/NzbDrone.Core/HealthCheck/HealthCheckFailedEvent.cs +++ b/src/NzbDrone.Core/HealthCheck/HealthCheckFailedEvent.cs @@ -13,4 +13,4 @@ public HealthCheckFailedEvent(HealthCheck healthCheck, bool isInStartupGraceperi IsInStartupGraceperiod = isInStartupGraceperiod; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/HealthCheck/HealthCheckService.cs b/src/NzbDrone.Core/HealthCheck/HealthCheckService.cs index 063f47724..1818c4a22 100644 --- a/src/NzbDrone.Core/HealthCheck/HealthCheckService.cs +++ b/src/NzbDrone.Core/HealthCheck/HealthCheckService.cs @@ -85,7 +85,6 @@ private void PerformHealthCheck(IProvideHealthCheck[] healthChecks) { _healthCheckResults.Remove(result.Source.Name); } - else { if (_healthCheckResults.Find(result.Source.Name) == null) @@ -99,7 +98,7 @@ private void PerformHealthCheck(IProvideHealthCheck[] healthChecks) _eventAggregator.PublishEvent(new HealthCheckCompleteEvent()); } - + public void Execute(CheckHealthCommand message) { if (message.Trigger == CommandTrigger.Manual) diff --git a/src/NzbDrone.Core/History/EpisodeHistory.cs b/src/NzbDrone.Core/History/EpisodeHistory.cs index 15dba719c..d3fa1d9b5 100644 --- a/src/NzbDrone.Core/History/EpisodeHistory.cs +++ b/src/NzbDrone.Core/History/EpisodeHistory.cs @@ -1,9 +1,9 @@ using System; using System.Collections.Generic; using NzbDrone.Core.Datastore; +using NzbDrone.Core.Languages; using NzbDrone.Core.Qualities; using NzbDrone.Core.Tv; -using NzbDrone.Core.Languages; namespace NzbDrone.Core.History { @@ -41,4 +41,4 @@ public enum EpisodeHistoryEventType EpisodeFileRenamed = 6, DownloadIgnored = 7 } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/History/HistoryRepository.cs b/src/NzbDrone.Core/History/HistoryRepository.cs index b3be6b3fe..eae10bbef 100644 --- a/src/NzbDrone.Core/History/HistoryRepository.cs +++ b/src/NzbDrone.Core/History/HistoryRepository.cs @@ -24,7 +24,6 @@ public interface IHistoryRepository : IBasicRepository public class HistoryRepository : BasicRepository, IHistoryRepository { - public HistoryRepository(IMainDatabase database, IEventAggregator eventAggregator) : base(database, eventAggregator) { @@ -95,8 +94,8 @@ public List FindDownloadHistory(int idSeriesId, QualityModel qua h.Quality == quality && (h.EventType == EpisodeHistoryEventType.Grabbed || h.EventType == EpisodeHistoryEventType.DownloadFailed || - h.EventType == EpisodeHistoryEventType.DownloadFolderImported) - ).ToList(); + h.EventType == EpisodeHistoryEventType.DownloadFolderImported)) + .ToList(); } public void DeleteForSeries(int seriesId) diff --git a/src/NzbDrone.Core/Housekeeping/Housekeepers/DeleteBadMediaCovers.cs b/src/NzbDrone.Core/Housekeeping/Housekeepers/DeleteBadMediaCovers.cs index 0bd74614b..55fcb7485 100644 --- a/src/NzbDrone.Core/Housekeeping/Housekeepers/DeleteBadMediaCovers.cs +++ b/src/NzbDrone.Core/Housekeeping/Housekeepers/DeleteBadMediaCovers.cs @@ -32,7 +32,10 @@ public DeleteBadMediaCovers(IMetadataFileService metaFileService, public void Clean() { - if (!_configService.CleanupMetadataImages) return; + if (!_configService.CleanupMetadataImages) + { + return; + } var series = _seriesService.GetAllSeries(); @@ -59,7 +62,6 @@ public void Clean() } } - _configService.CleanupMetadataImages = false; } @@ -75,7 +77,11 @@ private bool IsValid(string path) using (var imageStream = _diskProvider.OpenReadStream(path)) { - if (imageStream.Length < buffer.Length) return false; + if (imageStream.Length < buffer.Length) + { + return false; + } + imageStream.Read(buffer, 0, buffer.Length); } @@ -84,4 +90,4 @@ private bool IsValid(string path) return !text.ToLowerInvariant().Contains("html"); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Housekeeping/Housekeepers/FixFutureProviderStatusTimes.cs b/src/NzbDrone.Core/Housekeeping/Housekeepers/FixFutureProviderStatusTimes.cs index 80bf5c8b9..55a4c6b3d 100644 --- a/src/NzbDrone.Core/Housekeeping/Housekeepers/FixFutureProviderStatusTimes.cs +++ b/src/NzbDrone.Core/Housekeeping/Housekeepers/FixFutureProviderStatusTimes.cs @@ -5,7 +5,8 @@ namespace NzbDrone.Core.Housekeeping.Housekeepers { - public abstract class FixFutureProviderStatusTimes where TModel : ProviderStatusBase, new() + public abstract class FixFutureProviderStatusTimes + where TModel : ProviderStatusBase, new() { private readonly IProviderStatusRepository _repo; diff --git a/src/NzbDrone.Core/Housekeeping/HousekeepingService.cs b/src/NzbDrone.Core/Housekeeping/HousekeepingService.cs index eb8cedd9e..277065511 100644 --- a/src/NzbDrone.Core/Housekeeping/HousekeepingService.cs +++ b/src/NzbDrone.Core/Housekeeping/HousekeepingService.cs @@ -1,8 +1,8 @@ using System; using System.Collections.Generic; using NLog; -using NzbDrone.Core.Messaging.Commands; using NzbDrone.Core.Datastore; +using NzbDrone.Core.Messaging.Commands; namespace NzbDrone.Core.Housekeeping { @@ -30,7 +30,6 @@ private void Clean() _logger.Debug("Starting {0}", housekeeper.GetType().Name); housekeeper.Clean(); _logger.Debug("Completed {0}", housekeeper.GetType().Name); - } catch (Exception ex) { diff --git a/src/NzbDrone.Core/Housekeeping/IHousekeepingTask.cs b/src/NzbDrone.Core/Housekeeping/IHousekeepingTask.cs index 2a69cfdc5..f2e955782 100644 --- a/src/NzbDrone.Core/Housekeeping/IHousekeepingTask.cs +++ b/src/NzbDrone.Core/Housekeeping/IHousekeepingTask.cs @@ -4,4 +4,4 @@ public interface IHousekeepingTask { void Clean(); } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Http/CloudFlare/CloudFlareHttpInterceptor.cs b/src/NzbDrone.Core/Http/CloudFlare/CloudFlareHttpInterceptor.cs index e5590c63c..d77329f90 100644 --- a/src/NzbDrone.Core/Http/CloudFlare/CloudFlareHttpInterceptor.cs +++ b/src/NzbDrone.Core/Http/CloudFlare/CloudFlareHttpInterceptor.cs @@ -1,4 +1,4 @@ -using System.Net; +using System.Net; using System.Text.RegularExpressions; using NLog; using NzbDrone.Common.Http; @@ -7,9 +7,10 @@ namespace NzbDrone.Core.Http.CloudFlare { public class CloudFlareHttpInterceptor : IHttpRequestInterceptor { + private const string _cloudFlareChallengeScript = "cdn-cgi/scripts/cf.challenge.js"; + private readonly Logger _logger; - private const string _cloudFlareChallengeScript = "cdn-cgi/scripts/cf.challenge.js"; private static readonly Regex _cloudFlareRegex = new Regex(@"data-ray=""(?[\w-_]+)"".*?data-sitekey=""(?[\w-_]+)"".*?data-stoken=""(?[\w-_]+)""", RegexOptions.Compiled); public CloudFlareHttpInterceptor(Logger logger) diff --git a/src/NzbDrone.Core/Http/HttpProxySettingsProvider.cs b/src/NzbDrone.Core/Http/HttpProxySettingsProvider.cs index 6c335abae..57bd4451a 100644 --- a/src/NzbDrone.Core/Http/HttpProxySettingsProvider.cs +++ b/src/NzbDrone.Core/Http/HttpProxySettingsProvider.cs @@ -19,7 +19,9 @@ public HttpProxySettings GetProxySettings(HttpRequest request) { var proxySettings = GetProxySettings(); if (proxySettings == null) + { return null; + } if (ShouldProxyBeBypassed(proxySettings, request.Url)) { diff --git a/src/NzbDrone.Core/ImportLists/Exclusions/ImportListExclusionExistsValidator.cs b/src/NzbDrone.Core/ImportLists/Exclusions/ImportListExclusionExistsValidator.cs index fa8983bf6..f7aa42763 100644 --- a/src/NzbDrone.Core/ImportLists/Exclusions/ImportListExclusionExistsValidator.cs +++ b/src/NzbDrone.Core/ImportLists/Exclusions/ImportListExclusionExistsValidator.cs @@ -14,9 +14,12 @@ public ImportListExclusionExistsValidator(IImportListExclusionService importList protected override bool IsValid(PropertyValidatorContext context) { - if (context.PropertyValue == null) return true; + if (context.PropertyValue == null) + { + return true; + } - return (!_importListExclusionService.All().Exists(s => s.TvdbId == (int)context.PropertyValue)); + return !_importListExclusionService.All().Exists(s => s.TvdbId == (int)context.PropertyValue); } } } diff --git a/src/NzbDrone.Core/ImportLists/Exclusions/ImportListExclusionRepository.cs b/src/NzbDrone.Core/ImportLists/Exclusions/ImportListExclusionRepository.cs index effd3cf3e..9956191b5 100644 --- a/src/NzbDrone.Core/ImportLists/Exclusions/ImportListExclusionRepository.cs +++ b/src/NzbDrone.Core/ImportLists/Exclusions/ImportListExclusionRepository.cs @@ -1,6 +1,6 @@ +using System.Linq; using NzbDrone.Core.Datastore; using NzbDrone.Core.Messaging.Events; -using System.Linq; namespace NzbDrone.Core.ImportLists.Exclusions { diff --git a/src/NzbDrone.Core/ImportLists/Exclusions/ImportListExclusionService.cs b/src/NzbDrone.Core/ImportLists/Exclusions/ImportListExclusionService.cs index 54f361180..366c32293 100644 --- a/src/NzbDrone.Core/ImportLists/Exclusions/ImportListExclusionService.cs +++ b/src/NzbDrone.Core/ImportLists/Exclusions/ImportListExclusionService.cs @@ -1,7 +1,7 @@ -using NzbDrone.Core.Messaging.Events; -using NzbDrone.Core.Tv.Events; using System.Collections.Generic; using System.Linq; +using NzbDrone.Core.Messaging.Events; +using NzbDrone.Core.Tv.Events; namespace NzbDrone.Core.ImportLists.Exclusions { diff --git a/src/NzbDrone.Core/ImportLists/FetchAndParseImportListService.cs b/src/NzbDrone.Core/ImportLists/FetchAndParseImportListService.cs index 92a8ffc93..951e628eb 100644 --- a/src/NzbDrone.Core/ImportLists/FetchAndParseImportListService.cs +++ b/src/NzbDrone.Core/ImportLists/FetchAndParseImportListService.cs @@ -1,11 +1,11 @@ +using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using NLog; -using NzbDrone.Core.Parser.Model; -using NzbDrone.Common.TPL; -using System; using NzbDrone.Common.Extensions; +using NzbDrone.Common.TPL; +using NzbDrone.Core.Parser.Model; namespace NzbDrone.Core.ImportLists { @@ -71,7 +71,7 @@ public List Fetch() Task.WaitAll(taskList.ToArray()); - result = result.DistinctBy(r => new {r.TvdbId, r.Title}).ToList(); + result = result.DistinctBy(r => new { r.TvdbId, r.Title }).ToList(); _logger.Debug("Found {0} reports", result.Count); @@ -116,7 +116,6 @@ public List FetchSingleList(ImportListDefinition definition) taskList.Add(task); - Task.WaitAll(taskList.ToArray()); result = result.DistinctBy(r => new { r.TvdbId, r.Title }).ToList(); diff --git a/src/NzbDrone.Core/ImportLists/HttpImportListBase.cs b/src/NzbDrone.Core/ImportLists/HttpImportListBase.cs index 4a5b4e32b..7100b6882 100644 --- a/src/NzbDrone.Core/ImportLists/HttpImportListBase.cs +++ b/src/NzbDrone.Core/ImportLists/HttpImportListBase.cs @@ -22,7 +22,7 @@ public abstract class HttpImportListBase : ImportListBase protected const int MaxNumResultsPerQuery = 1000; protected readonly IHttpClient _httpClient; - + public bool SupportsPaging => PageSize > 0; public virtual int PageSize => 0; @@ -124,6 +124,7 @@ protected virtual IList FetchItems(Func : IImportList public abstract string Name { get; } - public abstract ImportListType ListType {get; } + public abstract ImportListType ListType { get; } public ImportListBase(IImportListStatusService importListStatusService, IConfigService configService, IParsingService parsingService, Logger logger) { @@ -53,7 +53,10 @@ public virtual IEnumerable DefaultDefinitions public virtual ProviderDefinition Definition { get; set; } - public virtual object RequestAction(string action, IDictionary query) { return null; } + public virtual object RequestAction(string action, IDictionary query) + { + return null; + } protected TSettings Settings => (TSettings)Definition.Settings; @@ -61,7 +64,7 @@ public virtual IEnumerable DefaultDefinitions protected virtual IList CleanupListItems(IEnumerable releases) { - var result = releases.DistinctBy(r => new {r.Title, r.TvdbId}).ToList(); + var result = releases.DistinctBy(r => new { r.Title, r.TvdbId }).ToList(); result.ForEach(c => { diff --git a/src/NzbDrone.Core/ImportLists/ImportListStatus.cs b/src/NzbDrone.Core/ImportLists/ImportListStatus.cs index e58976744..139d2b97b 100644 --- a/src/NzbDrone.Core/ImportLists/ImportListStatus.cs +++ b/src/NzbDrone.Core/ImportLists/ImportListStatus.cs @@ -5,6 +5,6 @@ namespace NzbDrone.Core.ImportLists { public class ImportListStatus : ProviderStatusBase { - public ImportListItemInfo LastSyncListInfo { get; set; } + public ImportListItemInfo LastSyncListInfo { get; set; } } } diff --git a/src/NzbDrone.Core/ImportLists/ImportListStatusRepository.cs b/src/NzbDrone.Core/ImportLists/ImportListStatusRepository.cs index 8bf500a7a..24d052dcc 100644 --- a/src/NzbDrone.Core/ImportLists/ImportListStatusRepository.cs +++ b/src/NzbDrone.Core/ImportLists/ImportListStatusRepository.cs @@ -9,7 +9,6 @@ public interface IImportListStatusRepository : IProviderStatusRepository, IImportListStatusRepository - { public ImportListStatusRepository(IMainDatabase database, IEventAggregator eventAggregator) : base(database, eventAggregator) diff --git a/src/NzbDrone.Core/ImportLists/ImportListStatusService.cs b/src/NzbDrone.Core/ImportLists/ImportListStatusService.cs index 9898a3f78..362359dca 100644 --- a/src/NzbDrone.Core/ImportLists/ImportListStatusService.cs +++ b/src/NzbDrone.Core/ImportLists/ImportListStatusService.cs @@ -25,7 +25,6 @@ public ImportListItemInfo GetLastSyncListInfo(int importListId) return GetProviderStatus(importListId).LastSyncListInfo; } - public void UpdateListSyncStatus(int importListId, ImportListItemInfo listItemInfo) { lock (_syncRoot) diff --git a/src/NzbDrone.Core/ImportLists/ImportListSyncService.cs b/src/NzbDrone.Core/ImportLists/ImportListSyncService.cs index 42081e905..3a0cef217 100644 --- a/src/NzbDrone.Core/ImportLists/ImportListSyncService.cs +++ b/src/NzbDrone.Core/ImportLists/ImportListSyncService.cs @@ -6,8 +6,8 @@ using NzbDrone.Core.ImportLists.Exclusions; using NzbDrone.Core.Messaging.Commands; using NzbDrone.Core.MetadataSource; -using NzbDrone.Core.Tv; using NzbDrone.Core.Parser.Model; +using NzbDrone.Core.Tv; namespace NzbDrone.Core.ImportLists { @@ -38,7 +38,6 @@ public ImportListSyncService(IImportListFactory importListFactory, _logger = logger; } - private void SyncAll() { _logger.ProgressInfo("Starting Import List Sync"); @@ -48,7 +47,6 @@ private void SyncAll() var reports = rssReleases.ToList(); ProcessReports(reports); - } private void SyncList(ImportListDefinition definition) @@ -60,7 +58,6 @@ private void SyncList(ImportListDefinition definition) var reports = rssReleases.ToList(); ProcessReports(reports); - } private void ProcessReports(List reports) diff --git a/src/NzbDrone.Core/ImportLists/Plex/PlexImport.cs b/src/NzbDrone.Core/ImportLists/Plex/PlexImport.cs index 666c0bc11..c99d7a21b 100644 --- a/src/NzbDrone.Core/ImportLists/Plex/PlexImport.cs +++ b/src/NzbDrone.Core/ImportLists/Plex/PlexImport.cs @@ -36,7 +36,7 @@ public override IList Fetch() // var generator = GetRequestGenerator(); - return FetchItems(g =>g.GetListItems()); + return FetchItems(g => g.GetListItems()); } public override IParseImportListResponse GetParser() diff --git a/src/NzbDrone.Core/ImportLists/Sonarr/SonarrImport.cs b/src/NzbDrone.Core/ImportLists/Sonarr/SonarrImport.cs index 052913d97..34a8ad546 100644 --- a/src/NzbDrone.Core/ImportLists/Sonarr/SonarrImport.cs +++ b/src/NzbDrone.Core/ImportLists/Sonarr/SonarrImport.cs @@ -6,8 +6,8 @@ using NzbDrone.Common.Extensions; using NzbDrone.Core.Configuration; using NzbDrone.Core.Parser; -using NzbDrone.Core.Validation; using NzbDrone.Core.Parser.Model; +using NzbDrone.Core.Validation; namespace NzbDrone.Core.ImportLists.Sonarr { diff --git a/src/NzbDrone.Core/ImportLists/Trakt/TraktImportBase.cs b/src/NzbDrone.Core/ImportLists/Trakt/TraktImportBase.cs index 668e795c2..acad8918c 100644 --- a/src/NzbDrone.Core/ImportLists/Trakt/TraktImportBase.cs +++ b/src/NzbDrone.Core/ImportLists/Trakt/TraktImportBase.cs @@ -20,7 +20,6 @@ public abstract class TraktImportBase : HttpImportListBase public const string RenewUri = "https://auth.servarr.com/v1/trakt_sonarr/renew"; public const string ClientId = "d44ba57cab40c31eb3f797dcfccd203500796539125b333883ec1d94aa62ed4c"; - private IImportListRepository _importListRepository; protected TraktImportBase(IImportListRepository netImportRepository, diff --git a/src/NzbDrone.Core/IndexerSearch/CutoffUnmetEpisodeSearchCommand.cs b/src/NzbDrone.Core/IndexerSearch/CutoffUnmetEpisodeSearchCommand.cs index bc6c85cb8..8d73e4968 100644 --- a/src/NzbDrone.Core/IndexerSearch/CutoffUnmetEpisodeSearchCommand.cs +++ b/src/NzbDrone.Core/IndexerSearch/CutoffUnmetEpisodeSearchCommand.cs @@ -26,4 +26,4 @@ public CutoffUnmetEpisodeSearchCommand(int seriesId) Monitored = true; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/IndexerSearch/Definitions/AnimeEpisodeSearchCriteria.cs b/src/NzbDrone.Core/IndexerSearch/Definitions/AnimeEpisodeSearchCriteria.cs index 50fe0c867..8d7ed5b2a 100644 --- a/src/NzbDrone.Core/IndexerSearch/Definitions/AnimeEpisodeSearchCriteria.cs +++ b/src/NzbDrone.Core/IndexerSearch/Definitions/AnimeEpisodeSearchCriteria.cs @@ -12,4 +12,4 @@ public override string ToString() return $"[{Series.Title} : S{SeasonNumber:00}E{EpisodeNumber:00} ({AbsoluteEpisodeNumber:00})]"; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/IndexerSearch/Definitions/SceneEpisodeMapping.cs b/src/NzbDrone.Core/IndexerSearch/Definitions/SceneEpisodeMapping.cs index 08fd734b1..57938452a 100644 --- a/src/NzbDrone.Core/IndexerSearch/Definitions/SceneEpisodeMapping.cs +++ b/src/NzbDrone.Core/IndexerSearch/Definitions/SceneEpisodeMapping.cs @@ -23,7 +23,10 @@ public override bool Equals(object obj) { var other = obj as SceneEpisodeMapping; - if (object.ReferenceEquals(other, null)) return false; + if (object.ReferenceEquals(other, null)) + { + return false; + } return SeasonNumber == other.SeasonNumber && EpisodeNumber == other.EpisodeNumber && SearchMode == other.SearchMode; } diff --git a/src/NzbDrone.Core/IndexerSearch/Definitions/SceneSeasonMapping.cs b/src/NzbDrone.Core/IndexerSearch/Definitions/SceneSeasonMapping.cs index 3fcaff35a..c4e4152b0 100644 --- a/src/NzbDrone.Core/IndexerSearch/Definitions/SceneSeasonMapping.cs +++ b/src/NzbDrone.Core/IndexerSearch/Definitions/SceneSeasonMapping.cs @@ -21,7 +21,10 @@ public override bool Equals(object obj) { var other = obj as SceneSeasonMapping; - if (object.ReferenceEquals(other, null)) return false; + if (object.ReferenceEquals(other, null)) + { + return false; + } return SeasonNumber == other.SeasonNumber && SearchMode == other.SearchMode; } diff --git a/src/NzbDrone.Core/IndexerSearch/Definitions/SearchCriteriaBase.cs b/src/NzbDrone.Core/IndexerSearch/Definitions/SearchCriteriaBase.cs index 1f64f41be..3e64a98ee 100644 --- a/src/NzbDrone.Core/IndexerSearch/Definitions/SearchCriteriaBase.cs +++ b/src/NzbDrone.Core/IndexerSearch/Definitions/SearchCriteriaBase.cs @@ -26,7 +26,7 @@ public abstract class SearchCriteriaBase public static string GetCleanSceneTitle(string title) { - Ensure.That(title,() => title).IsNotNullOrWhiteSpace(); + Ensure.That(title, () => title).IsNotNullOrWhiteSpace(); var cleanTitle = BeginningThe.Replace(title, string.Empty); diff --git a/src/NzbDrone.Core/IndexerSearch/Definitions/SeasonSearchCriteria.cs b/src/NzbDrone.Core/IndexerSearch/Definitions/SeasonSearchCriteria.cs index cec5aad37..98f6292de 100644 --- a/src/NzbDrone.Core/IndexerSearch/Definitions/SeasonSearchCriteria.cs +++ b/src/NzbDrone.Core/IndexerSearch/Definitions/SeasonSearchCriteria.cs @@ -9,4 +9,4 @@ public override string ToString() return string.Format("[{0} : S{1:00}]", Series.Title, SeasonNumber); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/IndexerSearch/Definitions/SingleEpisodeSearchCriteria.cs b/src/NzbDrone.Core/IndexerSearch/Definitions/SingleEpisodeSearchCriteria.cs index 797482846..e7d869813 100644 --- a/src/NzbDrone.Core/IndexerSearch/Definitions/SingleEpisodeSearchCriteria.cs +++ b/src/NzbDrone.Core/IndexerSearch/Definitions/SingleEpisodeSearchCriteria.cs @@ -10,4 +10,4 @@ public override string ToString() return string.Format("[{0} : S{1:00}E{2:00}]", Series.Title, SeasonNumber, EpisodeNumber); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/IndexerSearch/EpisodeSearchCommand.cs b/src/NzbDrone.Core/IndexerSearch/EpisodeSearchCommand.cs index af0cbf1cc..4f8bebc1f 100644 --- a/src/NzbDrone.Core/IndexerSearch/EpisodeSearchCommand.cs +++ b/src/NzbDrone.Core/IndexerSearch/EpisodeSearchCommand.cs @@ -18,4 +18,4 @@ public EpisodeSearchCommand(List episodeIds) EpisodeIds = episodeIds; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/IndexerSearch/EpisodeSearchService.cs b/src/NzbDrone.Core/IndexerSearch/EpisodeSearchService.cs index 9ea676d3f..73a54186a 100644 --- a/src/NzbDrone.Core/IndexerSearch/EpisodeSearchService.cs +++ b/src/NzbDrone.Core/IndexerSearch/EpisodeSearchService.cs @@ -63,7 +63,6 @@ private void SearchForEpisodes(List episodes, bool monitoredOnly, bool continue; } } - else { try @@ -90,7 +89,7 @@ private bool IsMonitored(bool episodeMonitored, bool seriesMonitored) { return episodeMonitored && seriesMonitored; } - + public void Execute(EpisodeSearchCommand message) { foreach (var episodeId in message.EpisodeIds) @@ -116,7 +115,6 @@ public void Execute(MissingEpisodeSearchCommand message) e.AirDateUtc.Value.Before(DateTime.UtcNow)) .ToList(); } - else { var pagingSpec = new PagingSpec diff --git a/src/NzbDrone.Core/IndexerSearch/MissingEpisodeSearchCommand.cs b/src/NzbDrone.Core/IndexerSearch/MissingEpisodeSearchCommand.cs index 350e8825e..0633aae46 100644 --- a/src/NzbDrone.Core/IndexerSearch/MissingEpisodeSearchCommand.cs +++ b/src/NzbDrone.Core/IndexerSearch/MissingEpisodeSearchCommand.cs @@ -20,4 +20,4 @@ public MissingEpisodeSearchCommand(int seriesId) Monitored = true; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/IndexerSearch/ReleaseSearchService.cs b/src/NzbDrone.Core/IndexerSearch/ReleaseSearchService.cs index 8159afc81..b511c6141 100644 --- a/src/NzbDrone.Core/IndexerSearch/ReleaseSearchService.cs +++ b/src/NzbDrone.Core/IndexerSearch/ReleaseSearchService.cs @@ -1,20 +1,20 @@ using System; using System.Collections.Generic; using System.Globalization; +using System.Linq; using System.Threading.Tasks; using NLog; +using NzbDrone.Common.Extensions; using NzbDrone.Common.Instrumentation.Extensions; +using NzbDrone.Common.TPL; using NzbDrone.Core.DataAugmentation.Scene; using NzbDrone.Core.DecisionEngine; -using NzbDrone.Core.IndexerSearch.Definitions; +using NzbDrone.Core.Exceptions; using NzbDrone.Core.Indexers; +using NzbDrone.Core.IndexerSearch.Definitions; +using NzbDrone.Core.Parser; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Tv; -using System.Linq; -using NzbDrone.Common.TPL; -using NzbDrone.Common.Extensions; -using NzbDrone.Core.Exceptions; -using NzbDrone.Core.Parser; namespace NzbDrone.Core.IndexerSearch { @@ -162,7 +162,7 @@ private List GetSceneSeasonMappings(Series series, List (v.SceneSeasonNumber ?? v.SeasonNumber) * 100000 + v.SeasonNumber); + var groupedEpisodes = episodes.ToLookup(v => ((v.SceneSeasonNumber ?? v.SeasonNumber) * 100000) + v.SeasonNumber); foreach (var groupedEpisode in groupedEpisodes) { @@ -238,7 +238,7 @@ private IEnumerable GetSceneEpisodeMappings(Series series, // - Mapped on Release Season Number with sceneMapping.SceneSeasonNumber specified and optionally sceneMapping.SeasonNumber. This translates via episode.SceneSeasonNumber/SeasonNumber to specific episodes. // - Mapped on Episode Season Number with optionally sceneMapping.SeasonNumber. This translates from episode.SceneSeasonNumber/SeasonNumber to specific releases. (Filter by episode.SeasonNumber or globally) - var ignoreSceneNumbering = (sceneMapping.SceneOrigin == "tvdb" || sceneMapping.SceneOrigin == "unknown:tvdb"); + var ignoreSceneNumbering = sceneMapping.SceneOrigin == "tvdb" || sceneMapping.SceneOrigin == "unknown:tvdb"; var mappingSceneSeasonNumber = sceneMapping.SceneSeasonNumber.NonNegative(); var mappingSeasonNumber = sceneMapping.SeasonNumber.NonNegative(); @@ -356,11 +356,12 @@ private List SearchAnime(Series series, Episode episode, bool return Dispatch(indexer => indexer.Fetch(searchSpec), searchSpec); } - private List SearchSpecial(Series series, List episodes,bool monitoredOnly, bool userInvokedSearch, bool interactiveSearch) + private List SearchSpecial(Series series, List episodes, bool monitoredOnly, bool userInvokedSearch, bool interactiveSearch) { var downloadDecisions = new List(); - + var searchSpec = Get(series, episodes, monitoredOnly, userInvokedSearch, interactiveSearch); + // build list of queries for each episode in the form: " " searchSpec.EpisodeQueryTitles = episodes.Where(e => !string.IsNullOrWhiteSpace(e.Title)) .SelectMany(e => searchSpec.CleanSceneTitles.Select(title => title + " " + SearchCriteriaBase.GetCleanSceneTitle(e.Title))) @@ -376,7 +377,7 @@ private List SearchSpecial(Series series, List episod { continue; } - + downloadDecisions.AddRange(SearchSingle(series, episode, monitoredOnly, userInvokedSearch, interactiveSearch)); } @@ -433,7 +434,8 @@ private List SearchDailySeason(Series series, List ep return DeDupeDecisions(downloadDecisions); } - private TSpec Get(Series series, List episodes, bool monitoredOnly, bool userInvokedSearch, bool interactiveSearch) where TSpec : SearchCriteriaBase, new() + private TSpec Get(Series series, List episodes, bool monitoredOnly, bool userInvokedSearch, bool interactiveSearch) + where TSpec : SearchCriteriaBase, new() { var spec = new TSpec(); @@ -441,7 +443,7 @@ private List SearchDailySeason(Series series, List ep spec.SceneTitles = _sceneMapping.GetSceneNames(series.TvdbId, episodes.Select(e => e.SeasonNumber).Distinct().ToList(), episodes.Select(e => e.SceneSeasonNumber ?? e.SeasonNumber).Distinct().ToList()); - + spec.Episodes = episodes; spec.MonitoredEpisodesOnly = monitoredOnly; spec.UserInvokedSearch = userInvokedSearch; @@ -455,7 +457,8 @@ private List SearchDailySeason(Series series, List ep return spec; } - private TSpec Get(Series series, SceneEpisodeMapping mapping, bool monitoredOnly, bool userInvokedSearch, bool interactiveSearch) where TSpec : SearchCriteriaBase, new() + private TSpec Get(Series series, SceneEpisodeMapping mapping, bool monitoredOnly, bool userInvokedSearch, bool interactiveSearch) + where TSpec : SearchCriteriaBase, new() { var spec = new TSpec(); @@ -471,7 +474,8 @@ private List SearchDailySeason(Series series, List ep return spec; } - private TSpec Get(Series series, SceneSeasonMapping mapping, bool monitoredOnly, bool userInvokedSearch, bool interactiveSearch) where TSpec : SearchCriteriaBase, new() + private TSpec Get(Series series, SceneSeasonMapping mapping, bool monitoredOnly, bool userInvokedSearch, bool interactiveSearch) + where TSpec : SearchCriteriaBase, new() { var spec = new TSpec(); diff --git a/src/NzbDrone.Core/IndexerSearch/SeasonSearchCommand.cs b/src/NzbDrone.Core/IndexerSearch/SeasonSearchCommand.cs index 2ac6cd439..5ee890828 100644 --- a/src/NzbDrone.Core/IndexerSearch/SeasonSearchCommand.cs +++ b/src/NzbDrone.Core/IndexerSearch/SeasonSearchCommand.cs @@ -9,4 +9,4 @@ public class SeasonSearchCommand : Command public override bool SendUpdatesToClient => true; } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/IndexerSearch/SeriesSearchCommand.cs b/src/NzbDrone.Core/IndexerSearch/SeriesSearchCommand.cs index d6bf7a150..2421bb390 100644 --- a/src/NzbDrone.Core/IndexerSearch/SeriesSearchCommand.cs +++ b/src/NzbDrone.Core/IndexerSearch/SeriesSearchCommand.cs @@ -17,4 +17,4 @@ public SeriesSearchCommand(int seriesId) SeriesId = seriesId; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Indexers/BroadcastheNet/BroadcastheNet.cs b/src/NzbDrone.Core/Indexers/BroadcastheNet/BroadcastheNet.cs index 434cd06f9..6f9f869f0 100644 --- a/src/NzbDrone.Core/Indexers/BroadcastheNet/BroadcastheNet.cs +++ b/src/NzbDrone.Core/Indexers/BroadcastheNet/BroadcastheNet.cs @@ -17,7 +17,6 @@ public class BroadcastheNet : HttpIndexerBase public BroadcastheNet(IHttpClient httpClient, IIndexerStatusService indexerStatusService, IConfigService configService, IParsingService parsingService, Logger logger) : base(httpClient, indexerStatusService, configService, parsingService, logger) { - } public override IIndexerRequestGenerator GetRequestGenerator() diff --git a/src/NzbDrone.Core/Indexers/BroadcastheNet/BroadcastheNetParser.cs b/src/NzbDrone.Core/Indexers/BroadcastheNet/BroadcastheNetParser.cs index 6cecc3b86..4888875bc 100644 --- a/src/NzbDrone.Core/Indexers/BroadcastheNet/BroadcastheNetParser.cs +++ b/src/NzbDrone.Core/Indexers/BroadcastheNet/BroadcastheNetParser.cs @@ -29,6 +29,7 @@ public IList ParseResponse(IndexerResponse indexerResponse) { throw new IndexerException(indexerResponse, "Indexer API call returned an unexpected StatusCode [{0}]", indexerResponse.HttpResponse.StatusCode); } + break; } @@ -42,7 +43,6 @@ public IList ParseResponse(IndexerResponse indexerResponse) throw new IndexerException(indexerResponse, "Indexer API returned an internal server error"); } - JsonRpcResponse jsonResponse = new HttpResponse>(indexerResponse.HttpResponse).Resource; if (jsonResponse.Error != null || jsonResponse.Result == null) @@ -66,16 +66,20 @@ public IList ParseResponse(IndexerResponse indexerResponse) torrentInfo.Size = torrent.Size; torrentInfo.DownloadUrl = RegexProtocol.Replace(torrent.DownloadURL, protocol); torrentInfo.InfoUrl = string.Format("{0}//broadcasthe.net/torrents.php?id={1}&torrentid={2}", protocol, torrent.GroupID, torrent.TorrentID); + //torrentInfo.CommentUrl = if (torrent.TvdbID.HasValue) { torrentInfo.TvdbId = torrent.TvdbID.Value; } + if (torrent.TvrageID.HasValue) { torrentInfo.TvRageId = torrent.TvrageID.Value; } + torrentInfo.PublishDate = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).ToUniversalTime().AddSeconds(torrent.Time); + //torrentInfo.MagnetUrl = torrentInfo.InfoHash = torrent.InfoHash; torrentInfo.Seeders = torrent.Seeders; diff --git a/src/NzbDrone.Core/Indexers/BroadcastheNet/BroadcastheNetRequestGenerator.cs b/src/NzbDrone.Core/Indexers/BroadcastheNet/BroadcastheNetRequestGenerator.cs index 8df7c7132..4b511d855 100644 --- a/src/NzbDrone.Core/Indexers/BroadcastheNet/BroadcastheNetRequestGenerator.cs +++ b/src/NzbDrone.Core/Indexers/BroadcastheNet/BroadcastheNetRequestGenerator.cs @@ -1,5 +1,5 @@ -using System.Linq; using System.Collections.Generic; +using System.Linq; using NzbDrone.Common.Http; using NzbDrone.Core.IndexerSearch.Definitions; @@ -190,7 +190,6 @@ public virtual IndexerPageableRequestChain GetSearchRequests(SpecialEpisodeSearc parameters.Category = "Episode"; parameters.Name = "%" + queryTitle + "%"; - pageableRequests.Add(GetPagedRequests(MaxPages, parameters)); } @@ -206,11 +205,13 @@ private bool AddSeriesSearchParameters(BroadcastheNetTorrentQuery parameters, Se parameters.Tvdb = string.Format("{0}", searchCriteria.Series.TvdbId); return true; } + if (searchCriteria.Series.TvRageId != 0) { parameters.Tvrage = string.Format("{0}", searchCriteria.Series.TvRageId); return true; } + // BTN is very neatly managed, so it's unlikely they map tvrage/tvdb wrongly. return false; } diff --git a/src/NzbDrone.Core/Indexers/BroadcastheNet/BroadcastheNetSettings.cs b/src/NzbDrone.Core/Indexers/BroadcastheNet/BroadcastheNetSettings.cs index 5dca18c01..e0ce19b45 100644 --- a/src/NzbDrone.Core/Indexers/BroadcastheNet/BroadcastheNetSettings.cs +++ b/src/NzbDrone.Core/Indexers/BroadcastheNet/BroadcastheNetSettings.cs @@ -11,7 +11,7 @@ public BroadcastheNetSettingsValidator() RuleFor(c => c.BaseUrl).ValidRootUrl(); RuleFor(c => c.ApiKey).NotEmpty(); - RuleFor(c => c.SeedCriteria).SetValidator(_ => new SeedCriteriaSettingsValidator(1.0, 24*60, 5*24*60)); + RuleFor(c => c.SeedCriteria).SetValidator(_ => new SeedCriteriaSettingsValidator(1.0, 24 * 60, 5 * 24 * 60)); } } diff --git a/src/NzbDrone.Core/Indexers/Exceptions/ApiKeyException.cs b/src/NzbDrone.Core/Indexers/Exceptions/ApiKeyException.cs index 41d0d4d5e..eb4e26654 100644 --- a/src/NzbDrone.Core/Indexers/Exceptions/ApiKeyException.cs +++ b/src/NzbDrone.Core/Indexers/Exceptions/ApiKeyException.cs @@ -4,11 +4,13 @@ namespace NzbDrone.Core.Indexers.Exceptions { public class ApiKeyException : NzbDroneException { - public ApiKeyException(string message, params object[] args) : base(message, args) + public ApiKeyException(string message, params object[] args) + : base(message, args) { } - public ApiKeyException(string message) : base(message) + public ApiKeyException(string message) + : base(message) { } } diff --git a/src/NzbDrone.Core/Indexers/Exceptions/SizeParsingException.cs b/src/NzbDrone.Core/Indexers/Exceptions/SizeParsingException.cs index 6fe085dd4..08e5d72f4 100644 --- a/src/NzbDrone.Core/Indexers/Exceptions/SizeParsingException.cs +++ b/src/NzbDrone.Core/Indexers/Exceptions/SizeParsingException.cs @@ -4,7 +4,8 @@ namespace NzbDrone.Core.Indexers.Exceptions { public class SizeParsingException : NzbDroneException { - public SizeParsingException(string message, params object[] args) : base(message, args) + public SizeParsingException(string message, params object[] args) + : base(message, args) { } } diff --git a/src/NzbDrone.Core/Indexers/EzrssTorrentRssParser.cs b/src/NzbDrone.Core/Indexers/EzrssTorrentRssParser.cs index b80782878..2b152ff2f 100644 --- a/src/NzbDrone.Core/Indexers/EzrssTorrentRssParser.cs +++ b/src/NzbDrone.Core/Indexers/EzrssTorrentRssParser.cs @@ -1,4 +1,4 @@ -using System.Linq; +using System.Linq; using System.Xml.Linq; using NzbDrone.Common.Extensions; using NzbDrone.Core.Indexers.Exceptions; @@ -30,6 +30,5 @@ protected override bool PreProcess(IndexerResponse indexerResponse) return base.PreProcess(indexerResponse); } - } } diff --git a/src/NzbDrone.Core/Indexers/Fanzub/Fanzub.cs b/src/NzbDrone.Core/Indexers/Fanzub/Fanzub.cs index fc66a83f1..f6b00e10a 100644 --- a/src/NzbDrone.Core/Indexers/Fanzub/Fanzub.cs +++ b/src/NzbDrone.Core/Indexers/Fanzub/Fanzub.cs @@ -14,7 +14,6 @@ public class Fanzub : HttpIndexerBase public Fanzub(IHttpClient httpClient, IIndexerStatusService indexerStatusService, IConfigService configService, IParsingService parsingService, Logger logger) : base(httpClient, indexerStatusService, configService, parsingService, logger) { - } public override IIndexerRequestGenerator GetRequestGenerator() diff --git a/src/NzbDrone.Core/Indexers/FetchAndParseRssService.cs b/src/NzbDrone.Core/Indexers/FetchAndParseRssService.cs index 6e23f1917..460f63e13 100644 --- a/src/NzbDrone.Core/Indexers/FetchAndParseRssService.cs +++ b/src/NzbDrone.Core/Indexers/FetchAndParseRssService.cs @@ -1,10 +1,10 @@ +using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using NLog; -using NzbDrone.Core.Parser.Model; using NzbDrone.Common.TPL; -using System; +using NzbDrone.Core.Parser.Model; namespace NzbDrone.Core.Indexers { public interface IFetchAndParseRss diff --git a/src/NzbDrone.Core/Indexers/FileList/FileListParser.cs b/src/NzbDrone.Core/Indexers/FileList/FileListParser.cs index dbf87b97d..511053421 100644 --- a/src/NzbDrone.Core/Indexers/FileList/FileListParser.cs +++ b/src/NzbDrone.Core/Indexers/FileList/FileListParser.cs @@ -52,7 +52,7 @@ public IList ParseResponse(IndexerResponse indexerResponse) return torrentInfos.ToArray(); } - + private string GetDownloadUrl(string torrentId) { var url = new HttpUri(_settings.BaseUrl) @@ -72,4 +72,4 @@ private string GetInfoUrl(string torrentId) return url.FullUri; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Indexers/FileList/FileListRequestGenerator.cs b/src/NzbDrone.Core/Indexers/FileList/FileListRequestGenerator.cs index 89a900988..76251a386 100644 --- a/src/NzbDrone.Core/Indexers/FileList/FileListRequestGenerator.cs +++ b/src/NzbDrone.Core/Indexers/FileList/FileListRequestGenerator.cs @@ -11,7 +11,7 @@ namespace NzbDrone.Core.Indexers.FileList public class FileListRequestGenerator : IIndexerRequestGenerator { public FileListSettings Settings { get; set; } - + public virtual IndexerPageableRequestChain GetRecentRequests() { var pageableRequests = new IndexerPageableRequestChain(); @@ -101,7 +101,6 @@ public IndexerPageableRequestChain GetSearchRequests(AnimeEpisodeSearchCriteria } return pageableRequests; - } public IndexerPageableRequestChain GetSearchRequests(SpecialEpisodeSearchCriteria searchCriteria) @@ -137,4 +136,4 @@ private IEnumerable GetRequest(string searchType, IEnumerable public HDBits(IHttpClient httpClient, IIndexerStatusService indexerStatusService, IConfigService configService, IParsingService parsingService, Logger logger) : base(httpClient, indexerStatusService, configService, parsingService, logger) - { } + { + } public override IIndexerRequestGenerator GetRequestGenerator() { diff --git a/src/NzbDrone.Core/Indexers/HDBits/HDBitsParser.cs b/src/NzbDrone.Core/Indexers/HDBits/HDBitsParser.cs index c5a6dfa4a..06f986b60 100644 --- a/src/NzbDrone.Core/Indexers/HDBits/HDBitsParser.cs +++ b/src/NzbDrone.Core/Indexers/HDBits/HDBitsParser.cs @@ -84,7 +84,6 @@ private string GetInfoUrl(string torrentId) .AddQueryParam("id", torrentId); return url.FullUri; - } } } diff --git a/src/NzbDrone.Core/Indexers/HDBits/HDBitsRequestGenerator.cs b/src/NzbDrone.Core/Indexers/HDBits/HDBitsRequestGenerator.cs index fead12419..6df07f8e9 100644 --- a/src/NzbDrone.Core/Indexers/HDBits/HDBitsRequestGenerator.cs +++ b/src/NzbDrone.Core/Indexers/HDBits/HDBitsRequestGenerator.cs @@ -122,6 +122,7 @@ private bool TryAddSearchParameters(TorrentQuery query, SearchCriteriaBase searc query.TvdbInfo.Id = searchCriteria.Series.TvdbId; return true; } + return false; } diff --git a/src/NzbDrone.Core/Indexers/HttpIndexerBase.cs b/src/NzbDrone.Core/Indexers/HttpIndexerBase.cs index f545e4395..7adeb3978 100644 --- a/src/NzbDrone.Core/Indexers/HttpIndexerBase.cs +++ b/src/NzbDrone.Core/Indexers/HttpIndexerBase.cs @@ -151,6 +151,7 @@ protected virtual IList FetchReleases(Func v.PublishDate).Min(); if (oldestReleaseDate < lastReleaseInfo.PublishDate || page.Any(v => v.DownloadUrl == lastReleaseInfo.DownloadUrl)) { @@ -195,6 +196,7 @@ protected virtual IList FetchReleases(Func FetchReleases(Func FetchPage(IndexerRequest request, IParseInd } catch (Exception ex) { - ex.WithData(response.HttpResponse, 128*1024); + ex.WithData(response.HttpResponse, 128 * 1024); _logger.Trace("Unexpected Response content ({0} bytes): {1}", response.HttpResponse.ResponseData.Length, response.HttpResponse.Content); throw; } @@ -318,6 +321,7 @@ protected virtual IndexerResponse FetchIndexerResponse(IndexerRequest request) { request.HttpRequest.RateLimit = RateLimit; } + request.HttpRequest.RateLimitKey = Definition.Id.ToString(); return new IndexerResponse(request, _httpClient.Execute(request.HttpRequest)); @@ -391,5 +395,4 @@ protected virtual ValidationFailure TestConnection() return null; } } - } diff --git a/src/NzbDrone.Core/Indexers/IPTorrents/IPTorrents.cs b/src/NzbDrone.Core/Indexers/IPTorrents/IPTorrents.cs index a62926c10..6b74949ba 100644 --- a/src/NzbDrone.Core/Indexers/IPTorrents/IPTorrents.cs +++ b/src/NzbDrone.Core/Indexers/IPTorrents/IPTorrents.cs @@ -1,7 +1,7 @@ +using NLog; using NzbDrone.Common.Http; using NzbDrone.Core.Configuration; using NzbDrone.Core.Parser; -using NLog; namespace NzbDrone.Core.Indexers.IPTorrents { @@ -16,7 +16,6 @@ public class IPTorrents : HttpIndexerBase public IPTorrents(IHttpClient httpClient, IIndexerStatusService indexerStatusService, IConfigService configService, IParsingService parsingService, Logger logger) : base(httpClient, indexerStatusService, configService, parsingService, logger) { - } public override IIndexerRequestGenerator GetRequestGenerator() @@ -29,4 +28,4 @@ public override IParseIndexerResponse GetParser() return new TorrentRssParser() { ParseSizeInDescription = true }; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Indexers/IndexerBase.cs b/src/NzbDrone.Core/Indexers/IndexerBase.cs index ec7e08386..8c469645f 100644 --- a/src/NzbDrone.Core/Indexers/IndexerBase.cs +++ b/src/NzbDrone.Core/Indexers/IndexerBase.cs @@ -60,7 +60,10 @@ public virtual IEnumerable DefaultDefinitions public virtual ProviderDefinition Definition { get; set; } - public virtual object RequestAction(string action, IDictionary query) { return null; } + public virtual object RequestAction(string action, IDictionary query) + { + return null; + } protected TSettings Settings => (TSettings)Definition.Settings; diff --git a/src/NzbDrone.Core/Indexers/IndexerPageableRequestChain.cs b/src/NzbDrone.Core/Indexers/IndexerPageableRequestChain.cs index 43b6b2277..d29b37ddb 100644 --- a/src/NzbDrone.Core/Indexers/IndexerPageableRequestChain.cs +++ b/src/NzbDrone.Core/Indexers/IndexerPageableRequestChain.cs @@ -27,14 +27,20 @@ public IEnumerable GetTier(int index) public void Add(IEnumerable request) { - if (request == null) return; + if (request == null) + { + return; + } _chains.Last().Add(new IndexerPageableRequest(request)); } public void AddToTier(int tierIndex, IEnumerable request) { - if (request == null) return; + if (request == null) + { + return; + } _chains[tierIndex].Add(new IndexerPageableRequest(request)); } @@ -47,9 +53,12 @@ public void AddTier(IEnumerable request) public void AddTier() { - if (_chains.Last().Count == 0) return; + if (_chains.Last().Count == 0) + { + return; + } _chains.Add(new List()); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Indexers/IndexerRepository.cs b/src/NzbDrone.Core/Indexers/IndexerRepository.cs index 50d07d66d..c4858f415 100644 --- a/src/NzbDrone.Core/Indexers/IndexerRepository.cs +++ b/src/NzbDrone.Core/Indexers/IndexerRepository.cs @@ -2,7 +2,6 @@ using NzbDrone.Core.Messaging.Events; using NzbDrone.Core.ThingiProvider; - namespace NzbDrone.Core.Indexers { public interface IIndexerRepository : IProviderRepository diff --git a/src/NzbDrone.Core/Indexers/IndexerStatusRepository.cs b/src/NzbDrone.Core/Indexers/IndexerStatusRepository.cs index 616c1cdf7..39856b5cf 100644 --- a/src/NzbDrone.Core/Indexers/IndexerStatusRepository.cs +++ b/src/NzbDrone.Core/Indexers/IndexerStatusRepository.cs @@ -6,7 +6,6 @@ namespace NzbDrone.Core.Indexers { public interface IIndexerStatusRepository : IProviderStatusRepository { - } public class IndexerStatusRepository : ProviderStatusRepository, IIndexerStatusRepository diff --git a/src/NzbDrone.Core/Indexers/IndexerStatusService.cs b/src/NzbDrone.Core/Indexers/IndexerStatusService.cs index 1bdf81533..4e6de3d68 100644 --- a/src/NzbDrone.Core/Indexers/IndexerStatusService.cs +++ b/src/NzbDrone.Core/Indexers/IndexerStatusService.cs @@ -18,7 +18,6 @@ public class IndexerStatusService : ProviderStatusServiceBase failures) { base.Test(failures); - if (failures.HasErrors()) return; + if (failures.HasErrors()) + { + return; + } + failures.AddIfNotNull(TestCapabilities()); } diff --git a/src/NzbDrone.Core/Indexers/Newznab/NewznabCapabilitiesProvider.cs b/src/NzbDrone.Core/Indexers/Newznab/NewznabCapabilitiesProvider.cs index 31f959412..1a91854ac 100644 --- a/src/NzbDrone.Core/Indexers/Newznab/NewznabCapabilitiesProvider.cs +++ b/src/NzbDrone.Core/Indexers/Newznab/NewznabCapabilitiesProvider.cs @@ -126,6 +126,7 @@ private NewznabCapabilities ParseCapabilities(HttpResponse response) { capabilities.SupportedSearchParameters = xmlBasicSearch.Attribute("supportedParams").Value.Split(','); } + capabilities.TextSearchEngine = xmlBasicSearch.Attribute("searchEngine")?.Value ?? capabilities.TextSearchEngine; } @@ -141,6 +142,7 @@ private NewznabCapabilities ParseCapabilities(HttpResponse response) capabilities.SupportedTvSearchParameters = xmlTvSearch.Attribute("supportedParams").Value.Split(','); capabilities.SupportsAggregateIdSearch = true; } + capabilities.TvTextSearchEngine = xmlTvSearch.Attribute("searchEngine")?.Value ?? capabilities.TvTextSearchEngine; } } @@ -165,7 +167,6 @@ private NewznabCapabilities ParseCapabilities(HttpResponse response) Id = int.Parse(xmlSubcat.Attribute("id").Value), Name = xmlSubcat.Attribute("name").Value, Description = xmlSubcat.Attribute("description") != null ? xmlSubcat.Attribute("description").Value : string.Empty - }); } diff --git a/src/NzbDrone.Core/Indexers/Newznab/NewznabCategoryFieldOptionsConverter.cs b/src/NzbDrone.Core/Indexers/Newznab/NewznabCategoryFieldOptionsConverter.cs index d1bf9715b..11fabde77 100644 --- a/src/NzbDrone.Core/Indexers/Newznab/NewznabCategoryFieldOptionsConverter.cs +++ b/src/NzbDrone.Core/Indexers/Newznab/NewznabCategoryFieldOptionsConverter.cs @@ -11,6 +11,7 @@ public static List GetFieldSelectOptions(List 0 && searchCriteria.EpisodeNumber > 0) { - pageableRequests.Add(GetPagedRequests(MaxPages, Settings.AnimeCategories, "tvsearch", - string.Format("&q={0}&season={1}&ep={2}", - NewsnabifyTitle(queryTitle), - searchCriteria.SeasonNumber, - searchCriteria.EpisodeNumber))); + pageableRequests.Add(GetPagedRequests(MaxPages, + Settings.AnimeCategories, + "tvsearch", + string.Format("&q={0}&season={1}&ep={2}", + NewsnabifyTitle(queryTitle), + searchCriteria.SeasonNumber, + searchCriteria.EpisodeNumber))); } } } @@ -347,7 +375,9 @@ public virtual IndexerPageableRequestChain GetSearchRequests(SpecialEpisodeSearc var query = queryTitle.Replace('+', ' '); query = System.Web.HttpUtility.UrlEncode(query); - pageableRequests.Add(GetPagedRequests(MaxPages, Settings.Categories.Concat(Settings.AnimeCategories), "search", + pageableRequests.Add(GetPagedRequests(MaxPages, + Settings.Categories.Concat(Settings.AnimeCategories), + "search", string.Format("&q={0}", query))); } @@ -371,6 +401,7 @@ private void AddTvIdPageableRequests(IndexerPageableRequestChain chain, IEnumera { ids += "&tvdbid=" + searchCriteria.Series.TvdbId; } + if (includeImdbSearch) { ids += "&imdbid=" + searchCriteria.Series.ImdbId; @@ -392,24 +423,39 @@ private void AddTvIdPageableRequests(IndexerPageableRequestChain chain, IEnumera { if (includeTvdbSearch) { - chain.Add(GetPagedRequests(MaxPages, categories, "tvsearch", - string.Format("&tvdbid={0}{1}", searchCriteria.Series.TvdbId, parameters))); + chain.Add(GetPagedRequests(MaxPages, + categories, + "tvsearch", + string.Format("&tvdbid={0}{1}", + searchCriteria.Series.TvdbId, + parameters))); } else if (includeImdbSearch) { - chain.Add(GetPagedRequests(MaxPages, categories, "tvsearch", - string.Format("&imdbid={0}{1}", searchCriteria.Series.ImdbId, parameters))); + chain.Add(GetPagedRequests(MaxPages, + categories, + "tvsearch", + string.Format("&imdbid={0}{1}", + searchCriteria.Series.ImdbId, + parameters))); } else if (includeTvRageSearch) { - chain.Add(GetPagedRequests(MaxPages, categories, "tvsearch", - string.Format("&rid={0}{1}", searchCriteria.Series.TvRageId, parameters))); + chain.Add(GetPagedRequests(MaxPages, + categories, + "tvsearch", + string.Format("&rid={0}{1}", + searchCriteria.Series.TvRageId, + parameters))); } - else if (includeTvMazeSearch) { - chain.Add(GetPagedRequests(MaxPages, categories, "tvsearch", - string.Format("&tvmazeid={0}{1}", searchCriteria.Series.TvMazeId, parameters))); + chain.Add(GetPagedRequests(MaxPages, + categories, + "tvsearch", + string.Format("&tvmazeid={0}{1}", + searchCriteria.Series.TvMazeId, + parameters))); } } } @@ -420,7 +466,9 @@ private void AddTitlePageableRequests(IndexerPageableRequestChain chain, IEnumer { foreach (var searchTerm in searchCriteria.SceneTitles) { - chain.Add(GetPagedRequests(MaxPages, Settings.Categories, "tvsearch", + chain.Add(GetPagedRequests(MaxPages, + Settings.Categories, + "tvsearch", string.Format("&title={0}{1}", Uri.EscapeDataString(searchTerm), parameters))); @@ -431,7 +479,9 @@ private void AddTitlePageableRequests(IndexerPageableRequestChain chain, IEnumer var queryTitles = TvTextSearchEngine == "raw" ? searchCriteria.SceneTitles : searchCriteria.CleanSceneTitles; foreach (var queryTitle in queryTitles) { - chain.Add(GetPagedRequests(MaxPages, Settings.Categories, "tvsearch", + chain.Add(GetPagedRequests(MaxPages, + Settings.Categories, + "tvsearch", string.Format("&q={0}{1}", NewsnabifyTitle(queryTitle), parameters))); @@ -474,7 +524,6 @@ private static string NewsnabifyTitle(string title) return Uri.EscapeDataString(title); } - // Temporary workaround for NNTMux considering season=0 -> null. '00' should work on existing newznab indexers. private static string NewznabifySeasonNumber(int seasonNumber) { diff --git a/src/NzbDrone.Core/Indexers/Newznab/NewznabRssParser.cs b/src/NzbDrone.Core/Indexers/Newznab/NewznabRssParser.cs index e5d4fb2bd..50a0a4fd2 100644 --- a/src/NzbDrone.Core/Indexers/Newznab/NewznabRssParser.cs +++ b/src/NzbDrone.Core/Indexers/Newznab/NewznabRssParser.cs @@ -25,7 +25,9 @@ public static void CheckError(XDocument xdoc, IndexerResponse indexerResponse) var error = xdoc.Descendants("error").FirstOrDefault(); if (error == null) + { return; + } var code = Convert.ToInt32(error.Attribute("code").Value); var errorMessage = error.Attribute("description").Value; diff --git a/src/NzbDrone.Core/Indexers/Nyaa/Nyaa.cs b/src/NzbDrone.Core/Indexers/Nyaa/Nyaa.cs index b652fdbc8..af169ecf5 100644 --- a/src/NzbDrone.Core/Indexers/Nyaa/Nyaa.cs +++ b/src/NzbDrone.Core/Indexers/Nyaa/Nyaa.cs @@ -15,7 +15,6 @@ public class Nyaa : HttpIndexerBase public Nyaa(IHttpClient httpClient, IIndexerStatusService indexerStatusService, IConfigService configService, IParsingService parsingService, Logger logger) : base(httpClient, indexerStatusService, configService, parsingService, logger) { - } public override IIndexerRequestGenerator GetRequestGenerator() @@ -28,4 +27,4 @@ public override IParseIndexerResponse GetParser() return new TorrentRssParser() { UseGuidInfoUrl = true, SizeElementName = "size", InfoHashElementName = "infoHash", PeersElementName = "leechers", CalculatePeersAsSum = true, SeedsElementName = "seeders" }; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Indexers/Nyaa/NyaaSettings.cs b/src/NzbDrone.Core/Indexers/Nyaa/NyaaSettings.cs index f5bc2bd5a..bed8caa78 100644 --- a/src/NzbDrone.Core/Indexers/Nyaa/NyaaSettings.cs +++ b/src/NzbDrone.Core/Indexers/Nyaa/NyaaSettings.cs @@ -1,7 +1,7 @@ +using System.Text.RegularExpressions; using FluentValidation; using NzbDrone.Core.Annotations; using NzbDrone.Core.Validation; -using System.Text.RegularExpressions; namespace NzbDrone.Core.Indexers.Nyaa { diff --git a/src/NzbDrone.Core/Indexers/Omgwtfnzbs/Omgwtfnzbs.cs b/src/NzbDrone.Core/Indexers/Omgwtfnzbs/Omgwtfnzbs.cs index d957b5cbd..e4f1bb56b 100644 --- a/src/NzbDrone.Core/Indexers/Omgwtfnzbs/Omgwtfnzbs.cs +++ b/src/NzbDrone.Core/Indexers/Omgwtfnzbs/Omgwtfnzbs.cs @@ -14,7 +14,6 @@ public class Omgwtfnzbs : HttpIndexerBase public Omgwtfnzbs(IHttpClient httpClient, IIndexerStatusService indexerStatusService, IConfigService configService, IParsingService parsingService, Logger logger) : base(httpClient, indexerStatusService, configService, parsingService, logger) { - } public override IIndexerRequestGenerator GetRequestGenerator() diff --git a/src/NzbDrone.Core/Indexers/Omgwtfnzbs/OmgwtfnzbsRssParser.cs b/src/NzbDrone.Core/Indexers/Omgwtfnzbs/OmgwtfnzbsRssParser.cs index a5946e5ff..1f2453f61 100644 --- a/src/NzbDrone.Core/Indexers/Omgwtfnzbs/OmgwtfnzbsRssParser.cs +++ b/src/NzbDrone.Core/Indexers/Omgwtfnzbs/OmgwtfnzbsRssParser.cs @@ -1,4 +1,4 @@ -using System.Linq; +using System.Linq; using System.Text.RegularExpressions; using System.Xml.Linq; using NzbDrone.Common.Extensions; @@ -19,9 +19,15 @@ protected override bool PreProcess(IndexerResponse indexerResponse) var xdoc = LoadXmlDocument(indexerResponse); var notice = xdoc.Descendants("notice").FirstOrDefault(); - if (notice == null) return true; + if (notice == null) + { + return true; + } - if (!notice.Value.ContainsIgnoreCase("api")) return true; + if (!notice.Value.ContainsIgnoreCase("api")) + { + return true; + } throw new ApiKeyException(notice.Value); } @@ -29,8 +35,9 @@ protected override bool PreProcess(IndexerResponse indexerResponse) protected override string GetInfoUrl(XElement item) { //Todo: Me thinks I need to parse details to get this... - var match = Regex.Match(item.Description(), @"(?:\View NZB\:\<\/b\>\s\.+)(?:\""\starget)", - RegexOptions.IgnoreCase | RegexOptions.Compiled); + var match = Regex.Match(item.Description(), + @"(?:\View NZB\:\<\/b\>\s\.+)(?:\""\starget)", + RegexOptions.IgnoreCase | RegexOptions.Compiled); if (match.Success) { @@ -40,4 +47,4 @@ protected override string GetInfoUrl(XElement item) return string.Empty; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Indexers/Rarbg/Rarbg.cs b/src/NzbDrone.Core/Indexers/Rarbg/Rarbg.cs index 049809dce..632ec43f7 100644 --- a/src/NzbDrone.Core/Indexers/Rarbg/Rarbg.cs +++ b/src/NzbDrone.Core/Indexers/Rarbg/Rarbg.cs @@ -62,7 +62,7 @@ public override object RequestAction(string action, IDictionary siteKey = ex.CaptchaRequest.SiteKey, secretToken = ex.CaptchaRequest.SecretToken, responseUrl = ex.CaptchaRequest.ResponseUrl.FullUri, - } + } }; } @@ -109,4 +109,4 @@ public override object RequestAction(string action, IDictionary return new { }; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Indexers/Rarbg/RarbgParser.cs b/src/NzbDrone.Core/Indexers/Rarbg/RarbgParser.cs index 5dca6bf70..c7c886093 100644 --- a/src/NzbDrone.Core/Indexers/Rarbg/RarbgParser.cs +++ b/src/NzbDrone.Core/Indexers/Rarbg/RarbgParser.cs @@ -22,6 +22,7 @@ public IList ParseResponse(IndexerResponse indexerResponse) { throw new IndexerException(indexerResponse, "Indexer API call returned an unexpected StatusCode [{0}]", indexerResponse.HttpResponse.StatusCode); } + break; } @@ -88,6 +89,5 @@ private string GetGuid(RarbgTorrent torrent) return string.Format("rarbg-{0}", torrent.download); } } - } } diff --git a/src/NzbDrone.Core/Indexers/Rarbg/RarbgTokenProvider.cs b/src/NzbDrone.Core/Indexers/Rarbg/RarbgTokenProvider.cs index 628faac41..a17c19d74 100644 --- a/src/NzbDrone.Core/Indexers/Rarbg/RarbgTokenProvider.cs +++ b/src/NzbDrone.Core/Indexers/Rarbg/RarbgTokenProvider.cs @@ -27,7 +27,8 @@ public RarbgTokenProvider(IHttpClient httpClient, ICacheManager cacheManager, Lo public string GetToken(RarbgSettings settings) { - return _tokenCache.Get(settings.BaseUrl, () => + return _tokenCache.Get(settings.BaseUrl, + () => { var requestBuilder = new HttpRequestBuilder(settings.BaseUrl.Trim('/')) .WithRateLimit(3.0) diff --git a/src/NzbDrone.Core/Indexers/RssIndexerRequestGenerator.cs b/src/NzbDrone.Core/Indexers/RssIndexerRequestGenerator.cs index c6b4c57d8..5be7f884e 100644 --- a/src/NzbDrone.Core/Indexers/RssIndexerRequestGenerator.cs +++ b/src/NzbDrone.Core/Indexers/RssIndexerRequestGenerator.cs @@ -12,7 +12,6 @@ public RssIndexerRequestGenerator(string baseUrl) _baseUrl = baseUrl; } - public virtual IndexerPageableRequestChain GetRecentRequests() { var pageableRequests = new IndexerPageableRequestChain(); diff --git a/src/NzbDrone.Core/Indexers/RssParser.cs b/src/NzbDrone.Core/Indexers/RssParser.cs index 91e8c19da..d6260b012 100644 --- a/src/NzbDrone.Core/Indexers/RssParser.cs +++ b/src/NzbDrone.Core/Indexers/RssParser.cs @@ -230,6 +230,7 @@ protected virtual long GetSize(XElement item) { return GetEnclosureLength(item); } + if (ParseSizeInDescription && item.Element("description") != null) { return ParseSize(item.Element("description").Value, true); @@ -392,6 +393,7 @@ public static long ParseSize(string sizeString, bool defaultToBinaryPrefix) return (long)value; } } + return 0; } diff --git a/src/NzbDrone.Core/Indexers/RssSyncCommand.cs b/src/NzbDrone.Core/Indexers/RssSyncCommand.cs index 308a9de2e..47b9cca67 100644 --- a/src/NzbDrone.Core/Indexers/RssSyncCommand.cs +++ b/src/NzbDrone.Core/Indexers/RssSyncCommand.cs @@ -4,7 +4,6 @@ namespace NzbDrone.Core.Indexers { public class RssSyncCommand : Command { - public override bool SendUpdatesToClient => true; } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Indexers/RssSyncService.cs b/src/NzbDrone.Core/Indexers/RssSyncService.cs index 27c0256e4..8f4a07a04 100644 --- a/src/NzbDrone.Core/Indexers/RssSyncService.cs +++ b/src/NzbDrone.Core/Indexers/RssSyncService.cs @@ -39,7 +39,6 @@ public RssSyncService(IIndexerStatusService indexerStatusService, _logger = logger; } - private ProcessedDecisions Sync() { _logger.ProgressInfo("Starting RSS Sync"); diff --git a/src/NzbDrone.Core/Indexers/SeedConfigProvider.cs b/src/NzbDrone.Core/Indexers/SeedConfigProvider.cs index 7dc44de98..2d1412a7d 100644 --- a/src/NzbDrone.Core/Indexers/SeedConfigProvider.cs +++ b/src/NzbDrone.Core/Indexers/SeedConfigProvider.cs @@ -1,7 +1,7 @@ using System; using System.Linq; -using NzbDrone.Common.Extensions; using NzbDrone.Common.Cache; +using NzbDrone.Common.Extensions; using NzbDrone.Core.Datastore; using NzbDrone.Core.Download.Clients; using NzbDrone.Core.Messaging.Events; @@ -29,20 +29,33 @@ public SeedConfigProvider(IIndexerFactory indexerFactory, ICacheManager cacheMan public TorrentSeedConfiguration GetSeedConfiguration(RemoteEpisode remoteEpisode) { - if (remoteEpisode.Release.DownloadProtocol != DownloadProtocol.Torrent) return null; - if (remoteEpisode.Release.IndexerId == 0) return null; + if (remoteEpisode.Release.DownloadProtocol != DownloadProtocol.Torrent) + { + return null; + } + + if (remoteEpisode.Release.IndexerId == 0) + { + return null; + } return GetSeedConfiguration(remoteEpisode.Release.IndexerId, remoteEpisode.ParsedEpisodeInfo.FullSeason); } public TorrentSeedConfiguration GetSeedConfiguration(int indexerId, bool fullSeason) { - if (indexerId == 0) return null; + if (indexerId == 0) + { + return null; + } var seedCriteria = _cache.Get(indexerId.ToString(), () => FetchSeedCriteria(indexerId)); - if (seedCriteria == null) return null; - + if (seedCriteria == null) + { + return null; + } + var seedConfig = new TorrentSeedConfiguration { Ratio = seedCriteria.SeedRatio diff --git a/src/NzbDrone.Core/Indexers/TorrentRss/TorrentRssIndexerSettings.cs b/src/NzbDrone.Core/Indexers/TorrentRss/TorrentRssIndexerSettings.cs index ac37fba1c..3e158482e 100644 --- a/src/NzbDrone.Core/Indexers/TorrentRss/TorrentRssIndexerSettings.cs +++ b/src/NzbDrone.Core/Indexers/TorrentRss/TorrentRssIndexerSettings.cs @@ -1,4 +1,4 @@ -using FluentValidation; +using FluentValidation; using NzbDrone.Core.Annotations; using NzbDrone.Core.Validation; @@ -16,7 +16,7 @@ public TorrentRssIndexerSettingsValidator() public class TorrentRssIndexerSettings : ITorrentIndexerSettings { - private static readonly TorrentRssIndexerSettingsValidator validator = new TorrentRssIndexerSettingsValidator(); + private static readonly TorrentRssIndexerSettingsValidator Validator = new TorrentRssIndexerSettingsValidator(); public TorrentRssIndexerSettings() { @@ -42,7 +42,7 @@ public TorrentRssIndexerSettings() public NzbDroneValidationResult Validate() { - return new NzbDroneValidationResult(validator.Validate(this)); + return new NzbDroneValidationResult(Validator.Validate(this)); } } } diff --git a/src/NzbDrone.Core/Indexers/TorrentRss/TorrentRssParserFactory.cs b/src/NzbDrone.Core/Indexers/TorrentRss/TorrentRssParserFactory.cs index a60e3cd9c..d7b58cda7 100644 --- a/src/NzbDrone.Core/Indexers/TorrentRss/TorrentRssParserFactory.cs +++ b/src/NzbDrone.Core/Indexers/TorrentRss/TorrentRssParserFactory.cs @@ -14,7 +14,7 @@ public interface ITorrentRssParserFactory public class TorrentRssParserFactory : ITorrentRssParserFactory { protected readonly Logger _logger; - + private readonly ICached _settingsCache; private readonly ITorrentRssSettingsDetector _torrentRssSettingsDetector; diff --git a/src/NzbDrone.Core/Indexers/TorrentRss/TorrentRssSettingsDetector.cs b/src/NzbDrone.Core/Indexers/TorrentRss/TorrentRssSettingsDetector.cs index 53ee117cc..faeb40808 100644 --- a/src/NzbDrone.Core/Indexers/TorrentRss/TorrentRssSettingsDetector.cs +++ b/src/NzbDrone.Core/Indexers/TorrentRss/TorrentRssSettingsDetector.cs @@ -1,6 +1,6 @@ -using System; -using System.Linq; +using System; using System.IO; +using System.Linq; using System.Text.RegularExpressions; using System.Xml; using System.Xml.Linq; @@ -19,12 +19,12 @@ public interface ITorrentRssSettingsDetector public class TorrentRssSettingsDetector : ITorrentRssSettingsDetector { + private const long ValidSizeThreshold = 2 * 1024 * 1024; + protected readonly Logger _logger; private readonly IHttpClient _httpClient; - private const long ValidSizeThreshold = 2 * 1024 * 1024; - public TorrentRssSettingsDetector(IHttpClient httpClient, Logger logger) { _httpClient = httpClient; @@ -183,6 +183,7 @@ private TorrentRssIndexerParserSettings GetGenericTorrentRssParserSettings(Index { _logger.Debug("Feed {0} contains very small releases.", response.Request.Url); } + _logger.Trace("Feed has valid size in description."); return settings; } @@ -244,7 +245,6 @@ private TorrentInfo[] ParseResponse(IParseIndexerResponse parser, IndexerRespons { var releases = parser.ParseResponse(response).Cast().ToArray(); return releases; - } catch (Exception ex) { @@ -279,7 +279,6 @@ private void ValidateReleases(TorrentInfo[] releases, TorrentRssIndexerSettings if (distinct.Length != total.Length) { - throw new UnsupportedFeedException("Feed contains releases with same guid, rejecting malformed rss feed."); } } diff --git a/src/NzbDrone.Core/Indexers/TorrentRssParser.cs b/src/NzbDrone.Core/Indexers/TorrentRssParser.cs index f73598af0..991f53c8a 100644 --- a/src/NzbDrone.Core/Indexers/TorrentRssParser.cs +++ b/src/NzbDrone.Core/Indexers/TorrentRssParser.cs @@ -1,4 +1,4 @@ -using System.Collections.Generic; +using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using System.Xml.Linq; @@ -65,6 +65,7 @@ protected override ReleaseInfo ProcessItem(XElement item, ReleaseInfo releaseInf { result.Peers = GetPeers(item); } + return result; } @@ -74,7 +75,7 @@ protected virtual string GetInfoHash(XElement item) { return item.FindDecendants(InfoHashElementName).FirstOrDefault().Value; } - + var magnetUrl = GetMagnetUrl(item); if (magnetUrl.IsNotNullOrWhiteSpace()) @@ -135,6 +136,7 @@ protected virtual string GetMagnetUrl(XElement item) return int.Parse(matchPeers.Groups["value"].Value) - int.Parse(matchLeechers.Groups["value"].Value); } } + var seeds = item.FindDecendants(SeedsElementName).SingleOrDefault(); if (seeds != null) { @@ -184,6 +186,7 @@ protected override long GetSize(XElement item) size = ParseSize(itemsize.Value, true); } } + return size; } diff --git a/src/NzbDrone.Core/Indexers/Torrentleech/Torrentleech.cs b/src/NzbDrone.Core/Indexers/Torrentleech/Torrentleech.cs index 5c7620a1a..fc3a46bc2 100644 --- a/src/NzbDrone.Core/Indexers/Torrentleech/Torrentleech.cs +++ b/src/NzbDrone.Core/Indexers/Torrentleech/Torrentleech.cs @@ -1,7 +1,7 @@ -using NzbDrone.Common.Http; +using NLog; +using NzbDrone.Common.Http; using NzbDrone.Core.Configuration; using NzbDrone.Core.Parser; -using NLog; namespace NzbDrone.Core.Indexers.Torrentleech { @@ -16,7 +16,6 @@ public class Torrentleech : HttpIndexerBase public Torrentleech(IHttpClient httpClient, IIndexerStatusService indexerStatusService, IConfigService configService, IParsingService parsingService, Logger logger) : base(httpClient, indexerStatusService, configService, parsingService, logger) { - } public override IIndexerRequestGenerator GetRequestGenerator() diff --git a/src/NzbDrone.Core/Indexers/Torznab/TorznabException.cs b/src/NzbDrone.Core/Indexers/Torznab/TorznabException.cs index 258a12492..4c8836a88 100644 --- a/src/NzbDrone.Core/Indexers/Torznab/TorznabException.cs +++ b/src/NzbDrone.Core/Indexers/Torznab/TorznabException.cs @@ -4,11 +4,13 @@ namespace NzbDrone.Core.Indexers.Torznab { public class TorznabException : NzbDroneException { - public TorznabException(string message, params object[] args) : base(message, args) + public TorznabException(string message, params object[] args) + : base(message, args) { } - public TorznabException(string message) : base(message) + public TorznabException(string message) + : base(message) { } } diff --git a/src/NzbDrone.Core/Indexers/Torznab/TorznabRssParser.cs b/src/NzbDrone.Core/Indexers/Torznab/TorznabRssParser.cs index 35d0f76c3..31322cf1f 100644 --- a/src/NzbDrone.Core/Indexers/Torznab/TorznabRssParser.cs +++ b/src/NzbDrone.Core/Indexers/Torznab/TorznabRssParser.cs @@ -22,12 +22,18 @@ protected override bool PreProcess(IndexerResponse indexerResponse) var xdoc = LoadXmlDocument(indexerResponse); var error = xdoc.Descendants("error").FirstOrDefault(); - if (error == null) return true; + if (error == null) + { + return true; + } var code = Convert.ToInt32(error.Attribute("code").Value); var errorMessage = error.Attribute("description").Value; - if (code >= 100 && code <= 199) throw new ApiKeyException("Invalid API key"); + if (code >= 100 && code <= 199) + { + throw new ApiKeyException("Invalid API key"); + } if (!indexerResponse.Request.Url.FullUri.Contains("apikey=") && errorMessage == "Missing parameter") { @@ -137,6 +143,7 @@ protected virtual int GetTvRageId(XElement item) return 0; } + protected override string GetInfoHash(XElement item) { return TryGetTorznabAttribute(item, "infohash"); diff --git a/src/NzbDrone.Core/Indexers/XElementExtensions.cs b/src/NzbDrone.Core/Indexers/XElementExtensions.cs index ef2b8b064..a90dbed85 100644 --- a/src/NzbDrone.Core/Indexers/XElementExtensions.cs +++ b/src/NzbDrone.Core/Indexers/XElementExtensions.cs @@ -27,8 +27,7 @@ public static XElement StripNameSpace(this XElement root) root.Name.LocalName, root.HasElements ? root.Elements().Select(StripNameSpace) : - (object)root.Value - ); + (object)root.Value); res.ReplaceAttributes( root.Attributes().Where(attr => (!attr.IsNamespaceDeclaration))); @@ -46,6 +45,7 @@ public static DateTime ParseDate(string dateString) dateString = RemoveTimeZoneRegex.Replace(dateString, ""); result = DateTime.Parse(dateString, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AssumeUniversal); } + return result.ToUniversalTime(); } catch (FormatException e) @@ -109,7 +109,6 @@ public static T TryGetValue(this XElement item, string elementName, T default { return (T)Convert.ChangeType(element.Value, typeof(T)); } - catch (InvalidCastException) { return defaultValue; diff --git a/src/NzbDrone.Core/Indexers/XmlCleaner.cs b/src/NzbDrone.Core/Indexers/XmlCleaner.cs index 91d0ea3b1..f2c5de388 100644 --- a/src/NzbDrone.Core/Indexers/XmlCleaner.cs +++ b/src/NzbDrone.Core/Indexers/XmlCleaner.cs @@ -6,7 +6,6 @@ namespace NzbDrone.Core.Indexers { public static class XmlCleaner { - private static readonly Regex ReplaceEntitiesRegex = new Regex("&[a-z]+;", RegexOptions.Compiled | RegexOptions.IgnoreCase); private static readonly Regex ReplaceUnicodeRegex = new Regex(@"[^\x09\x0A\x0D\u0020-\uD7FF\uE000-\uFFFD]", RegexOptions.Compiled | RegexOptions.IgnoreCase); diff --git a/src/NzbDrone.Core/Instrumentation/Commands/ClearLogCommand.cs b/src/NzbDrone.Core/Instrumentation/Commands/ClearLogCommand.cs index f8eb71ee7..80463075c 100644 --- a/src/NzbDrone.Core/Instrumentation/Commands/ClearLogCommand.cs +++ b/src/NzbDrone.Core/Instrumentation/Commands/ClearLogCommand.cs @@ -6,4 +6,4 @@ public class ClearLogCommand : Command { public override bool SendUpdatesToClient => true; } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Instrumentation/Commands/DeleteLogFilesCommand.cs b/src/NzbDrone.Core/Instrumentation/Commands/DeleteLogFilesCommand.cs index 7676baa52..1cc1712d2 100644 --- a/src/NzbDrone.Core/Instrumentation/Commands/DeleteLogFilesCommand.cs +++ b/src/NzbDrone.Core/Instrumentation/Commands/DeleteLogFilesCommand.cs @@ -6,4 +6,4 @@ public class DeleteLogFilesCommand : Command { public override bool SendUpdatesToClient => true; } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Instrumentation/Commands/DeleteUpdateLogFilesCommand.cs b/src/NzbDrone.Core/Instrumentation/Commands/DeleteUpdateLogFilesCommand.cs index 5a909bdf6..97fa8d456 100644 --- a/src/NzbDrone.Core/Instrumentation/Commands/DeleteUpdateLogFilesCommand.cs +++ b/src/NzbDrone.Core/Instrumentation/Commands/DeleteUpdateLogFilesCommand.cs @@ -6,4 +6,4 @@ public class DeleteUpdateLogFilesCommand : Command { public override bool SendUpdatesToClient => true; } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Instrumentation/DatabaseTarget.cs b/src/NzbDrone.Core/Instrumentation/DatabaseTarget.cs index c55aa90cc..1a7c8a241 100644 --- a/src/NzbDrone.Core/Instrumentation/DatabaseTarget.cs +++ b/src/NzbDrone.Core/Instrumentation/DatabaseTarget.cs @@ -1,8 +1,8 @@ -using System.Data; +using System.Data; using System.Data.SQLite; +using NLog; using NLog.Common; using NLog.Config; -using NLog; using NLog.Targets; using NzbDrone.Common.Instrumentation; using NzbDrone.Core.Datastore; @@ -13,10 +13,10 @@ namespace NzbDrone.Core.Instrumentation { public class DatabaseTarget : TargetWithLayout, IHandle { - private readonly SQLiteConnection _connection; + private const string INSERT_COMMAND = "INSERT INTO [Logs]([Message],[Time],[Logger],[Exception],[ExceptionType],[Level]) " + + "VALUES(@Message,@Time,@Logger,@Exception,@ExceptionType,@Level)"; - const string INSERT_COMMAND = "INSERT INTO [Logs]([Message],[Time],[Logger],[Exception],[ExceptionType],[Level]) " + - "VALUES(@Message,@Time,@Logger,@Exception,@ExceptionType,@Level)"; + private readonly SQLiteConnection _connection; public DatabaseTarget(IConnectionStringFactory connectionStringFactory) { @@ -110,4 +110,4 @@ public void Handle(ApplicationShutdownRequested message) } } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Instrumentation/Log.cs b/src/NzbDrone.Core/Instrumentation/Log.cs index 6410ab6e9..91e4710b0 100644 --- a/src/NzbDrone.Core/Instrumentation/Log.cs +++ b/src/NzbDrone.Core/Instrumentation/Log.cs @@ -1,12 +1,10 @@ using System; using NzbDrone.Core.Datastore; - namespace NzbDrone.Core.Instrumentation { public class Log : ModelBase { - public string Message { get; set; } public DateTime Time { get; set; } @@ -19,4 +17,4 @@ public class Log : ModelBase public string Level { get; set; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Instrumentation/LogRepository.cs b/src/NzbDrone.Core/Instrumentation/LogRepository.cs index 97bfe9f79..69bcbe474 100644 --- a/src/NzbDrone.Core/Instrumentation/LogRepository.cs +++ b/src/NzbDrone.Core/Instrumentation/LogRepository.cs @@ -2,7 +2,6 @@ using NzbDrone.Core.Datastore; using NzbDrone.Core.Messaging.Events; - namespace NzbDrone.Core.Instrumentation { public interface ILogRepository : IBasicRepository @@ -24,4 +23,4 @@ public void Trim() Vacuum(); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Instrumentation/LogService.cs b/src/NzbDrone.Core/Instrumentation/LogService.cs index f0727e859..c12a65694 100644 --- a/src/NzbDrone.Core/Instrumentation/LogService.cs +++ b/src/NzbDrone.Core/Instrumentation/LogService.cs @@ -28,4 +28,4 @@ public void Execute(ClearLogCommand message) _logRepository.Purge(vacuum: true); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Instrumentation/ReconfigureLogging.cs b/src/NzbDrone.Core/Instrumentation/ReconfigureLogging.cs index fc9208e16..db8ea0d2f 100644 --- a/src/NzbDrone.Core/Instrumentation/ReconfigureLogging.cs +++ b/src/NzbDrone.Core/Instrumentation/ReconfigureLogging.cs @@ -28,11 +28,17 @@ public void Reconfigure() LogLevel minimumConsoleLogLevel; if (_configFileProvider.ConsoleLogLevel.IsNotNullOrWhiteSpace()) + { minimumConsoleLogLevel = LogLevel.FromString(_configFileProvider.ConsoleLogLevel); + } else if (minimumLogLevel > LogLevel.Info) + { minimumConsoleLogLevel = minimumLogLevel; + } else + { minimumConsoleLogLevel = LogLevel.Info; + } if (_configFileProvider.SyslogServer.IsNotNullOrWhiteSpace()) { @@ -72,7 +78,6 @@ private void SetMinimumLogLevel(LoggingRule rule, LogLevel minimumLogLevel) { rule.DisableLoggingForLevel(logLevel); } - else { rule.EnableLoggingForLevel(logLevel); @@ -85,7 +90,7 @@ private void ReconfigureSentry() var sentryTarget = LogManager.Configuration.AllTargets.OfType().FirstOrDefault(); if (sentryTarget != null) { - sentryTarget.SentryEnabled = RuntimeInfo.IsProduction && _configFileProvider.AnalyticsEnabled || RuntimeInfo.IsDevelopment; + sentryTarget.SentryEnabled = (RuntimeInfo.IsProduction && _configFileProvider.AnalyticsEnabled) || RuntimeInfo.IsDevelopment; } } diff --git a/src/NzbDrone.Core/Instrumentation/SlowRunningAsyncTargetWrapper.cs b/src/NzbDrone.Core/Instrumentation/SlowRunningAsyncTargetWrapper.cs index 994aedc50..27151fd7f 100644 --- a/src/NzbDrone.Core/Instrumentation/SlowRunningAsyncTargetWrapper.cs +++ b/src/NzbDrone.Core/Instrumentation/SlowRunningAsyncTargetWrapper.cs @@ -13,7 +13,6 @@ public class SlowRunningAsyncTargetWrapper : AsyncTargetWrapper public SlowRunningAsyncTargetWrapper(Target wrappedTarget) : base(wrappedTarget) { - } protected override void StopLazyWriterThread() diff --git a/src/NzbDrone.Core/Jobs/ScheduledTask.cs b/src/NzbDrone.Core/Jobs/ScheduledTask.cs index 3547dcf62..31b209410 100644 --- a/src/NzbDrone.Core/Jobs/ScheduledTask.cs +++ b/src/NzbDrone.Core/Jobs/ScheduledTask.cs @@ -16,4 +16,4 @@ public ScheduledTask() Priority = CommandPriority.Low; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Jobs/ScheduledTaskRepository.cs b/src/NzbDrone.Core/Jobs/ScheduledTaskRepository.cs index 648ca0450..73821e932 100644 --- a/src/NzbDrone.Core/Jobs/ScheduledTaskRepository.cs +++ b/src/NzbDrone.Core/Jobs/ScheduledTaskRepository.cs @@ -3,7 +3,6 @@ using NzbDrone.Core.Datastore; using NzbDrone.Core.Messaging.Events; - namespace NzbDrone.Core.Jobs { public interface IScheduledTaskRepository : IBasicRepository @@ -14,7 +13,6 @@ public interface IScheduledTaskRepository : IBasicRepository public class ScheduledTaskRepository : BasicRepository, IScheduledTaskRepository { - public ScheduledTaskRepository(IMainDatabase database, IEventAggregator eventAggregator) : base(database, eventAggregator) { diff --git a/src/NzbDrone.Core/Jobs/Scheduler.cs b/src/NzbDrone.Core/Jobs/Scheduler.cs index c55035597..ee0940dc9 100644 --- a/src/NzbDrone.Core/Jobs/Scheduler.cs +++ b/src/NzbDrone.Core/Jobs/Scheduler.cs @@ -2,11 +2,11 @@ using System.Threading; using System.Threading.Tasks; using NLog; +using NzbDrone.Common.TPL; using NzbDrone.Core.Lifecycle; using NzbDrone.Core.Messaging.Commands; using NzbDrone.Core.Messaging.Events; using Timer = System.Timers.Timer; -using NzbDrone.Common.TPL; namespace NzbDrone.Core.Jobs { @@ -42,7 +42,6 @@ private void ExecuteCommands() _commandQueueManager.Push(task.TypeName, task.LastExecution, task.Priority, CommandTrigger.Scheduled); } } - finally { if (!_cancellationTokenSource.IsCancellationRequested) @@ -69,4 +68,4 @@ public void Handle(ApplicationShutdownRequested message) Timer.Stop(); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Jobs/TaskManager.cs b/src/NzbDrone.Core/Jobs/TaskManager.cs index de7ab3222..2bcae4bac 100644 --- a/src/NzbDrone.Core/Jobs/TaskManager.cs +++ b/src/NzbDrone.Core/Jobs/TaskManager.cs @@ -128,7 +128,7 @@ public void Handle(ApplicationStartedEvent message) }, new ScheduledTask - { + { Interval = GetRssSyncInterval(), TypeName = typeof(RssSyncCommand).FullName } @@ -222,7 +222,7 @@ public void HandleAsync(ConfigSavedEvent message) var backup = _scheduledTaskRepository.GetDefinition(typeof(BackupCommand)); backup.Interval = GetBackupInterval(); - _scheduledTaskRepository.UpdateMany(new List{ rss, backup }); + _scheduledTaskRepository.UpdateMany(new List { rss, backup }); _cache.Find(rss.TypeName).Interval = rss.Interval; _cache.Find(backup.TypeName).Interval = backup.Interval; diff --git a/src/NzbDrone.Core/Languages/Language.cs b/src/NzbDrone.Core/Languages/Language.cs index 64866ee7f..c276bda3b 100644 --- a/src/NzbDrone.Core/Languages/Language.cs +++ b/src/NzbDrone.Core/Languages/Language.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using NzbDrone.Core.Datastore; @@ -32,15 +32,30 @@ public override int GetHashCode() public bool Equals(Language other) { - if (ReferenceEquals(null, other)) return false; - if (ReferenceEquals(this, other)) return true; + if (ReferenceEquals(null, other)) + { + return false; + } + + if (ReferenceEquals(this, other)) + { + return true; + } + return Id.Equals(other.Id); } public override bool Equals(object obj) { - if (ReferenceEquals(null, obj)) return false; - if (ReferenceEquals(this, obj)) return true; + if (ReferenceEquals(null, obj)) + { + return false; + } + + if (ReferenceEquals(this, obj)) + { + return true; + } return Equals(obj as Language); } @@ -55,38 +70,37 @@ public override bool Equals(object obj) return !Equals(left, right); } - public static Language Unknown { get { return new Language(0, "Unknown"); } } - public static Language English { get { return new Language(1, "English"); } } - public static Language French { get { return new Language(2, "French"); } } - public static Language Spanish { get { return new Language(3, "Spanish"); } } - public static Language German { get { return new Language(4, "German"); } } - public static Language Italian { get { return new Language(5, "Italian"); } } - public static Language Danish { get { return new Language(6, "Danish"); } } - public static Language Dutch { get { return new Language(7, "Dutch"); } } - public static Language Japanese { get { return new Language(8, "Japanese"); } } - public static Language Icelandic { get { return new Language(9, "Icelandic"); } } - public static Language Chinese { get { return new Language(10, "Chinese"); } } - public static Language Russian { get { return new Language(11, "Russian"); } } - public static Language Polish { get { return new Language(12, "Polish"); } } - public static Language Vietnamese { get { return new Language(13, "Vietnamese"); } } - public static Language Swedish { get { return new Language(14, "Swedish"); } } - public static Language Norwegian { get { return new Language(15, "Norwegian"); } } - public static Language Finnish { get { return new Language(16, "Finnish"); } } - public static Language Turkish { get { return new Language(17, "Turkish"); } } - public static Language Portuguese { get { return new Language(18, "Portuguese"); } } - public static Language Flemish { get { return new Language(19, "Flemish"); } } - public static Language Greek { get { return new Language(20, "Greek"); } } - public static Language Korean { get { return new Language(21, "Korean"); } } - public static Language Hungarian { get { return new Language(22, "Hungarian"); } } - public static Language Hebrew { get { return new Language(23, "Hebrew"); } } - public static Language Lithuanian { get { return new Language(24, "Lithuanian"); } } - public static Language Czech { get { return new Language(25, "Czech"); } } - public static Language Arabic { get { return new Language(26, "Arabic"); } } - public static Language Hindi { get { return new Language(27, "Hindi"); } } - public static Language Bulgarian { get { return new Language(28, "Bulgarian"); } } - public static Language Malayalam { get { return new Language(29, "Malayalam"); } } - public static Language Ukrainian { get { return new Language(30, "Ukrainian"); } } - + public static Language Unknown => new Language(0, "Unknown"); + public static Language English => new Language(1, "English"); + public static Language French => new Language(2, "French"); + public static Language Spanish => new Language(3, "Spanish"); + public static Language German => new Language(4, "German"); + public static Language Italian => new Language(5, "Italian"); + public static Language Danish => new Language(6, "Danish"); + public static Language Dutch => new Language(7, "Dutch"); + public static Language Japanese => new Language(8, "Japanese"); + public static Language Icelandic => new Language(9, "Icelandic"); + public static Language Chinese => new Language(10, "Chinese"); + public static Language Russian => new Language(11, "Russian"); + public static Language Polish => new Language(12, "Polish"); + public static Language Vietnamese => new Language(13, "Vietnamese"); + public static Language Swedish => new Language(14, "Swedish"); + public static Language Norwegian => new Language(15, "Norwegian"); + public static Language Finnish => new Language(16, "Finnish"); + public static Language Turkish => new Language(17, "Turkish"); + public static Language Portuguese => new Language(18, "Portuguese"); + public static Language Flemish => new Language(19, "Flemish"); + public static Language Greek => new Language(20, "Greek"); + public static Language Korean => new Language(21, "Korean"); + public static Language Hungarian => new Language(22, "Hungarian"); + public static Language Hebrew => new Language(23, "Hebrew"); + public static Language Lithuanian => new Language(24, "Lithuanian"); + public static Language Czech => new Language(25, "Czech"); + public static Language Arabic => new Language(26, "Arabic"); + public static Language Hindi => new Language(27, "Hindi"); + public static Language Bulgarian => new Language(28, "Bulgarian"); + public static Language Malayalam => new Language(29, "Malayalam"); + public static Language Ukrainian => new Language(30, "Ukrainian"); public static List All { @@ -133,7 +147,10 @@ public static List All public static Language FindById(int id) { - if (id == 0) return Unknown; + if (id == 0) + { + return Unknown; + } if (!Lookup.TryGetValue(id, out var language)) { diff --git a/src/NzbDrone.Core/Lifecycle/ApplicationShutdownRequested.cs b/src/NzbDrone.Core/Lifecycle/ApplicationShutdownRequested.cs index 42d2f411e..7982c1d36 100644 --- a/src/NzbDrone.Core/Lifecycle/ApplicationShutdownRequested.cs +++ b/src/NzbDrone.Core/Lifecycle/ApplicationShutdownRequested.cs @@ -11,4 +11,4 @@ public ApplicationShutdownRequested(bool restarting = false) Restarting = restarting; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Lifecycle/ApplicationStartedEvent.cs b/src/NzbDrone.Core/Lifecycle/ApplicationStartedEvent.cs index f66622dd3..8e0d45e15 100644 --- a/src/NzbDrone.Core/Lifecycle/ApplicationStartedEvent.cs +++ b/src/NzbDrone.Core/Lifecycle/ApplicationStartedEvent.cs @@ -4,6 +4,5 @@ namespace NzbDrone.Core.Lifecycle { public class ApplicationStartedEvent : IEvent { - } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Lifecycle/ApplicationStartingEvent.cs b/src/NzbDrone.Core/Lifecycle/ApplicationStartingEvent.cs index 99aa40422..0fa838d76 100644 --- a/src/NzbDrone.Core/Lifecycle/ApplicationStartingEvent.cs +++ b/src/NzbDrone.Core/Lifecycle/ApplicationStartingEvent.cs @@ -4,6 +4,5 @@ namespace NzbDrone.Core.Lifecycle { public class ApplicationStartingEvent : IEvent { - } } diff --git a/src/NzbDrone.Core/Lifecycle/LifecycleService.cs b/src/NzbDrone.Core/Lifecycle/LifecycleService.cs index e4d727b0d..9ed36a42e 100644 --- a/src/NzbDrone.Core/Lifecycle/LifecycleService.cs +++ b/src/NzbDrone.Core/Lifecycle/LifecycleService.cs @@ -21,7 +21,6 @@ public class LifecycleService : ILifecycleService, IExecute, IE private readonly IServiceProvider _serviceProvider; private readonly Logger _logger; - public LifecycleService(IEventAggregator eventAggregator, IRuntimeInfo runtimeInfo, IServiceProvider serviceProvider, diff --git a/src/NzbDrone.Core/MediaCover/CoverAlreadyExistsSpecification.cs b/src/NzbDrone.Core/MediaCover/CoverAlreadyExistsSpecification.cs index 83f1e13de..a43075bfe 100644 --- a/src/NzbDrone.Core/MediaCover/CoverAlreadyExistsSpecification.cs +++ b/src/NzbDrone.Core/MediaCover/CoverAlreadyExistsSpecification.cs @@ -31,4 +31,4 @@ public bool AlreadyExists(string url, string path) return fileSize == headers.ContentLength; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/MediaCover/ImageResizer.cs b/src/NzbDrone.Core/MediaCover/ImageResizer.cs index d9855437c..a668659b1 100644 --- a/src/NzbDrone.Core/MediaCover/ImageResizer.cs +++ b/src/NzbDrone.Core/MediaCover/ImageResizer.cs @@ -35,7 +35,10 @@ public ImageResizer(IDiskProvider diskProvider, IPlatformInfo platformInfo) public void Resize(string source, string destination, int height) { - if (!_enabled) return; + if (!_enabled) + { + return; + } try { @@ -51,6 +54,7 @@ public void Resize(string source, string destination, int height) { _diskProvider.DeleteFile(destination); } + throw; } } diff --git a/src/NzbDrone.Core/MediaCover/MediaCover.cs b/src/NzbDrone.Core/MediaCover/MediaCover.cs index c521d9836..acea3ab42 100644 --- a/src/NzbDrone.Core/MediaCover/MediaCover.cs +++ b/src/NzbDrone.Core/MediaCover/MediaCover.cs @@ -2,7 +2,6 @@ namespace NzbDrone.Core.MediaCover { - public enum MediaCoverTypes { Unknown = 0, @@ -29,4 +28,4 @@ public MediaCover(MediaCoverTypes coverType, string url) Url = url; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/MediaCover/MediaCoverProxy.cs b/src/NzbDrone.Core/MediaCover/MediaCoverProxy.cs index 79344f004..ee58eb46b 100644 --- a/src/NzbDrone.Core/MediaCover/MediaCoverProxy.cs +++ b/src/NzbDrone.Core/MediaCover/MediaCoverProxy.cs @@ -1,12 +1,12 @@ -using NzbDrone.Common.Cache; -using NzbDrone.Common.Http; -using NzbDrone.Core.Configuration; -using System; +using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; +using NzbDrone.Common.Cache; +using NzbDrone.Common.Http; +using NzbDrone.Core.Configuration; namespace NzbDrone.Core.MediaCover { @@ -17,6 +17,7 @@ public interface IMediaCoverProxy string GetUrl(string hash); byte[] GetImage(string hash); } + public class MediaCoverProxy : IMediaCoverProxy { private readonly IHttpClient _httpClient; @@ -59,7 +60,7 @@ public byte[] GetImage(string hash) var url = GetUrl(hash); var request = new HttpRequest(url); - + return _httpClient.Get(request).ResponseData; } } diff --git a/src/NzbDrone.Core/MediaFiles/Commands/BackendCommandAttribute.cs b/src/NzbDrone.Core/MediaFiles/Commands/BackendCommandAttribute.cs index 7e8347897..9ba649e16 100644 --- a/src/NzbDrone.Core/MediaFiles/Commands/BackendCommandAttribute.cs +++ b/src/NzbDrone.Core/MediaFiles/Commands/BackendCommandAttribute.cs @@ -5,4 +5,4 @@ namespace NzbDrone.Core.MediaFiles.Commands public class BackendCommandAttribute : Attribute { } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/MediaFiles/Commands/CleanUpRecycleBinCommand.cs b/src/NzbDrone.Core/MediaFiles/Commands/CleanUpRecycleBinCommand.cs index cb8d8c3a6..15f687edd 100644 --- a/src/NzbDrone.Core/MediaFiles/Commands/CleanUpRecycleBinCommand.cs +++ b/src/NzbDrone.Core/MediaFiles/Commands/CleanUpRecycleBinCommand.cs @@ -5,4 +5,4 @@ namespace NzbDrone.Core.MediaFiles.Commands public class CleanUpRecycleBinCommand : Command { } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/MediaFiles/Commands/RescanSeriesCommand.cs b/src/NzbDrone.Core/MediaFiles/Commands/RescanSeriesCommand.cs index 6330574ab..e39d92055 100644 --- a/src/NzbDrone.Core/MediaFiles/Commands/RescanSeriesCommand.cs +++ b/src/NzbDrone.Core/MediaFiles/Commands/RescanSeriesCommand.cs @@ -17,4 +17,4 @@ public RescanSeriesCommand(int seriesId) SeriesId = seriesId; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/MediaFiles/DiskScanService.cs b/src/NzbDrone.Core/MediaFiles/DiskScanService.cs index a036e33c0..4910eadb9 100644 --- a/src/NzbDrone.Core/MediaFiles/DiskScanService.cs +++ b/src/NzbDrone.Core/MediaFiles/DiskScanService.cs @@ -110,7 +110,7 @@ public void Scan(Series series) else { _logger.Debug("Creating missing series folder: {0}", series.Path); - + _diskProvider.CreateFolder(series.Path); SetPermissions(series.Path); } @@ -152,7 +152,10 @@ public void Scan(Series series) var path = Path.Combine(series.Path, file.RelativePath); var fileSize = _diskProvider.GetFileSize(path); - if (file.Size == fileSize) continue; + if (file.Size == fileSize) + { + continue; + } file.Size = fileSize; @@ -273,7 +276,6 @@ public void Execute(RescanSeriesCommand message) var series = _seriesService.GetSeries(message.SeriesId.Value); Scan(series); } - else { var allSeries = _seriesService.GetAllSeries(); diff --git a/src/NzbDrone.Core/MediaFiles/DownloadedEpisodesCommandService.cs b/src/NzbDrone.Core/MediaFiles/DownloadedEpisodesCommandService.cs index 656a22b7f..8c75b196e 100644 --- a/src/NzbDrone.Core/MediaFiles/DownloadedEpisodesCommandService.cs +++ b/src/NzbDrone.Core/MediaFiles/DownloadedEpisodesCommandService.cs @@ -56,7 +56,7 @@ private List ProcessPath(DownloadedEpisodesScanCommand message) return importResults; } - + _logger.Warn("External directory scan request for unknown download {0}, attempting normal import. [{1}]", message.DownloadClientId, message.Path); } diff --git a/src/NzbDrone.Core/MediaFiles/EpisodeFile.cs b/src/NzbDrone.Core/MediaFiles/EpisodeFile.cs index c4da4cadd..1ae44efcd 100644 --- a/src/NzbDrone.Core/MediaFiles/EpisodeFile.cs +++ b/src/NzbDrone.Core/MediaFiles/EpisodeFile.cs @@ -1,12 +1,12 @@ using System; using System.Collections.Generic; using Marr.Data; +using NzbDrone.Common.Extensions; using NzbDrone.Core.Datastore; +using NzbDrone.Core.Languages; +using NzbDrone.Core.MediaFiles.MediaInfo; using NzbDrone.Core.Qualities; using NzbDrone.Core.Tv; -using NzbDrone.Core.MediaFiles.MediaInfo; -using NzbDrone.Common.Extensions; -using NzbDrone.Core.Languages; namespace NzbDrone.Core.MediaFiles { diff --git a/src/NzbDrone.Core/MediaFiles/EpisodeFileMovingService.cs b/src/NzbDrone.Core/MediaFiles/EpisodeFileMovingService.cs index 123d11484..43947c326 100644 --- a/src/NzbDrone.Core/MediaFiles/EpisodeFileMovingService.cs +++ b/src/NzbDrone.Core/MediaFiles/EpisodeFileMovingService.cs @@ -7,12 +7,12 @@ using NzbDrone.Common.EnsureThat; using NzbDrone.Common.Extensions; using NzbDrone.Core.Configuration; +using NzbDrone.Core.MediaFiles.EpisodeImport; using NzbDrone.Core.MediaFiles.Events; using NzbDrone.Core.Messaging.Events; using NzbDrone.Core.Organizer; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Tv; -using NzbDrone.Core.MediaFiles.EpisodeImport; namespace NzbDrone.Core.MediaFiles { @@ -130,7 +130,6 @@ private EpisodeFile TransferFile(EpisodeFile episodeFile, Series series, List scores) var matchingPairs = _preferredWordService.GetMatchingPreferredWordsAndScores(series, title, 0); - // Only add the score if there are matching terms + // Only add the score if there are matching terms if (matchingPairs.Any()) { score = matchingPairs.Sum(p => p.Value); diff --git a/src/NzbDrone.Core/MediaFiles/EpisodeImport/Aggregation/AggregationFailedException.cs b/src/NzbDrone.Core/MediaFiles/EpisodeImport/Aggregation/AggregationFailedException.cs index 948df4580..19ee2b4b3 100644 --- a/src/NzbDrone.Core/MediaFiles/EpisodeImport/Aggregation/AggregationFailedException.cs +++ b/src/NzbDrone.Core/MediaFiles/EpisodeImport/Aggregation/AggregationFailedException.cs @@ -5,19 +5,23 @@ namespace NzbDrone.Core.MediaFiles.EpisodeImport.Aggregation { public class AugmentingFailedException : NzbDroneException { - public AugmentingFailedException(string message, params object[] args) : base(message, args) + public AugmentingFailedException(string message, params object[] args) + : base(message, args) { } - public AugmentingFailedException(string message) : base(message) + public AugmentingFailedException(string message) + : base(message) { } - public AugmentingFailedException(string message, Exception innerException, params object[] args) : base(message, innerException, args) + public AugmentingFailedException(string message, Exception innerException, params object[] args) + : base(message, innerException, args) { } - public AugmentingFailedException(string message, Exception innerException) : base(message, innerException) + public AugmentingFailedException(string message, Exception innerException) + : base(message, innerException) { } } diff --git a/src/NzbDrone.Core/MediaFiles/EpisodeImport/Aggregation/Aggregators/AggregatePreferredWordScore.cs b/src/NzbDrone.Core/MediaFiles/EpisodeImport/Aggregation/Aggregators/AggregatePreferredWordScore.cs index feaf233b7..2b61a7731 100644 --- a/src/NzbDrone.Core/MediaFiles/EpisodeImport/Aggregation/Aggregators/AggregatePreferredWordScore.cs +++ b/src/NzbDrone.Core/MediaFiles/EpisodeImport/Aggregation/Aggregators/AggregatePreferredWordScore.cs @@ -28,7 +28,7 @@ public LocalEpisode Aggregate(LocalEpisode localEpisode, DownloadClientItem down { scores.Add(_preferredWordService.Calculate(series, localEpisode.SceneName, 0)); } - + localEpisode.PreferredWordScore = scores.MaxOrDefault(); return localEpisode; diff --git a/src/NzbDrone.Core/MediaFiles/EpisodeImport/Aggregation/Aggregators/AggregateQuality.cs b/src/NzbDrone.Core/MediaFiles/EpisodeImport/Aggregation/Aggregators/AggregateQuality.cs index a53f7f4e0..434663f5e 100644 --- a/src/NzbDrone.Core/MediaFiles/EpisodeImport/Aggregation/Aggregators/AggregateQuality.cs +++ b/src/NzbDrone.Core/MediaFiles/EpisodeImport/Aggregation/Aggregators/AggregateQuality.cs @@ -40,14 +40,14 @@ public LocalEpisode Aggregate(LocalEpisode localEpisode, DownloadClientItem down _logger.Trace("Considering Source {0} ({1}) Resolution {2} ({3}) Revision {4} from {5}", augmentedQuality.Source, augmentedQuality.SourceConfidence, augmentedQuality.Resolution, augmentedQuality.ResolutionConfidence, augmentedQuality.Revision, augmentQuality.Name); if (source == QualitySource.Unknown || - augmentedQuality.SourceConfidence > sourceConfidence && augmentedQuality.Source != QualitySource.Unknown) + (augmentedQuality.SourceConfidence > sourceConfidence && augmentedQuality.Source != QualitySource.Unknown)) { source = augmentedQuality.Source; sourceConfidence = augmentedQuality.SourceConfidence; } if (resolution == 0 || - augmentedQuality.ResolutionConfidence > resolutionConfidence && augmentedQuality.Resolution > 0) + (augmentedQuality.ResolutionConfidence > resolutionConfidence && augmentedQuality.Resolution > 0)) { resolution = augmentedQuality.Resolution; resolutionConfidence = augmentedQuality.ResolutionConfidence; @@ -62,6 +62,7 @@ public LocalEpisode Aggregate(LocalEpisode localEpisode, DownloadClientItem down revision = augmentedQuality.Revision; revisionConfidence = augmentedQuality.RevisionConfidence; } + // Update the revision and confidence if it is the same confidence and the revision is higher, // this will allow the best revision to be used in the event there is a disagreement. else if (augmentedQuality.RevisionConfidence == revisionConfidence && diff --git a/src/NzbDrone.Core/MediaFiles/EpisodeImport/Aggregation/Aggregators/AggregateReleaseGroup.cs b/src/NzbDrone.Core/MediaFiles/EpisodeImport/Aggregation/Aggregators/AggregateReleaseGroup.cs index a9eb67bc3..a8b1d1b8e 100644 --- a/src/NzbDrone.Core/MediaFiles/EpisodeImport/Aggregation/Aggregators/AggregateReleaseGroup.cs +++ b/src/NzbDrone.Core/MediaFiles/EpisodeImport/Aggregation/Aggregators/AggregateReleaseGroup.cs @@ -30,7 +30,7 @@ public LocalEpisode Aggregate(LocalEpisode localEpisode, DownloadClientItem down { releaseGroup = GetReleaseGroup(localEpisode.FolderEpisodeInfo, false); } - + localEpisode.ReleaseGroup = releaseGroup; return localEpisode; @@ -38,7 +38,7 @@ public LocalEpisode Aggregate(LocalEpisode localEpisode, DownloadClientItem down private string GetReleaseGroup(ParsedEpisodeInfo episodeInfo, bool skipFullSeason) { - if (episodeInfo == null || episodeInfo.FullSeason && skipFullSeason) + if (episodeInfo == null || (episodeInfo.FullSeason && skipFullSeason)) { return null; } diff --git a/src/NzbDrone.Core/MediaFiles/EpisodeImport/Aggregation/Aggregators/Augmenters/Quality/AugmentQualityFromMediaInfo.cs b/src/NzbDrone.Core/MediaFiles/EpisodeImport/Aggregation/Aggregators/Augmenters/Quality/AugmentQualityFromMediaInfo.cs index 71350f22e..ce90c9ff8 100644 --- a/src/NzbDrone.Core/MediaFiles/EpisodeImport/Aggregation/Aggregators/Augmenters/Quality/AugmentQualityFromMediaInfo.cs +++ b/src/NzbDrone.Core/MediaFiles/EpisodeImport/Aggregation/Aggregators/Augmenters/Quality/AugmentQualityFromMediaInfo.cs @@ -26,7 +26,6 @@ public AugmentQualityResult AugmentQuality(LocalEpisode localEpisode, DownloadCl var width = localEpisode.MediaInfo.Width; var height = localEpisode.MediaInfo.Height; - if (width >= 3200 || height >= 2100) { _logger.Trace("Resolution {0}x{1} considered 2160p", width, height); diff --git a/src/NzbDrone.Core/MediaFiles/EpisodeImport/ImportApprovedEpisodes.cs b/src/NzbDrone.Core/MediaFiles/EpisodeImport/ImportApprovedEpisodes.cs index ed646125c..62fc0e291 100644 --- a/src/NzbDrone.Core/MediaFiles/EpisodeImport/ImportApprovedEpisodes.cs +++ b/src/NzbDrone.Core/MediaFiles/EpisodeImport/ImportApprovedEpisodes.cs @@ -5,13 +5,13 @@ using NLog; using NzbDrone.Common.Disk; using NzbDrone.Common.Extensions; +using NzbDrone.Core.Download; +using NzbDrone.Core.Extras; +using NzbDrone.Core.Languages; using NzbDrone.Core.MediaFiles.Events; using NzbDrone.Core.Messaging.Events; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Qualities; -using NzbDrone.Core.Download; -using NzbDrone.Core.Extras; -using NzbDrone.Core.Languages; namespace NzbDrone.Core.MediaFiles.EpisodeImport { diff --git a/src/NzbDrone.Core/MediaFiles/EpisodeImport/ImportDecisionMaker.cs b/src/NzbDrone.Core/MediaFiles/EpisodeImport/ImportDecisionMaker.cs index acb57fc32..7f082b191 100644 --- a/src/NzbDrone.Core/MediaFiles/EpisodeImport/ImportDecisionMaker.cs +++ b/src/NzbDrone.Core/MediaFiles/EpisodeImport/ImportDecisionMaker.cs @@ -191,6 +191,7 @@ private Rejection EvaluateSpec(IImportDecisionEngineSpecification spec, LocalEpi private int GetNonSampleVideoFileCount(List videoFiles, Series series, ParsedEpisodeInfo downloadClientItemInfo, ParsedEpisodeInfo folderInfo) { var isPossibleSpecialEpisode = downloadClientItemInfo?.IsPossibleSpecialEpisode ?? false; + // If we might already have a special, don't try to get it from the folder info. isPossibleSpecialEpisode = isPossibleSpecialEpisode || (folderInfo?.IsPossibleSpecialEpisode ?? false); diff --git a/src/NzbDrone.Core/MediaFiles/EpisodeImport/Manual/ManualImportService.cs b/src/NzbDrone.Core/MediaFiles/EpisodeImport/Manual/ManualImportService.cs index 69277bb7b..5c15189f0 100644 --- a/src/NzbDrone.Core/MediaFiles/EpisodeImport/Manual/ManualImportService.cs +++ b/src/NzbDrone.Core/MediaFiles/EpisodeImport/Manual/ManualImportService.cs @@ -100,8 +100,7 @@ public List GetMediaFiles(int seriesId, int? seasonNumber) Language = Language.Unknown, Size = _diskProvider.GetFileSize(file), Rejections = Enumerable.Empty() - } - )); + })); } return items; @@ -294,12 +293,18 @@ private ManualImportItem ProcessFile(string rootFolder, string baseFolder, strin localEpisode.Language = LanguageParser.ParseLanguage(file); localEpisode.Size = _diskProvider.GetFileSize(file); - return MapItem(new ImportDecision(localEpisode, new Rejection("Unknown Series")), rootFolder, - downloadId, null); + return MapItem(new ImportDecision(localEpisode, + new Rejection("Unknown Series")), + rootFolder, + downloadId, + null); } - var importDecisions = _importDecisionMaker.GetImportDecisions(new List {file}, series, - trackedDownload?.DownloadItem, null, SceneSource(series, baseFolder)); + var importDecisions = _importDecisionMaker.GetImportDecisions(new List { file }, + series, + trackedDownload?.DownloadItem, + null, + SceneSource(series, baseFolder)); if (importDecisions.Any()) { @@ -349,7 +354,7 @@ private TrackedDownload GetTrackedDownload(string downloadId) if (downloadId.IsNotNullOrWhiteSpace()) { var trackedDownload = _trackedDownloadService.Find(downloadId); - + return trackedDownload; } @@ -518,9 +523,9 @@ public void Execute(ManualImportCommand message) } var allEpisodesImported = groupedTrackedDownload.Select(c => c.ImportResult) - .Where(c => c.Result == ImportResultType.Imported) - .SelectMany(c => c.ImportDecision.LocalEpisode.Episodes).Count() >= - Math.Max(1, trackedDownload.RemoteEpisode?.Episodes?.Count ?? 1); + .Where(c => c.Result == ImportResultType.Imported) + .SelectMany(c => c.ImportDecision.LocalEpisode.Episodes).Count() >= + Math.Max(1, trackedDownload.RemoteEpisode?.Episodes?.Count ?? 1); if (allEpisodesImported) { diff --git a/src/NzbDrone.Core/MediaFiles/EpisodeImport/RootFolderNotFoundException.cs b/src/NzbDrone.Core/MediaFiles/EpisodeImport/RootFolderNotFoundException.cs index afa918a77..9690a4028 100644 --- a/src/NzbDrone.Core/MediaFiles/EpisodeImport/RootFolderNotFoundException.cs +++ b/src/NzbDrone.Core/MediaFiles/EpisodeImport/RootFolderNotFoundException.cs @@ -10,15 +10,18 @@ public RootFolderNotFoundException() { } - public RootFolderNotFoundException(string message) : base(message) + public RootFolderNotFoundException(string message) + : base(message) { } - public RootFolderNotFoundException(string message, Exception innerException) : base(message, innerException) + public RootFolderNotFoundException(string message, Exception innerException) + : base(message, innerException) { } - protected RootFolderNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context) + protected RootFolderNotFoundException(SerializationInfo info, StreamingContext context) + : base(info, context) { } } diff --git a/src/NzbDrone.Core/MediaFiles/EpisodeImport/Specifications/AbsoluteEpisodeNumberSpecification.cs b/src/NzbDrone.Core/MediaFiles/EpisodeImport/Specifications/AbsoluteEpisodeNumberSpecification.cs index 65eeabd5c..1aad4a1e5 100644 --- a/src/NzbDrone.Core/MediaFiles/EpisodeImport/Specifications/AbsoluteEpisodeNumberSpecification.cs +++ b/src/NzbDrone.Core/MediaFiles/EpisodeImport/Specifications/AbsoluteEpisodeNumberSpecification.cs @@ -19,6 +19,7 @@ public AbsoluteEpisodeNumberSpecification(IBuildFileNames buildFileNames, Logger _buildFileNames = buildFileNames; _logger = logger; } + public Decision IsSatisfiedBy(LocalEpisode localEpisode, DownloadClientItem downloadClientItem) { if (localEpisode.Series.SeriesType != SeriesTypes.Anime) diff --git a/src/NzbDrone.Core/MediaFiles/EpisodeImport/Specifications/EpisodeTitleSpecification.cs b/src/NzbDrone.Core/MediaFiles/EpisodeImport/Specifications/EpisodeTitleSpecification.cs index b689d3bff..79a94e2f5 100644 --- a/src/NzbDrone.Core/MediaFiles/EpisodeImport/Specifications/EpisodeTitleSpecification.cs +++ b/src/NzbDrone.Core/MediaFiles/EpisodeImport/Specifications/EpisodeTitleSpecification.cs @@ -61,9 +61,7 @@ public Decision IsSatisfiedBy(LocalEpisode localEpisode, DownloadClientItem down if (episodeTitleRequired == EpisodeTitleRequiredType.BulkSeasonReleases && allEpisodesOnTheSameDay && episodesInSeason.Count(e => !e.AirDateUtc.HasValue || - e.AirDateUtc.Value == firstEpisode.AirDateUtc.Value - ) < 4 - ) + e.AirDateUtc.Value == firstEpisode.AirDateUtc.Value) < 4) { _logger.Debug("Episode title only required for bulk season releases"); return Decision.Accept(); diff --git a/src/NzbDrone.Core/MediaFiles/EpisodeImport/Specifications/NotSampleSpecification.cs b/src/NzbDrone.Core/MediaFiles/EpisodeImport/Specifications/NotSampleSpecification.cs index 731f69f9c..166e58774 100644 --- a/src/NzbDrone.Core/MediaFiles/EpisodeImport/Specifications/NotSampleSpecification.cs +++ b/src/NzbDrone.Core/MediaFiles/EpisodeImport/Specifications/NotSampleSpecification.cs @@ -35,7 +35,6 @@ public Decision IsSatisfiedBy(LocalEpisode localEpisode, DownloadClientItem down { return Decision.Reject("Sample"); } - else if (sample == DetectSampleResult.Indeterminate) { return Decision.Reject("Unable to determine if file is a sample"); diff --git a/src/NzbDrone.Core/MediaFiles/EpisodeImport/Specifications/UpgradeSpecification.cs b/src/NzbDrone.Core/MediaFiles/EpisodeImport/Specifications/UpgradeSpecification.cs index 44bd2b8aa..546573b98 100644 --- a/src/NzbDrone.Core/MediaFiles/EpisodeImport/Specifications/UpgradeSpecification.cs +++ b/src/NzbDrone.Core/MediaFiles/EpisodeImport/Specifications/UpgradeSpecification.cs @@ -3,10 +3,10 @@ using NzbDrone.Core.Configuration; using NzbDrone.Core.DecisionEngine; using NzbDrone.Core.Download; -using NzbDrone.Core.Parser.Model; -using NzbDrone.Core.Qualities; using NzbDrone.Core.Languages; +using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Profiles.Releases; +using NzbDrone.Core.Qualities; namespace NzbDrone.Core.MediaFiles.EpisodeImport.Specifications { diff --git a/src/NzbDrone.Core/MediaFiles/Events/DeleteCompletedEvent.cs b/src/NzbDrone.Core/MediaFiles/Events/DeleteCompletedEvent.cs index 883ac4df9..805c86a85 100644 --- a/src/NzbDrone.Core/MediaFiles/Events/DeleteCompletedEvent.cs +++ b/src/NzbDrone.Core/MediaFiles/Events/DeleteCompletedEvent.cs @@ -4,6 +4,5 @@ namespace NzbDrone.Core.MediaFiles.Events { public class DeleteCompletedEvent : IEvent { - } } diff --git a/src/NzbDrone.Core/MediaFiles/Events/EpisodeFileAddedEvent.cs b/src/NzbDrone.Core/MediaFiles/Events/EpisodeFileAddedEvent.cs index 83ea2a908..21989d8d1 100644 --- a/src/NzbDrone.Core/MediaFiles/Events/EpisodeFileAddedEvent.cs +++ b/src/NzbDrone.Core/MediaFiles/Events/EpisodeFileAddedEvent.cs @@ -11,4 +11,4 @@ public EpisodeFileAddedEvent(EpisodeFile episodeFile) EpisodeFile = episodeFile; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/MediaFiles/Events/EpisodeFileDeletedEvent.cs b/src/NzbDrone.Core/MediaFiles/Events/EpisodeFileDeletedEvent.cs index 2cbc177a2..aaeca550f 100644 --- a/src/NzbDrone.Core/MediaFiles/Events/EpisodeFileDeletedEvent.cs +++ b/src/NzbDrone.Core/MediaFiles/Events/EpisodeFileDeletedEvent.cs @@ -13,4 +13,4 @@ public EpisodeFileDeletedEvent(EpisodeFile episodeFile, DeleteMediaFileReason re Reason = reason; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/MediaFiles/Events/EpisodeFileRenamedEvent.cs b/src/NzbDrone.Core/MediaFiles/Events/EpisodeFileRenamedEvent.cs index 98708ce5e..3c47a3b63 100644 --- a/src/NzbDrone.Core/MediaFiles/Events/EpisodeFileRenamedEvent.cs +++ b/src/NzbDrone.Core/MediaFiles/Events/EpisodeFileRenamedEvent.cs @@ -16,4 +16,4 @@ public EpisodeFileRenamedEvent(Series series, EpisodeFile episodeFile, string or OriginalPath = originalPath; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/MediaFiles/Events/RenameCompletedEvent.cs b/src/NzbDrone.Core/MediaFiles/Events/RenameCompletedEvent.cs index bccd99028..bbe590b62 100644 --- a/src/NzbDrone.Core/MediaFiles/Events/RenameCompletedEvent.cs +++ b/src/NzbDrone.Core/MediaFiles/Events/RenameCompletedEvent.cs @@ -4,6 +4,5 @@ namespace NzbDrone.Core.MediaFiles.Events { public class RenameCompletedEvent : IEvent { - } } diff --git a/src/NzbDrone.Core/MediaFiles/Events/SeriesRenamedEvent.cs b/src/NzbDrone.Core/MediaFiles/Events/SeriesRenamedEvent.cs index 9b2b82151..8c78ec501 100644 --- a/src/NzbDrone.Core/MediaFiles/Events/SeriesRenamedEvent.cs +++ b/src/NzbDrone.Core/MediaFiles/Events/SeriesRenamedEvent.cs @@ -15,4 +15,4 @@ public SeriesRenamedEvent(Series series, List renamedFiles) RenamedFiles = renamedFiles; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/MediaFiles/Events/SeriesScannedEvent.cs b/src/NzbDrone.Core/MediaFiles/Events/SeriesScannedEvent.cs index f82de5214..e07bbd75f 100644 --- a/src/NzbDrone.Core/MediaFiles/Events/SeriesScannedEvent.cs +++ b/src/NzbDrone.Core/MediaFiles/Events/SeriesScannedEvent.cs @@ -12,4 +12,4 @@ public SeriesScannedEvent(Series series) Series = series; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/MediaFiles/MediaFileAttributeService.cs b/src/NzbDrone.Core/MediaFiles/MediaFileAttributeService.cs index 03e3c6bda..deca5f471 100644 --- a/src/NzbDrone.Core/MediaFiles/MediaFileAttributeService.cs +++ b/src/NzbDrone.Core/MediaFiles/MediaFileAttributeService.cs @@ -52,7 +52,6 @@ public void SetFilePermissions(string path) } } } - else { SetMonoPermissions(path); @@ -87,10 +86,8 @@ private void SetMonoPermissions(string path) { _diskProvider.SetPermissions(path, _configService.ChmodFolder, _configService.ChownGroup); } - catch (Exception ex) { - _logger.Warn(ex, "Unable to apply permissions to: " + path); } } diff --git a/src/NzbDrone.Core/MediaFiles/MediaFileDeletionService.cs b/src/NzbDrone.Core/MediaFiles/MediaFileDeletionService.cs index 00fdc8254..a80437ace 100644 --- a/src/NzbDrone.Core/MediaFiles/MediaFileDeletionService.cs +++ b/src/NzbDrone.Core/MediaFiles/MediaFileDeletionService.cs @@ -44,7 +44,7 @@ public MediaFileDeletionService(IDiskProvider diskProvider, _mediaFileService = mediaFileService; _seriesService = seriesService; _configService = configService; - _eventAggregator = eventAggregator; + _eventAggregator = eventAggregator; _logger = logger; } @@ -81,7 +81,7 @@ public void DeleteEpisodeFile(Series series, EpisodeFile episodeFile) throw new NzbDroneClientException(HttpStatusCode.InternalServerError, "Unable to delete episode file"); } } - + // Delete the episode file from the database to clean it up even if the file was already deleted _mediaFileService.Delete(episodeFile, DeleteMediaFileReason.Manual); @@ -97,7 +97,10 @@ public void HandleAsync(SeriesDeletedEvent message) foreach (var s in allSeries) { - if (s.Id == series.Id) continue; + if (s.Id == series.Id) + { + continue; + } if (series.Path.IsParentPath(s.Path)) { @@ -116,6 +119,7 @@ public void HandleAsync(SeriesDeletedEvent message) { _recycleBinProvider.DeleteFolder(message.Series.Path); } + _eventAggregator.PublishEvent(new DeleteCompletedEvent()); } } diff --git a/src/NzbDrone.Core/MediaFiles/MediaFileExtensions.cs b/src/NzbDrone.Core/MediaFiles/MediaFileExtensions.cs index e62e046d3..33fcbf607 100644 --- a/src/NzbDrone.Core/MediaFiles/MediaFileExtensions.cs +++ b/src/NzbDrone.Core/MediaFiles/MediaFileExtensions.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using NzbDrone.Core.Qualities; - namespace NzbDrone.Core.MediaFiles { public static class MediaFileExtensions diff --git a/src/NzbDrone.Core/MediaFiles/MediaFileRepository.cs b/src/NzbDrone.Core/MediaFiles/MediaFileRepository.cs index 7b3f5cf7b..554db99cf 100644 --- a/src/NzbDrone.Core/MediaFiles/MediaFileRepository.cs +++ b/src/NzbDrone.Core/MediaFiles/MediaFileRepository.cs @@ -2,7 +2,6 @@ using NzbDrone.Core.Datastore; using NzbDrone.Core.Messaging.Events; - namespace NzbDrone.Core.MediaFiles { public interface IMediaFileRepository : IBasicRepository @@ -13,7 +12,6 @@ public interface IMediaFileRepository : IBasicRepository List GetFilesWithRelativePath(int seriesId, string relativePath); } - public class MediaFileRepository : BasicRepository, IMediaFileRepository { public MediaFileRepository(IMainDatabase database, IEventAggregator eventAggregator) diff --git a/src/NzbDrone.Core/MediaFiles/MediaFileService.cs b/src/NzbDrone.Core/MediaFiles/MediaFileService.cs index 179085138..96bff78f9 100644 --- a/src/NzbDrone.Core/MediaFiles/MediaFileService.cs +++ b/src/NzbDrone.Core/MediaFiles/MediaFileService.cs @@ -2,11 +2,11 @@ using System.IO; using System.Linq; using NLog; +using NzbDrone.Common; using NzbDrone.Core.MediaFiles.Events; using NzbDrone.Core.Messaging.Events; using NzbDrone.Core.Tv; using NzbDrone.Core.Tv.Events; -using NzbDrone.Common; namespace NzbDrone.Core.MediaFiles { @@ -118,10 +118,12 @@ public static List FilterExistingFiles(List files, List Path.Combine(series.Path, f.RelativePath)).ToList(); - if (!seriesFilePaths.Any()) return files; + if (!seriesFilePaths.Any()) + { + return files; + } return files.Except(seriesFilePaths, PathEqualityComparer.Instance).ToList(); } - } } diff --git a/src/NzbDrone.Core/MediaFiles/MediaFileTableCleanupService.cs b/src/NzbDrone.Core/MediaFiles/MediaFileTableCleanupService.cs index 0b7b2cba3..d6f3c6b81 100644 --- a/src/NzbDrone.Core/MediaFiles/MediaFileTableCleanupService.cs +++ b/src/NzbDrone.Core/MediaFiles/MediaFileTableCleanupService.cs @@ -34,7 +34,7 @@ public void Clean(Series series, List filesOnDisk) var episodes = _episodeService.GetEpisodeBySeries(series.Id); var filesOnDiskKeys = new HashSet(filesOnDisk, PathEqualityComparer.Instance); - + foreach (var seriesFile in seriesFiles) { var episodeFile = seriesFile; @@ -65,7 +65,6 @@ public void Clean(Series series, List filesOnDisk) // continue; // } } - catch (Exception ex) { _logger.Error(ex, "Unable to cleanup EpisodeFile in DB: {0}", episodeFile.Id); @@ -84,4 +83,4 @@ public void Clean(Series series, List filesOnDisk) } } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/MediaFiles/MediaInfo/MediaInfoFormatter.cs b/src/NzbDrone.Core/MediaFiles/MediaInfo/MediaInfoFormatter.cs index 169e56eb7..8494c9772 100644 --- a/src/NzbDrone.Core/MediaFiles/MediaInfo/MediaInfoFormatter.cs +++ b/src/NzbDrone.Core/MediaFiles/MediaInfo/MediaInfoFormatter.cs @@ -12,6 +12,9 @@ namespace NzbDrone.Core.MediaFiles.MediaInfo { public static class MediaInfoFormatter { + private const string ValidHdrColourPrimaries = "BT.2020"; + private const string VideoDynamicRangeHdr = "HDR"; + private static readonly Logger Logger = NzbDroneLogger.GetLogger(typeof(MediaInfoFormatter)); public static decimal FormatAudioChannels(MediaInfoModel mediaInfo) @@ -42,13 +45,13 @@ public static string FormatAudioCodec(MediaInfoModel mediaInfo, string sceneName var audioCodecID = mediaInfo.AudioCodecID ?? string.Empty; var audioProfile = mediaInfo.AudioProfile ?? string.Empty; var audioCodecLibrary = mediaInfo.AudioCodecLibrary ?? string.Empty; - var splitAdditionalFeatures = (mediaInfo.AudioAdditionalFeatures ?? string.Empty).Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries); + var splitAdditionalFeatures = (mediaInfo.AudioAdditionalFeatures ?? string.Empty).Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); if (audioFormat.Empty()) { return string.Empty; } - + if (audioFormat.ContainsIgnoreCase("Atmos")) { return "TrueHD Atmos"; @@ -82,6 +85,7 @@ public static string FormatAudioCodec(MediaInfoModel mediaInfo, string sceneName { return "DTS-X"; } + return "DTS-HD MA"; } @@ -463,7 +467,7 @@ public static string FormatVideoCodecLegacy(MediaInfoModel mediaInfo, string sce "", RegexOptions.Compiled | RegexOptions.IgnoreCase) .Replace("Object Based / ", "") - .Split(new string[] {" / "}, StringSplitOptions.RemoveEmptyEntries) + .Split(new string[] { " / " }, StringSplitOptions.RemoveEmptyEntries) .FirstOrDefault() ?.Split('/'); @@ -592,7 +596,7 @@ public static string FormatVideoDynamicRange(MediaInfoModel mediaInfo) public static string FormatVideoDynamicRangeType(MediaInfoModel mediaInfo) { - switch(mediaInfo.GetHdrFormat()) + switch (mediaInfo.GetHdrFormat()) { case HdrFormat.DolbyVision: return "DV"; diff --git a/src/NzbDrone.Core/MediaFiles/MediaInfo/MediaInfoLib.cs b/src/NzbDrone.Core/MediaFiles/MediaInfo/MediaInfoLib.cs index 11fa19e96..0be357863 100644 --- a/src/NzbDrone.Core/MediaFiles/MediaInfo/MediaInfoLib.cs +++ b/src/NzbDrone.Core/MediaFiles/MediaInfo/MediaInfoLib.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.IO; using System.Runtime.InteropServices; @@ -55,8 +55,7 @@ public enum InfoFileOptions FileOption_NoRecursive = 0x01, FileOption_CloseAll = 0x02, FileOption_Max = 0x04 - }; - + } public class MediaInfo : IDisposable { @@ -87,6 +86,7 @@ public void Dispose() { MediaInfo_Delete(_handle); } + GC.SuppressFinalize(this); } @@ -132,7 +132,7 @@ private void InitializeEncoding() return; } - throw new NotSupportedException("Unsupported MediaInfoLib encoding, version check responses (may be gibberish, show it to the Sonarr devs): " + responses.Join(", ") ); + throw new NotSupportedException("Unsupported MediaInfoLib encoding, version check responses (may be gibberish, show it to the Sonarr devs): " + responses.Join(", ")); } } @@ -233,7 +233,8 @@ public int Open(Stream stream) seekStart = seekPos; MediaInfo_Open_Buffer_Init(_handle, stream.Length, seekPos); } - } while (bufferRead > 0); + } + while (bufferRead > 0); MediaInfo_Open_Buffer_Finalize(_handle); diff --git a/src/NzbDrone.Core/MediaFiles/MediaInfo/MediaInfoModel.cs b/src/NzbDrone.Core/MediaFiles/MediaInfo/MediaInfoModel.cs index 0fc53c19b..a329af173 100644 --- a/src/NzbDrone.Core/MediaFiles/MediaInfo/MediaInfoModel.cs +++ b/src/NzbDrone.Core/MediaFiles/MediaInfo/MediaInfoModel.cs @@ -10,6 +10,7 @@ namespace NzbDrone.Core.MediaFiles.MediaInfo public class MediaInfoModel : IEmbeddedDocument { public string ContainerFormat { get; set; } + // Deprecated according to MediaInfo public string VideoCodec { get; set; } public string VideoFormat { get; set; } diff --git a/src/NzbDrone.Core/MediaFiles/MediaInfo/MediaInfoModelExtensions.cs b/src/NzbDrone.Core/MediaFiles/MediaInfo/MediaInfoModelExtensions.cs index 9a7b97672..b9038f83a 100644 --- a/src/NzbDrone.Core/MediaFiles/MediaInfo/MediaInfoModelExtensions.cs +++ b/src/NzbDrone.Core/MediaFiles/MediaInfo/MediaInfoModelExtensions.cs @@ -1,9 +1,5 @@ -using NzbDrone.Common.Extensions; -using System; -using System.Collections.Generic; using System.Linq; -using System.Text; -using System.Threading.Tasks; +using NzbDrone.Common.Extensions; namespace NzbDrone.Core.MediaFiles.MediaInfo { @@ -26,9 +22,9 @@ public static HdrFormat GetHdrFormat(this MediaInfoModel mediaInfo) if (mediaInfo.VideoHdrFormat.IsNotNullOrWhiteSpace()) { - if(DolbyVisionFormats.Any(mediaInfo.VideoHdrFormat.ContainsIgnoreCase)) + if (DolbyVisionFormats.Any(mediaInfo.VideoHdrFormat.ContainsIgnoreCase)) { - if(Hdr10Formats.Any(mediaInfo.VideoHdrFormat.ContainsIgnoreCase)) + if (Hdr10Formats.Any(mediaInfo.VideoHdrFormat.ContainsIgnoreCase)) { return HdrFormat.DolbyVisionHdr10; } @@ -37,19 +33,17 @@ public static HdrFormat GetHdrFormat(this MediaInfoModel mediaInfo) return HdrFormat.DolbyVision; } } - else if(Hdr10Formats.Any(mediaInfo.VideoHdrFormat.ContainsIgnoreCase)) + else if (Hdr10Formats.Any(mediaInfo.VideoHdrFormat.ContainsIgnoreCase)) { return HdrFormat.Hdr10; } - else if(Hdr10PlusFormats.Any(mediaInfo.VideoHdrFormat.ContainsIgnoreCase)) + else if (Hdr10PlusFormats.Any(mediaInfo.VideoHdrFormat.ContainsIgnoreCase)) { return HdrFormat.Hdr10Plus; } } - // - // We didn't match straight from the format from MediaInfo, so try and match in ColourPrimaries and TransferCharacteristics - // + // We didn't match straight from the format from MediaInfo, so try and match in ColourPrimaries and TransferCharacteristics if (mediaInfo.VideoColourPrimaries.IsNotNullOrWhiteSpace() && mediaInfo.VideoTransferCharacteristics.IsNotNullOrWhiteSpace()) { if (mediaInfo.VideoColourPrimaries.EqualsIgnoreCase(ValidHdrColourPrimaries)) diff --git a/src/NzbDrone.Core/MediaFiles/MediaInfo/UpdateMediaInfoService.cs b/src/NzbDrone.Core/MediaFiles/MediaInfo/UpdateMediaInfoService.cs index 807878d9a..597d27301 100644 --- a/src/NzbDrone.Core/MediaFiles/MediaInfo/UpdateMediaInfoService.cs +++ b/src/NzbDrone.Core/MediaFiles/MediaInfo/UpdateMediaInfoService.cs @@ -1,12 +1,12 @@ -using System.IO; +using System.Collections.Generic; +using System.IO; +using System.Linq; using NLog; using NzbDrone.Common.Disk; +using NzbDrone.Core.Configuration; using NzbDrone.Core.MediaFiles.Events; using NzbDrone.Core.Messaging.Events; using NzbDrone.Core.Tv; -using System.Collections.Generic; -using System.Linq; -using NzbDrone.Core.Configuration; namespace NzbDrone.Core.MediaFiles.MediaInfo { @@ -78,14 +78,16 @@ private bool UpdateMediaInfo(EpisodeFile episodeFile, Series series) var updatedMediaInfo = _videoFileInfoReader.GetMediaInfo(path); - if (updatedMediaInfo == null) return false; + if (updatedMediaInfo == null) + { + return false; + } episodeFile.MediaInfo = updatedMediaInfo; _mediaFileService.Update(episodeFile); _logger.Debug("Updated MediaInfo for '{0}'", path); return true; - } } } diff --git a/src/NzbDrone.Core/MediaFiles/MediaInfo/VideoFileInfoReader.cs b/src/NzbDrone.Core/MediaFiles/MediaInfo/VideoFileInfoReader.cs index 43a162f8b..65e95a09f 100644 --- a/src/NzbDrone.Core/MediaFiles/MediaInfo/VideoFileInfoReader.cs +++ b/src/NzbDrone.Core/MediaFiles/MediaInfo/VideoFileInfoReader.cs @@ -27,7 +27,6 @@ public VideoFileInfoReader(IDiskProvider diskProvider, Logger logger) _logger = logger; } - public MediaInfoModel GetMediaInfo(string filename) { if (!_diskProvider.FileExists(filename)) @@ -126,6 +125,7 @@ public MediaInfoModel GetMediaInfo(string filename) { int.TryParse(mediaInfo.Get(StreamKind.Video, 0, "BitRate_Nominal"), out videoBitRate); } + decimal.TryParse(mediaInfo.Get(StreamKind.Video, 0, "FrameRate"), NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out videoFrameRate); int.TryParse(mediaInfo.Get(StreamKind.Video, 0, "BitDepth"), out videoBitDepth); int.TryParse(mediaInfo.Get(StreamKind.Video, 0, "MultiView_Count"), out videoMultiViewCount); @@ -140,7 +140,6 @@ public MediaInfoModel GetMediaInfo(string filename) int.TryParse(aBitRate, out audioBitRate); int.TryParse(mediaInfo.Get(StreamKind.Audio, 0, "StreamCount"), out streamCount); - var audioChannelsStr = mediaInfo.Get(StreamKind.Audio, 0, "Channel(s)").Split(new string[] { " /" }, StringSplitOptions.None)[0].Trim(); int.TryParse(audioChannelsStr, out audioChannels); diff --git a/src/NzbDrone.Core/MediaFiles/RecycleBinProvider.cs b/src/NzbDrone.Core/MediaFiles/RecycleBinProvider.cs index 1b636de65..70060021a 100644 --- a/src/NzbDrone.Core/MediaFiles/RecycleBinProvider.cs +++ b/src/NzbDrone.Core/MediaFiles/RecycleBinProvider.cs @@ -27,7 +27,6 @@ public class RecycleBinProvider : IExecute, IRecycleBi private readonly IConfigService _configService; private readonly Logger _logger; - public RecycleBinProvider(IDiskTransferService diskTransferService, IDiskProvider diskProvider, IConfigService configService, @@ -50,7 +49,6 @@ public void DeleteFolder(string path) _diskProvider.DeleteFolder(path, true); _logger.Debug("Folder has been permanently deleted: {0}", path); } - else { var destination = Path.Combine(recyclingBin, new DirectoryInfo(path).Name); @@ -86,7 +84,6 @@ public void DeleteFile(string path, string subfolder = "") _diskProvider.DeleteFile(path); _logger.Debug("File has been permanently deleted: {0}", path); } - else { var fileInfo = new FileInfo(path); diff --git a/src/NzbDrone.Core/MediaFiles/SameFilenameException.cs b/src/NzbDrone.Core/MediaFiles/SameFilenameException.cs index c2a8cbd1f..d191bf55d 100644 --- a/src/NzbDrone.Core/MediaFiles/SameFilenameException.cs +++ b/src/NzbDrone.Core/MediaFiles/SameFilenameException.cs @@ -6,7 +6,8 @@ public class SameFilenameException : Exception { public string Filename { get; set; } - public SameFilenameException(string message, string filename) : base(message) + public SameFilenameException(string message, string filename) + : base(message) { Filename = filename; } diff --git a/src/NzbDrone.Core/MediaFiles/TorrentInfo/TorrentFileInfoReader.cs b/src/NzbDrone.Core/MediaFiles/TorrentInfo/TorrentFileInfoReader.cs index 879cd9ca2..a3bb71acc 100644 --- a/src/NzbDrone.Core/MediaFiles/TorrentInfo/TorrentFileInfoReader.cs +++ b/src/NzbDrone.Core/MediaFiles/TorrentInfo/TorrentFileInfoReader.cs @@ -2,12 +2,12 @@ namespace NzbDrone.Core.MediaFiles.TorrentInfo { - public interface ITorrentFileInfoReader + public interface ITorrentFileInfoReader { string GetHashFromTorrentFile(byte[] fileContents); } - public class TorrentFileInfoReader: ITorrentFileInfoReader + public class TorrentFileInfoReader : ITorrentFileInfoReader { public string GetHashFromTorrentFile(byte[] fileContents) { diff --git a/src/NzbDrone.Core/MediaFiles/UpdateEpisodeFileService.cs b/src/NzbDrone.Core/MediaFiles/UpdateEpisodeFileService.cs index cdc8454ec..cffaa9e97 100644 --- a/src/NzbDrone.Core/MediaFiles/UpdateEpisodeFileService.cs +++ b/src/NzbDrone.Core/MediaFiles/UpdateEpisodeFileService.cs @@ -103,14 +103,12 @@ private bool ChangeFileDateToLocalAirDate(string filePath, string fileDate, stri return true; } - catch (Exception ex) { _logger.Warn(ex, "Unable to set date of file [" + filePath + "]"); } } } - else { _logger.Debug("Could not create valid date to change file [{0}]", filePath); @@ -138,7 +136,6 @@ private bool ChangeFileDateToUtcAirDate(string filePath, DateTime airDateUtc) return true; } - catch (Exception ex) { _logger.Warn(ex, "Unable to set date of file [" + filePath + "]"); @@ -177,7 +174,6 @@ public void Handle(SeriesScannedEvent message) { _logger.ProgressDebug("Changed file date for {0} files of {1} in {2}", updated.Count, episodeFiles.Count, message.Series.Title); } - else { _logger.ProgressDebug("No file dates changed for {0}", message.Series.Title); diff --git a/src/NzbDrone.Core/Messaging/Commands/BackendCommandAttribute.cs b/src/NzbDrone.Core/Messaging/Commands/BackendCommandAttribute.cs index b40f64f9c..85f162a23 100644 --- a/src/NzbDrone.Core/Messaging/Commands/BackendCommandAttribute.cs +++ b/src/NzbDrone.Core/Messaging/Commands/BackendCommandAttribute.cs @@ -5,4 +5,4 @@ namespace NzbDrone.Core.Messaging.Commands public class BackendCommandAttribute : Attribute { } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Messaging/Commands/Command.cs b/src/NzbDrone.Core/Messaging/Commands/Command.cs index 8ca57519f..16915201e 100644 --- a/src/NzbDrone.Core/Messaging/Commands/Command.cs +++ b/src/NzbDrone.Core/Messaging/Commands/Command.cs @@ -16,7 +16,7 @@ public virtual bool SendUpdatesToClient set { _sendUpdatesToClient = value; - } + } } public virtual bool UpdateScheduledTask => true; diff --git a/src/NzbDrone.Core/Messaging/Commands/CommandEqualityComparer.cs b/src/NzbDrone.Core/Messaging/Commands/CommandEqualityComparer.cs index 65f21b935..ea24a29df 100644 --- a/src/NzbDrone.Core/Messaging/Commands/CommandEqualityComparer.cs +++ b/src/NzbDrone.Core/Messaging/Commands/CommandEqualityComparer.cs @@ -10,12 +10,14 @@ public class CommandEqualityComparer : IEqualityComparer private CommandEqualityComparer() { - } public bool Equals(Command x, Command y) { - if(x.GetType() != y.GetType()) return false; + if (x.GetType() != y.GetType()) + { + return false; + } var xProperties = x.GetType().GetProperties(); var yProperties = y.GetType().GetProperties(); @@ -27,7 +29,7 @@ public bool Equals(Command x, Command y) continue; } - if (xProperty.DeclaringType == typeof (Command)) + if (xProperty.DeclaringType == typeof(Command)) { continue; } @@ -60,7 +62,6 @@ public bool Equals(Command x, Command y) return false; } } - else if (!xValue.Equals(yValue)) { return false; diff --git a/src/NzbDrone.Core/Messaging/Commands/CommandExecutor.cs b/src/NzbDrone.Core/Messaging/Commands/CommandExecutor.cs index 2089ce0ed..18dabae07 100644 --- a/src/NzbDrone.Core/Messaging/Commands/CommandExecutor.cs +++ b/src/NzbDrone.Core/Messaging/Commands/CommandExecutor.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Threading; using NLog; using NzbDrone.Common; @@ -11,13 +11,14 @@ namespace NzbDrone.Core.Messaging.Commands public class CommandExecutor : IHandle, IHandle { + private const int THREAD_LIMIT = 3; + private readonly Logger _logger; private readonly IServiceFactory _serviceFactory; private readonly IManageCommandQueue _commandQueueManager; private readonly IEventAggregator _eventAggregator; private static CancellationTokenSource _cancellationTokenSource; - private const int THREAD_LIMIT = 3; public CommandExecutor(IServiceFactory serviceFactory, IManageCommandQueue commandQueueManager, @@ -61,7 +62,8 @@ private void ExecuteCommands() } } - private void ExecuteCommand(TCommand command, CommandModel commandModel) where TCommand : Command + private void ExecuteCommand(TCommand command, CommandModel commandModel) + where TCommand : Command { IExecute handler = null; diff --git a/src/NzbDrone.Core/Messaging/Commands/CommandFailedException.cs b/src/NzbDrone.Core/Messaging/Commands/CommandFailedException.cs index 3dcbf60cc..cfb41883f 100644 --- a/src/NzbDrone.Core/Messaging/Commands/CommandFailedException.cs +++ b/src/NzbDrone.Core/Messaging/Commands/CommandFailedException.cs @@ -5,19 +5,23 @@ namespace NzbDrone.Core.Messaging.Commands { public class CommandFailedException : NzbDroneException { - public CommandFailedException(string message, params object[] args) : base(message, args) + public CommandFailedException(string message, params object[] args) + : base(message, args) { } - public CommandFailedException(string message) : base(message) + public CommandFailedException(string message) + : base(message) { } - public CommandFailedException(string message, Exception innerException, params object[] args) : base(message, innerException, args) + public CommandFailedException(string message, Exception innerException, params object[] args) + : base(message, innerException, args) { } - public CommandFailedException(string message, Exception innerException) : base(message, innerException) + public CommandFailedException(string message, Exception innerException) + : base(message, innerException) { } diff --git a/src/NzbDrone.Core/Messaging/Commands/CommandNotFoundException.cs b/src/NzbDrone.Core/Messaging/Commands/CommandNotFoundException.cs index 656037138..503dadadf 100644 --- a/src/NzbDrone.Core/Messaging/Commands/CommandNotFoundException.cs +++ b/src/NzbDrone.Core/Messaging/Commands/CommandNotFoundException.cs @@ -8,6 +8,5 @@ public CommandNotFoundException(string contract) : base("Couldn't find command " + contract) { } - } } diff --git a/src/NzbDrone.Core/Messaging/Commands/CommandPriorityComparer.cs b/src/NzbDrone.Core/Messaging/Commands/CommandPriorityComparer.cs index d3be33d59..5d8d5f13e 100644 --- a/src/NzbDrone.Core/Messaging/Commands/CommandPriorityComparer.cs +++ b/src/NzbDrone.Core/Messaging/Commands/CommandPriorityComparer.cs @@ -1,8 +1,8 @@ -using System.Collections.Generic; +using System.Collections.Generic; namespace NzbDrone.Core.Messaging.Commands { - public class CommandPriorityComparer: IComparer + public class CommandPriorityComparer : IComparer { public int Compare(CommandStatus x, CommandStatus y) { diff --git a/src/NzbDrone.Core/Messaging/Commands/CommandQueue.cs b/src/NzbDrone.Core/Messaging/Commands/CommandQueue.cs index 67fa437b7..b77e7fecb 100644 --- a/src/NzbDrone.Core/Messaging/Commands/CommandQueue.cs +++ b/src/NzbDrone.Core/Messaging/Commands/CommandQueue.cs @@ -74,6 +74,7 @@ public void RemoveMany(IEnumerable commands) Monitor.PulseAll(_mutex); } } + public bool RemoveIfQueued(int id) { var rval = false; @@ -154,7 +155,6 @@ private bool TryGet(out CommandModel item) { rval = false; } - else { var startedCommands = _items.Where(c => c.Status == CommandStatus.Started) diff --git a/src/NzbDrone.Core/Messaging/Commands/CommandQueueManager.cs b/src/NzbDrone.Core/Messaging/Commands/CommandQueueManager.cs index 9156e0844..7e038561c 100644 --- a/src/NzbDrone.Core/Messaging/Commands/CommandQueueManager.cs +++ b/src/NzbDrone.Core/Messaging/Commands/CommandQueueManager.cs @@ -1,27 +1,29 @@ -using NLog; -using NzbDrone.Common; -using NzbDrone.Common.EnsureThat; -using NzbDrone.Common.Serializer; -using NzbDrone.Core.Lifecycle; -using NzbDrone.Core.Messaging.Events; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Threading; +using NLog; +using NzbDrone.Common; +using NzbDrone.Common.EnsureThat; +using NzbDrone.Common.Serializer; using NzbDrone.Core.Exceptions; +using NzbDrone.Core.Lifecycle; +using NzbDrone.Core.Messaging.Events; namespace NzbDrone.Core.Messaging.Commands { public interface IManageCommandQueue { - List PushMany(List commands) where TCommand : Command; - CommandModel Push(TCommand command, CommandPriority priority = CommandPriority.Normal, CommandTrigger trigger = CommandTrigger.Unspecified) where TCommand : Command; + List PushMany(List commands) + where TCommand : Command; + CommandModel Push(TCommand command, CommandPriority priority = CommandPriority.Normal, CommandTrigger trigger = CommandTrigger.Unspecified) + where TCommand : Command; CommandModel Push(string commandName, DateTime? lastExecutionTime, CommandPriority priority = CommandPriority.Normal, CommandTrigger trigger = CommandTrigger.Unspecified); IEnumerable Queue(CancellationToken cancellationToken); List All(); CommandModel Get(int id); - List GetStarted(); + List GetStarted(); void SetMessage(CommandModel command, string message); void Start(CommandModel command); void Complete(CommandModel command, string message); @@ -39,7 +41,7 @@ public class CommandQueueManager : IManageCommandQueue, IHandle PushMany(List commands) where TCommand : Command + public List PushMany(List commands) + where TCommand : Command { _logger.Trace("Publishing {0} commands", commands.Count); @@ -92,7 +95,8 @@ public List PushMany(List commands) where TCom } } - public CommandModel Push(TCommand command, CommandPriority priority = CommandPriority.Normal, CommandTrigger trigger = CommandTrigger.Unspecified) where TCommand : Command + public CommandModel Push(TCommand command, CommandPriority priority = CommandPriority.Normal, CommandTrigger trigger = CommandTrigger.Unspecified) + where TCommand : Command { Ensure.That(command, () => command).IsNotNull(); @@ -190,7 +194,7 @@ public void Complete(CommandModel command, string message) public void Fail(CommandModel command, string message, Exception e) { command.Exception = e.ToString(); - + Update(command, CommandStatus.Failed, message); _commandQueue.PulseAllConsumers(); @@ -215,7 +219,7 @@ public void Cancel(int id) public void CleanCommands() { _logger.Trace("Cleaning up old commands"); - + var commands = _commandQueue.All() .Where(c => c.EndedAt < DateTime.UtcNow.AddMinutes(-5)) .ToList(); diff --git a/src/NzbDrone.Core/Messaging/Commands/IExecute.cs b/src/NzbDrone.Core/Messaging/Commands/IExecute.cs index 4e058e4d0..63bcc02d6 100644 --- a/src/NzbDrone.Core/Messaging/Commands/IExecute.cs +++ b/src/NzbDrone.Core/Messaging/Commands/IExecute.cs @@ -1,7 +1,8 @@ namespace NzbDrone.Core.Messaging.Commands { - public interface IExecute : IProcessMessage where TCommand : Command + public interface IExecute : IProcessMessage + where TCommand : Command { void Execute(TCommand message); } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Messaging/Commands/TestCommand.cs b/src/NzbDrone.Core/Messaging/Commands/TestCommand.cs index f52fdeae7..9fe7c77c6 100644 --- a/src/NzbDrone.Core/Messaging/Commands/TestCommand.cs +++ b/src/NzbDrone.Core/Messaging/Commands/TestCommand.cs @@ -11,4 +11,4 @@ public TestCommand() Duration = 4000; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Messaging/Commands/TestCommandExecutor.cs b/src/NzbDrone.Core/Messaging/Commands/TestCommandExecutor.cs index 09c0f777d..40def385f 100644 --- a/src/NzbDrone.Core/Messaging/Commands/TestCommandExecutor.cs +++ b/src/NzbDrone.Core/Messaging/Commands/TestCommandExecutor.cs @@ -20,4 +20,4 @@ public void Execute(TestCommand message) _logger.ProgressInfo("Completed Test command"); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Messaging/Events/CommandExecutedEvent.cs b/src/NzbDrone.Core/Messaging/Events/CommandExecutedEvent.cs index 43556c47d..56ff5556c 100644 --- a/src/NzbDrone.Core/Messaging/Events/CommandExecutedEvent.cs +++ b/src/NzbDrone.Core/Messaging/Events/CommandExecutedEvent.cs @@ -12,4 +12,4 @@ public CommandExecutedEvent(CommandModel command) Command = command; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Messaging/Events/EventAggregator.cs b/src/NzbDrone.Core/Messaging/Events/EventAggregator.cs index 6c9491e0d..78bc5f15c 100644 --- a/src/NzbDrone.Core/Messaging/Events/EventAggregator.cs +++ b/src/NzbDrone.Core/Messaging/Events/EventAggregator.cs @@ -17,7 +17,8 @@ public class EventAggregator : IEventAggregator private readonly TaskFactory _taskFactory; private readonly Dictionary _eventSubscribers; - private class EventSubscribers where TEvent : class, IEvent + private class EventSubscribers + where TEvent : class, IEvent { public IHandle[] _syncHandlers; public IHandleAsync[] _asyncHandlers; @@ -45,7 +46,8 @@ public EventAggregator(Logger logger, IServiceFactory serviceFactory) _eventSubscribers = new Dictionary(); } - public void PublishEvent(TEvent @event) where TEvent : class, IEvent + public void PublishEvent(TEvent @event) + where TEvent : class, IEvent { Ensure.That(@event, () => @event).IsNotNull(); @@ -133,20 +135,21 @@ private static string GetEventName(Type eventType) return string.Format("{0}<{1}>", eventType.Name.Remove(eventType.Name.IndexOf('`')), eventType.GetGenericArguments()[0].Name); } - internal static int GetEventHandleOrder(IHandle eventHandler) where TEvent : class, IEvent + internal static int GetEventHandleOrder(IHandle eventHandler) + where TEvent : class, IEvent { - var method = eventHandler.GetType().GetMethod(nameof(eventHandler.Handle), new Type[] {typeof(TEvent)}); + var method = eventHandler.GetType().GetMethod(nameof(eventHandler.Handle), new Type[] { typeof(TEvent) }); if (method == null) { - return (int) EventHandleOrder.Any; + return (int)EventHandleOrder.Any; } var attribute = method.GetCustomAttributes(typeof(EventHandleOrderAttribute), true).FirstOrDefault() as EventHandleOrderAttribute; if (attribute == null) { - return (int) EventHandleOrder.Any; + return (int)EventHandleOrder.Any; } return (int)attribute.EventHandleOrder; diff --git a/src/NzbDrone.Core/Messaging/Events/IEventAggregator.cs b/src/NzbDrone.Core/Messaging/Events/IEventAggregator.cs index 9df32d66d..f92d8f808 100644 --- a/src/NzbDrone.Core/Messaging/Events/IEventAggregator.cs +++ b/src/NzbDrone.Core/Messaging/Events/IEventAggregator.cs @@ -4,6 +4,7 @@ namespace NzbDrone.Core.Messaging.Events { public interface IEventAggregator { - void PublishEvent(TEvent @event) where TEvent : class, IEvent; + void PublishEvent(TEvent @event) + where TEvent : class, IEvent; } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Messaging/Events/IHandle.cs b/src/NzbDrone.Core/Messaging/Events/IHandle.cs index 291e099d2..17c232e62 100644 --- a/src/NzbDrone.Core/Messaging/Events/IHandle.cs +++ b/src/NzbDrone.Core/Messaging/Events/IHandle.cs @@ -2,13 +2,15 @@ namespace NzbDrone.Core.Messaging.Events { - public interface IHandle : IProcessMessage where TEvent : IEvent + public interface IHandle : IProcessMessage + where TEvent : IEvent { void Handle(TEvent message); } - public interface IHandleAsync : IProcessMessageAsync where TEvent : IEvent + public interface IHandleAsync : IProcessMessageAsync + where TEvent : IEvent { void HandleAsync(TEvent message); } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Messaging/IProcessMessage.cs b/src/NzbDrone.Core/Messaging/IProcessMessage.cs index 2207e803d..f0463ce2e 100644 --- a/src/NzbDrone.Core/Messaging/IProcessMessage.cs +++ b/src/NzbDrone.Core/Messaging/IProcessMessage.cs @@ -1,10 +1,18 @@ namespace NzbDrone.Core.Messaging { - public interface IProcessMessage { } + public interface IProcessMessage + { + } - public interface IProcessMessageAsync : IProcessMessage { } + public interface IProcessMessageAsync : IProcessMessage + { + } - public interface IProcessMessage : IProcessMessage { } + public interface IProcessMessage : IProcessMessage + { + } - public interface IProcessMessageAsync : IProcessMessageAsync { } -} \ No newline at end of file + public interface IProcessMessageAsync : IProcessMessageAsync + { + } +} diff --git a/src/NzbDrone.Core/MetadataSource/IProvideSeriesInfo.cs b/src/NzbDrone.Core/MetadataSource/IProvideSeriesInfo.cs index f2ab03336..2664038d4 100644 --- a/src/NzbDrone.Core/MetadataSource/IProvideSeriesInfo.cs +++ b/src/NzbDrone.Core/MetadataSource/IProvideSeriesInfo.cs @@ -8,4 +8,4 @@ public interface IProvideSeriesInfo { Tuple> GetSeriesInfo(int tvdbSeriesId); } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/MetadataSource/ISearchForNewSeries.cs b/src/NzbDrone.Core/MetadataSource/ISearchForNewSeries.cs index 5abd02bcc..bd6698251 100644 --- a/src/NzbDrone.Core/MetadataSource/ISearchForNewSeries.cs +++ b/src/NzbDrone.Core/MetadataSource/ISearchForNewSeries.cs @@ -7,4 +7,4 @@ public interface ISearchForNewSeries { List SearchForNewSeries(string title); } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/MetadataSource/SearchSeriesComparer.cs b/src/NzbDrone.Core/MetadataSource/SearchSeriesComparer.cs index 05d9a1223..7b49247a5 100644 --- a/src/NzbDrone.Core/MetadataSource/SearchSeriesComparer.cs +++ b/src/NzbDrone.Core/MetadataSource/SearchSeriesComparer.cs @@ -20,7 +20,7 @@ public class SearchSeriesComparer : IComparer public SearchSeriesComparer(string searchQuery) { SearchQuery = searchQuery; - + var match = Regex.Match(SearchQuery, @"^(?.+)\s+(?:\((?\d{4})\)|(?\d{4}))$"); if (match.Success) { @@ -39,28 +39,43 @@ public int Compare(Series x, Series y) // Prefer exact matches result = Compare(x, y, s => CleanPunctuation(s.Title).Equals(CleanPunctuation(SearchQuery))); - if (result != 0) return -result; + if (result != 0) + { + return -result; + } // Remove Articles (a/an/the) result = Compare(x, y, s => CleanArticles(s.Title).Equals(CleanArticles(SearchQuery))); - if (result != 0) return -result; + if (result != 0) + { + return -result; + } // Prefer close matches result = Compare(x, y, s => CleanPunctuation(s.Title).LevenshteinDistance(CleanPunctuation(SearchQuery)) <= 1); - if (result != 0) return -result; + if (result != 0) + { + return -result; + } // Compare clean matches by year "Battlestar Galactica 1978" result = CompareWithYear(x, y, s => CleanTitle(s.Title).LevenshteinDistance(_searchQueryWithoutYear) <= 1); - if (result != 0) return -result; + if (result != 0) + { + return -result; + } // Compare prefix matches by year "(CSI: ..." result = CompareWithYear(x, y, s => s.Title.ToLowerInvariant().StartsWith(_searchQueryWithoutYear + ":")); - if (result != 0) return -result; - + if (result != 0) + { + return -result; + } + return Compare(x, y, s => SearchQuery.LevenshteinDistanceClean(s.Title) - GetYearFactor(s)); } - - public int Compare(Series x, Series y, Func keySelector) + + public int Compare(Series x, Series y, Func keySelector) where T : IComparable { var keyX = keySelector(x); @@ -79,7 +94,10 @@ public int CompareWithYear(Series x, Series y, Predicate canMatch) if (_year.HasValue) { var result = Compare(x, y, s => s.Year == _year.Value); - if (result != 0) return result; + if (result != 0) + { + return result; + } } return Compare(x, y, s => s.Year); @@ -117,7 +135,7 @@ private int GetYearFactor(Series series) var offset = Math.Abs(series.Year - _year.Value); if (offset <= 1) { - return 20 - 10 * offset; + return 20 - (10 * offset); } } diff --git a/src/NzbDrone.Core/MetadataSource/SkyHook/Resource/ActorResource.cs b/src/NzbDrone.Core/MetadataSource/SkyHook/Resource/ActorResource.cs index 180933387..0fdf22c55 100644 --- a/src/NzbDrone.Core/MetadataSource/SkyHook/Resource/ActorResource.cs +++ b/src/NzbDrone.Core/MetadataSource/SkyHook/Resource/ActorResource.cs @@ -6,4 +6,4 @@ public class ActorResource public string Character { get; set; } public string Image { get; set; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/MetadataSource/SkyHook/Resource/EpisodeResource.cs b/src/NzbDrone.Core/MetadataSource/SkyHook/Resource/EpisodeResource.cs index 48ca3b9bc..28021bbb0 100644 --- a/src/NzbDrone.Core/MetadataSource/SkyHook/Resource/EpisodeResource.cs +++ b/src/NzbDrone.Core/MetadataSource/SkyHook/Resource/EpisodeResource.cs @@ -18,4 +18,4 @@ public class EpisodeResource public string Overview { get; set; } public string Image { get; set; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/MetadataSource/SkyHook/Resource/ImageResource.cs b/src/NzbDrone.Core/MetadataSource/SkyHook/Resource/ImageResource.cs index 81a2f578e..c5f8827d1 100644 --- a/src/NzbDrone.Core/MetadataSource/SkyHook/Resource/ImageResource.cs +++ b/src/NzbDrone.Core/MetadataSource/SkyHook/Resource/ImageResource.cs @@ -5,4 +5,4 @@ public class ImageResource public string CoverType { get; set; } public string Url { get; set; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/MetadataSource/SkyHook/Resource/RatingResource.cs b/src/NzbDrone.Core/MetadataSource/SkyHook/Resource/RatingResource.cs index d3958378b..c14e188e4 100644 --- a/src/NzbDrone.Core/MetadataSource/SkyHook/Resource/RatingResource.cs +++ b/src/NzbDrone.Core/MetadataSource/SkyHook/Resource/RatingResource.cs @@ -5,4 +5,4 @@ public class RatingResource public int Count { get; set; } public decimal Value { get; set; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/MetadataSource/SkyHook/Resource/SeasonResource.cs b/src/NzbDrone.Core/MetadataSource/SkyHook/Resource/SeasonResource.cs index 55ce6ccf9..eb9433b71 100644 --- a/src/NzbDrone.Core/MetadataSource/SkyHook/Resource/SeasonResource.cs +++ b/src/NzbDrone.Core/MetadataSource/SkyHook/Resource/SeasonResource.cs @@ -8,8 +8,8 @@ public SeasonResource() { Images = new List(); } - + public int SeasonNumber { get; set; } public List Images { get; set; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/MetadataSource/SkyHook/Resource/ShowResource.cs b/src/NzbDrone.Core/MetadataSource/SkyHook/Resource/ShowResource.cs index fd442100d..76fc0ecd9 100644 --- a/src/NzbDrone.Core/MetadataSource/SkyHook/Resource/ShowResource.cs +++ b/src/NzbDrone.Core/MetadataSource/SkyHook/Resource/ShowResource.cs @@ -16,6 +16,7 @@ public ShowResource() public int TvdbId { get; set; } public string Title { get; set; } public string Overview { get; set; } + //public string Language { get; set; } public string Slug { get; set; } public string FirstAired { get; set; } @@ -40,4 +41,4 @@ public ShowResource() public List Seasons { get; set; } public List Episodes { get; set; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/MetadataSource/SkyHook/Resource/TimeOfDayResource.cs b/src/NzbDrone.Core/MetadataSource/SkyHook/Resource/TimeOfDayResource.cs index 242f92a7c..6bd3d232c 100644 --- a/src/NzbDrone.Core/MetadataSource/SkyHook/Resource/TimeOfDayResource.cs +++ b/src/NzbDrone.Core/MetadataSource/SkyHook/Resource/TimeOfDayResource.cs @@ -5,4 +5,4 @@ public class TimeOfDayResource public int Hours { get; set; } public int Minutes { get; set; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/MetadataSource/SkyHook/SkyHookException.cs b/src/NzbDrone.Core/MetadataSource/SkyHook/SkyHookException.cs index fb6c02d49..8fcc9c5bf 100644 --- a/src/NzbDrone.Core/MetadataSource/SkyHook/SkyHookException.cs +++ b/src/NzbDrone.Core/MetadataSource/SkyHook/SkyHookException.cs @@ -6,7 +6,8 @@ namespace NzbDrone.Core.MetadataSource.SkyHook { public class SkyHookException : NzbDroneClientException { - public SkyHookException(string message) : base(HttpStatusCode.ServiceUnavailable, message) + public SkyHookException(string message) + : base(HttpStatusCode.ServiceUnavailable, message) { } diff --git a/src/NzbDrone.Core/MetadataSource/SkyHook/SkyHookProxy.cs b/src/NzbDrone.Core/MetadataSource/SkyHook/SkyHookProxy.cs index 606a6871e..331a93027 100644 --- a/src/NzbDrone.Core/MetadataSource/SkyHook/SkyHookProxy.cs +++ b/src/NzbDrone.Core/MetadataSource/SkyHook/SkyHookProxy.cs @@ -30,7 +30,7 @@ public SkyHookProxy(IHttpClient httpClient, Logger logger) { _httpClient = httpClient; - _requestBuilder = requestBuilder.SkyHookTvdb; + _requestBuilder = requestBuilder.SkyHookTvdb; _logger = logger; _seriesService = seriesService; _dailySeriesService = dailySeriesService; diff --git a/src/NzbDrone.Core/Notifications/Boxcar/Boxcar.cs b/src/NzbDrone.Core/Notifications/Boxcar/Boxcar.cs index ba4b5b739..10b24b224 100644 --- a/src/NzbDrone.Core/Notifications/Boxcar/Boxcar.cs +++ b/src/NzbDrone.Core/Notifications/Boxcar/Boxcar.cs @@ -1,4 +1,4 @@ -using System.Collections.Generic; +using System.Collections.Generic; using FluentValidation.Results; using NzbDrone.Common.Extensions; @@ -45,6 +45,7 @@ public override void OnApplicationUpdate(ApplicationUpdateMessage message) { _proxy.SendNotification(APPLICATION_UPDATE_TITLE, message.Message, Settings); } + public override ValidationResult Test() { var failures = new List(); diff --git a/src/NzbDrone.Core/Notifications/Boxcar/BoxcarException.cs b/src/NzbDrone.Core/Notifications/Boxcar/BoxcarException.cs index 139c3b1ab..6108d4aab 100644 --- a/src/NzbDrone.Core/Notifications/Boxcar/BoxcarException.cs +++ b/src/NzbDrone.Core/Notifications/Boxcar/BoxcarException.cs @@ -5,11 +5,13 @@ namespace NzbDrone.Core.Notifications.Boxcar { public class BoxcarException : NzbDroneException { - public BoxcarException(string message) : base(message) + public BoxcarException(string message) + : base(message) { } - public BoxcarException(string message, Exception innerException, params object[] args) : base(message, innerException, args) + public BoxcarException(string message, Exception innerException, params object[] args) + : base(message, innerException, args) { } } diff --git a/src/NzbDrone.Core/Notifications/Boxcar/BoxcarProxy.cs b/src/NzbDrone.Core/Notifications/Boxcar/BoxcarProxy.cs index e372bbaae..fda8dc71e 100644 --- a/src/NzbDrone.Core/Notifications/Boxcar/BoxcarProxy.cs +++ b/src/NzbDrone.Core/Notifications/Boxcar/BoxcarProxy.cs @@ -15,9 +15,10 @@ public interface IBoxcarProxy public class BoxcarProxy : IBoxcarProxy { + private const string URL = "https://new.boxcar.io/api/notifications"; + private readonly IHttpClient _httpClient; private readonly Logger _logger; - private const string URL = "https://new.boxcar.io/api/notifications"; public BoxcarProxy(IHttpClient httpClient, Logger logger) { diff --git a/src/NzbDrone.Core/Notifications/Discord/Discord.cs b/src/NzbDrone.Core/Notifications/Discord/Discord.cs index fb382c508..2970bc4df 100644 --- a/src/NzbDrone.Core/Notifications/Discord/Discord.cs +++ b/src/NzbDrone.Core/Notifications/Discord/Discord.cs @@ -329,6 +329,7 @@ public override void OnApplicationUpdate(ApplicationUpdateMessage updateMessage) _proxy.SendPayload(payload, Settings); } + public override ValidationResult Test() { var failures = new List(); @@ -346,7 +347,6 @@ public ValidationFailure TestMessage() var payload = CreatePayload(message); _proxy.SendPayload(payload, Settings); - } catch (DiscordException ex) { diff --git a/src/NzbDrone.Core/Notifications/Discord/DiscordException.cs b/src/NzbDrone.Core/Notifications/Discord/DiscordException.cs index 38c44713d..79b2bbfaf 100644 --- a/src/NzbDrone.Core/Notifications/Discord/DiscordException.cs +++ b/src/NzbDrone.Core/Notifications/Discord/DiscordException.cs @@ -5,11 +5,13 @@ namespace NzbDrone.Core.Notifications.Discord { public class DiscordException : NzbDroneException { - public DiscordException(string message) : base(message) + public DiscordException(string message) + : base(message) { } - public DiscordException(string message, Exception innerException, params object[] args) : base(message, innerException, args) + public DiscordException(string message, Exception innerException, params object[] args) + : base(message, innerException, args) { } } diff --git a/src/NzbDrone.Core/Notifications/Discord/DiscordProxy.cs b/src/NzbDrone.Core/Notifications/Discord/DiscordProxy.cs index 9bcbeb454..f3a6be3d2 100644 --- a/src/NzbDrone.Core/Notifications/Discord/DiscordProxy.cs +++ b/src/NzbDrone.Core/Notifications/Discord/DiscordProxy.cs @@ -33,7 +33,7 @@ public void SendPayload(DiscordPayload payload, DiscordSettings settings) request.Headers.ContentType = "application/json"; request.SetContent(payload.ToJson()); - _httpClient.Execute(request); + _httpClient.Execute(request); } catch (HttpException ex) { diff --git a/src/NzbDrone.Core/Notifications/Discord/DiscordSettings.cs b/src/NzbDrone.Core/Notifications/Discord/DiscordSettings.cs index 48e917b83..766afc2f0 100644 --- a/src/NzbDrone.Core/Notifications/Discord/DiscordSettings.cs +++ b/src/NzbDrone.Core/Notifications/Discord/DiscordSettings.cs @@ -19,8 +19,8 @@ public class DiscordSettings : IProviderConfig public DiscordSettings() { //Set Default Fields - GrabFields = new [] { 0, 1, 2, 3, 5, 6, 7, 8, 9 }; - ImportFields = new [] { 0, 1, 2, 3, 4, 6, 7, 8, 9, 10, 11, 12 }; + GrabFields = new[] { 0, 1, 2, 3, 5, 6, 7, 8, 9 }; + ImportFields = new[] { 0, 1, 2, 3, 4, 6, 7, 8, 9, 10, 11, 12 }; } private static readonly DiscordSettingsValidator Validator = new DiscordSettingsValidator(); diff --git a/src/NzbDrone.Core/Notifications/Email/Email.cs b/src/NzbDrone.Core/Notifications/Email/Email.cs index a58e17264..10d5cc370 100644 --- a/src/NzbDrone.Core/Notifications/Email/Email.cs +++ b/src/NzbDrone.Core/Notifications/Email/Email.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using FluentValidation.Results; @@ -16,7 +16,6 @@ public class Email : NotificationBase public override string Name => "Email"; - public Email(Logger logger) { _logger = logger; @@ -63,6 +62,7 @@ public override void OnApplicationUpdate(ApplicationUpdateMessage updateMessage) SendEmail(Settings, APPLICATION_UPDATE_TITLE_BRANDED, body); } + public override ValidationResult Test() { var failures = new List(); @@ -93,7 +93,6 @@ private void SendEmail(EmailSettings settings, string subject, string body, bool { Send(email, settings); _logger.Debug("Email sent. Subject: {0}", subject); - } catch (Exception ex) { @@ -138,7 +137,6 @@ private void Send(MimeMessage email, EmailSettings settings) _logger.Debug("Sending to mail server"); - client.Send(email); _logger.Debug("Sent to mail server, disconnecting"); diff --git a/src/NzbDrone.Core/Notifications/EpisodeDeleteMessage.cs b/src/NzbDrone.Core/Notifications/EpisodeDeleteMessage.cs index 0084a8822..b9213b6bf 100644 --- a/src/NzbDrone.Core/Notifications/EpisodeDeleteMessage.cs +++ b/src/NzbDrone.Core/Notifications/EpisodeDeleteMessage.cs @@ -17,4 +17,3 @@ public override string ToString() } } } - diff --git a/src/NzbDrone.Core/Notifications/Gotify/GotifyPriority.cs b/src/NzbDrone.Core/Notifications/Gotify/GotifyPriority.cs index 8782d4dcd..9a5f9c5dc 100644 --- a/src/NzbDrone.Core/Notifications/Gotify/GotifyPriority.cs +++ b/src/NzbDrone.Core/Notifications/Gotify/GotifyPriority.cs @@ -1,5 +1,4 @@ namespace NzbDrone.Core.Notifications.Gotify - { public enum GotifyPriority { diff --git a/src/NzbDrone.Core/Notifications/Join/Join.cs b/src/NzbDrone.Core/Notifications/Join/Join.cs index 2f9df88e6..103e188ec 100644 --- a/src/NzbDrone.Core/Notifications/Join/Join.cs +++ b/src/NzbDrone.Core/Notifications/Join/Join.cs @@ -31,6 +31,7 @@ public override void OnEpisodeFileDelete(EpisodeDeleteMessage deleteMessage) { _proxy.SendNotification(EPISODE_DELETED_TITLE_BRANDED, deleteMessage.Message, Settings); } + public override void OnSeriesDelete(SeriesDeleteMessage deleteMessage) { _proxy.SendNotification(SERIES_DELETED_TITLE_BRANDED, deleteMessage.Message, Settings); diff --git a/src/NzbDrone.Core/Notifications/Join/JoinAuthException.cs b/src/NzbDrone.Core/Notifications/Join/JoinAuthException.cs index 92b977722..12c55b2c3 100644 --- a/src/NzbDrone.Core/Notifications/Join/JoinAuthException.cs +++ b/src/NzbDrone.Core/Notifications/Join/JoinAuthException.cs @@ -4,11 +4,13 @@ namespace NzbDrone.Core.Notifications.Join { public class JoinAuthException : JoinException { - public JoinAuthException(string message) : base(message) + public JoinAuthException(string message) + : base(message) { } - public JoinAuthException(string message, Exception innerException, params object[] args) : base(message, innerException, args) + public JoinAuthException(string message, Exception innerException, params object[] args) + : base(message, innerException, args) { } } diff --git a/src/NzbDrone.Core/Notifications/Join/JoinException.cs b/src/NzbDrone.Core/Notifications/Join/JoinException.cs index e0ad0e1c3..18ef5e2f2 100644 --- a/src/NzbDrone.Core/Notifications/Join/JoinException.cs +++ b/src/NzbDrone.Core/Notifications/Join/JoinException.cs @@ -5,11 +5,13 @@ namespace NzbDrone.Core.Notifications.Join { public class JoinException : NzbDroneException { - public JoinException(string message) : base(message) + public JoinException(string message) + : base(message) { } - public JoinException(string message, Exception innerException, params object[] args) : base(message, innerException, args) + public JoinException(string message, Exception innerException, params object[] args) + : base(message, innerException, args) { } } diff --git a/src/NzbDrone.Core/Notifications/Join/JoinInvalidDeviceException.cs b/src/NzbDrone.Core/Notifications/Join/JoinInvalidDeviceException.cs index a6463abb4..d79e989ec 100644 --- a/src/NzbDrone.Core/Notifications/Join/JoinInvalidDeviceException.cs +++ b/src/NzbDrone.Core/Notifications/Join/JoinInvalidDeviceException.cs @@ -4,11 +4,13 @@ namespace NzbDrone.Core.Notifications.Join { public class JoinInvalidDeviceException : JoinException { - public JoinInvalidDeviceException(string message) : base(message) + public JoinInvalidDeviceException(string message) + : base(message) { } - public JoinInvalidDeviceException(string message, Exception innerException, params object[] args) : base(message, innerException, args) + public JoinInvalidDeviceException(string message, Exception innerException, params object[] args) + : base(message, innerException, args) { } } diff --git a/src/NzbDrone.Core/Notifications/Join/JoinProxy.cs b/src/NzbDrone.Core/Notifications/Join/JoinProxy.cs index afe077a76..b96508b75 100644 --- a/src/NzbDrone.Core/Notifications/Join/JoinProxy.cs +++ b/src/NzbDrone.Core/Notifications/Join/JoinProxy.cs @@ -2,8 +2,6 @@ using FluentValidation.Results; using NLog; using NzbDrone.Common.Extensions; -using RestSharp; -using NzbDrone.Core.Rest; using NzbDrone.Common.Http; using NzbDrone.Common.Serializer; @@ -17,9 +15,10 @@ public interface IJoinProxy public class JoinProxy : IJoinProxy { + private const string URL = "https://joinjoaomgcd.appspot.com/_ah/api/messaging/v1/sendPush?"; + private readonly IHttpClient _httpClient; private readonly Logger _logger; - private const string URL = "https://joinjoaomgcd.appspot.com/_ah/api/messaging/v1/sendPush?"; public JoinProxy(IHttpClient httpClient, Logger logger) { @@ -104,7 +103,10 @@ private void SendNotification(string title, string message, HttpMethod method, J var response = _httpClient.Execute(request); var res = Json.Deserialize(response.Content); - if (res.success) return; + if (res.success) + { + return; + } if (res.userAuthError) { @@ -119,14 +121,16 @@ private void SendNotification(string title, string message, HttpMethod method, J { throw new JoinInvalidDeviceException(res.errorMessage); } + // Oddly enough, rather than give us an "Invalid API key", the Join API seems to assume the key is valid, - // but fails when doing a device lookup associated with that key. + // but fails when doing a device lookup associated with that key. // In our case we are using "deviceIds" rather than "deviceId" so when the singular form error shows up // we know the API key was the fault. else if (res.errorMessage.Equals("No device to send message to")) { throw new JoinAuthException("Authentication failed."); } + throw new JoinException(res.errorMessage); } diff --git a/src/NzbDrone.Core/Notifications/Join/JoinSettings.cs b/src/NzbDrone.Core/Notifications/Join/JoinSettings.cs index 797e7230a..db5c8550a 100644 --- a/src/NzbDrone.Core/Notifications/Join/JoinSettings.cs +++ b/src/NzbDrone.Core/Notifications/Join/JoinSettings.cs @@ -16,7 +16,6 @@ public JoinSettingsValidator() public class JoinSettings : IProviderConfig { - public JoinSettings() { Priority = (int)JoinPriority.Normal; diff --git a/src/NzbDrone.Core/Notifications/Mailgun/MailgunException.cs b/src/NzbDrone.Core/Notifications/Mailgun/MailgunException.cs index e09e3e050..4ddd53814 100644 --- a/src/NzbDrone.Core/Notifications/Mailgun/MailgunException.cs +++ b/src/NzbDrone.Core/Notifications/Mailgun/MailgunException.cs @@ -5,9 +5,14 @@ namespace NzbDrone.Core.Notifications.Mailgun { public class MailgunException : NzbDroneException { - public MailgunException(string message) : base (message) { } - + public MailgunException(string message) + : base(message) + { + } + public MailgunException(string message, Exception innerException, params object[] args) - : base(message, innerException, args) { } + : base(message, innerException, args) + { + } } } diff --git a/src/NzbDrone.Core/Notifications/Mailgun/MailgunProxy.cs b/src/NzbDrone.Core/Notifications/Mailgun/MailgunProxy.cs index 47e4d39c7..837cb4ee0 100644 --- a/src/NzbDrone.Core/Notifications/Mailgun/MailgunProxy.cs +++ b/src/NzbDrone.Core/Notifications/Mailgun/MailgunProxy.cs @@ -3,19 +3,20 @@ using NzbDrone.Common.Http; using HttpMethod = NzbDrone.Common.Http.HttpMethod; -namespace NzbDrone.Core.Notifications.Mailgun { +namespace NzbDrone.Core.Notifications.Mailgun +{ public interface IMailgunProxy { void SendNotification(string tittle, string message, MailgunSettings settings); } - + public class MailgunProxy : IMailgunProxy { - private readonly IHttpClient _httpClient; - private readonly Logger _logger; private const string BaseUrlEu = "https://api.eu.mailgun.net/v3"; private const string BaseUrlUs = "https://api.mailgun.net/v3"; + private readonly IHttpClient _httpClient; + private readonly Logger _logger; public MailgunProxy(IHttpClient httpClient, Logger logger) { @@ -27,8 +28,7 @@ public void SendNotification(string title, string message, MailgunSettings setti { try { - var request = BuildRequest(settings, $"{settings.SenderDomain}/messages", HttpMethod.POST, - title, message).Build(); + var request = BuildRequest(settings, $"{settings.SenderDomain}/messages", HttpMethod.POST, title, message).Build(); _httpClient.Execute(request); } catch (HttpException ex) @@ -37,32 +37,30 @@ public void SendNotification(string title, string message, MailgunSettings setti { throw new MailgunException("Unauthorised - ApiKey is invalid"); } - + throw new MailgunException("Unable to connect to Mailgun. Status code: {0}", ex); } } - - private HttpRequestBuilder BuildRequest(MailgunSettings settings, string resource, HttpMethod method, - string messageSubject, string messageBody) + private HttpRequestBuilder BuildRequest(MailgunSettings settings, string resource, HttpMethod method, string messageSubject, string messageBody) { var loginCredentials = new NetworkCredential("api", settings.ApiKey); var url = settings.UseEuEndpoint ? BaseUrlEu : BaseUrlUs; var requestBuilder = new HttpRequestBuilder(url).Resource(resource); - + requestBuilder.Method = method; requestBuilder.NetworkCredential = loginCredentials; - + requestBuilder.AddFormParameter("from", $"{settings.From}"); - + foreach (var recipient in settings.Recipients) - { + { requestBuilder.AddFormParameter("to", $"{recipient}"); } - + requestBuilder.AddFormParameter("subject", $"{messageSubject}"); requestBuilder.AddFormParameter("text", $"{messageBody}"); - + return requestBuilder; } } diff --git a/src/NzbDrone.Core/Notifications/Mailgun/MailgunSettings.cs b/src/NzbDrone.Core/Notifications/Mailgun/MailgunSettings.cs index 3bcedf11b..b09824ac3 100644 --- a/src/NzbDrone.Core/Notifications/Mailgun/MailgunSettings.cs +++ b/src/NzbDrone.Core/Notifications/Mailgun/MailgunSettings.cs @@ -15,7 +15,7 @@ public MailGunSettingsValidator() RuleFor(c => c.Recipients).NotEmpty(); } } - + public class MailgunSettings : IProviderConfig { private static readonly MailGunSettingsValidator Validator = new MailGunSettingsValidator(); @@ -24,20 +24,19 @@ public MailgunSettings() { Recipients = new string[] { }; } - - + [FieldDefinition(0, Label = "API Key", HelpText = "The API key generated from MailGun")] public string ApiKey { get; set; } - + [FieldDefinition(1, Label = "Use EU Endpoint?", HelpText = "You can choose to use the EU MailGun endpoint with this", Type = FieldType.Checkbox)] public bool UseEuEndpoint { get; set; } - + [FieldDefinition(2, Label = "From Address")] public string From { get; set; } - + [FieldDefinition(3, Label = "Sender Domain")] public string SenderDomain { get; set; } - + [FieldDefinition(4, Label = "Recipient Address(es)", Type = FieldType.Tag)] public IEnumerable Recipients { get; set; } diff --git a/src/NzbDrone.Core/Notifications/MediaBrowser/MediaBrowser.cs b/src/NzbDrone.Core/Notifications/MediaBrowser/MediaBrowser.cs index 41d9af18f..196261f7f 100644 --- a/src/NzbDrone.Core/Notifications/MediaBrowser/MediaBrowser.cs +++ b/src/NzbDrone.Core/Notifications/MediaBrowser/MediaBrowser.cs @@ -18,7 +18,6 @@ public MediaBrowser(IMediaBrowserService mediaBrowserService) public override string Link => "https://emby.media/"; public override string Name => "Emby"; - public override void OnGrab(GrabMessage grabMessage) { if (Settings.Notify) diff --git a/src/NzbDrone.Core/Notifications/MediaBrowser/MediaBrowserProxy.cs b/src/NzbDrone.Core/Notifications/MediaBrowser/MediaBrowserProxy.cs index 3df841729..cb32aa154 100644 --- a/src/NzbDrone.Core/Notifications/MediaBrowser/MediaBrowserProxy.cs +++ b/src/NzbDrone.Core/Notifications/MediaBrowser/MediaBrowserProxy.cs @@ -68,7 +68,7 @@ private HttpRequest BuildRequest(string path, MediaBrowserSettings settings) { var scheme = settings.UseSsl ? "https" : "http"; var url = $@"{scheme}://{settings.Address}/mediabrowser"; - + return new HttpRequestBuilder(url).Resource(path).Build(); } diff --git a/src/NzbDrone.Core/Notifications/NotificationBase.cs b/src/NzbDrone.Core/Notifications/NotificationBase.cs index 8cffdea17..29cf6e012 100644 --- a/src/NzbDrone.Core/Notifications/NotificationBase.cs +++ b/src/NzbDrone.Core/Notifications/NotificationBase.cs @@ -8,7 +8,8 @@ namespace NzbDrone.Core.Notifications { - public abstract class NotificationBase : INotification where TSettings : IProviderConfig, new() + public abstract class NotificationBase : INotification + where TSettings : IProviderConfig, new() { protected const string EPISODE_GRABBED_TITLE = "Episode Grabbed"; protected const string EPISODE_DOWNLOADED_TITLE = "Episode Downloaded"; @@ -39,32 +40,26 @@ namespace NzbDrone.Core.Notifications public virtual void OnGrab(GrabMessage grabMessage) { - } public virtual void OnDownload(DownloadMessage message) { - } public virtual void OnRename(Series series, List renamedFiles) { - } public virtual void OnEpisodeFileDelete(EpisodeDeleteMessage deleteMessage) { - } public virtual void OnSeriesDelete(SeriesDeleteMessage deleteMessage) { - } public virtual void OnHealthIssue(HealthCheck.HealthCheck healthCheck) { - } public virtual void OnApplicationUpdate(ApplicationUpdateMessage updateMessage) @@ -73,7 +68,6 @@ public virtual void OnApplicationUpdate(ApplicationUpdateMessage updateMessage) public virtual void ProcessQueue() { - } public bool SupportsOnGrab => HasConcreteImplementation("OnGrab"); @@ -93,8 +87,10 @@ public override string ToString() return GetType().Name; } - public virtual object RequestAction(string action, IDictionary query) { return null; } - + public virtual object RequestAction(string action, IDictionary query) + { + return null; + } private bool HasConcreteImplementation(string methodName) { diff --git a/src/NzbDrone.Core/Notifications/NotificationFactory.cs b/src/NzbDrone.Core/Notifications/NotificationFactory.cs index b4b366a94..6e526637c 100644 --- a/src/NzbDrone.Core/Notifications/NotificationFactory.cs +++ b/src/NzbDrone.Core/Notifications/NotificationFactory.cs @@ -61,6 +61,7 @@ public List OnEpisodeFileDeleteForUpgradeEnabled() { return GetAvailableProviders().Where(n => ((NotificationDefinition)n.Definition).OnEpisodeFileDeleteForUpgrade).ToList(); } + public List OnHealthIssueEnabled() { return GetAvailableProviders().Where(n => ((NotificationDefinition)n.Definition).OnHealthIssue).ToList(); diff --git a/src/NzbDrone.Core/Notifications/NotificationRepository.cs b/src/NzbDrone.Core/Notifications/NotificationRepository.cs index 4dddebba9..96ff55b52 100644 --- a/src/NzbDrone.Core/Notifications/NotificationRepository.cs +++ b/src/NzbDrone.Core/Notifications/NotificationRepository.cs @@ -1,8 +1,7 @@ -using NzbDrone.Core.Datastore; +using NzbDrone.Core.Datastore; using NzbDrone.Core.Messaging.Events; using NzbDrone.Core.ThingiProvider; - namespace NzbDrone.Core.Notifications { public interface INotificationRepository : IProviderRepository @@ -16,9 +15,10 @@ public NotificationRepository(IMainDatabase database, IEventAggregator eventAggr : base(database, eventAggregator) { } + public void UpdateSettings(NotificationDefinition model) { SetFields(model, m => m.Settings); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Notifications/NotificationService.cs b/src/NzbDrone.Core/Notifications/NotificationService.cs index 1934e6743..2557ef019 100644 --- a/src/NzbDrone.Core/Notifications/NotificationService.cs +++ b/src/NzbDrone.Core/Notifications/NotificationService.cs @@ -47,7 +47,6 @@ private string GetMessage(Series series, List episodes, QualityModel qu { qualityString += " v" + quality.Revision.Version; } - else { qualityString += " Proper"; @@ -128,10 +127,13 @@ public void Handle(EpisodeGrabbedEvent message) { try { - if (!ShouldHandleSeries(notification.Definition, message.Episode.Series)) continue; + if (!ShouldHandleSeries(notification.Definition, message.Episode.Series)) + { + continue; + } + notification.OnGrab(grabMessage); } - catch (Exception ex) { _logger.Error(ex, "Unable to send OnGrab notification to {0}", notification.Definition.Name); @@ -169,7 +171,6 @@ public void Handle(EpisodeImportedEvent message) } } } - catch (Exception ex) { _logger.Warn(ex, "Unable to send OnDownload notification to: " + notification.Definition.Name); @@ -188,7 +189,6 @@ public void Handle(SeriesRenamedEvent message) notification.OnRename(message.Series, message.RenamedFiles); } } - catch (Exception ex) { _logger.Warn(ex, "Unable to send OnRename notification to: " + notification.Definition.Name); @@ -289,7 +289,6 @@ public void Handle(HealthCheckFailedEvent message) notification.OnHealthIssue(message.HealthCheck); } } - catch (Exception ex) { _logger.Warn(ex, "Unable to send OnHealthIssue notification to: " + notification.Definition.Name); diff --git a/src/NzbDrone.Core/Notifications/Plex/PlexAuthenticationException.cs b/src/NzbDrone.Core/Notifications/Plex/PlexAuthenticationException.cs index 86a0d15ec..4235168b4 100644 --- a/src/NzbDrone.Core/Notifications/Plex/PlexAuthenticationException.cs +++ b/src/NzbDrone.Core/Notifications/Plex/PlexAuthenticationException.cs @@ -2,7 +2,8 @@ { public class PlexAuthenticationException : PlexException { - public PlexAuthenticationException(string message) : base(message) + public PlexAuthenticationException(string message) + : base(message) { } diff --git a/src/NzbDrone.Core/Notifications/Plex/PlexException.cs b/src/NzbDrone.Core/Notifications/Plex/PlexException.cs index 402f4a448..c545c20f5 100644 --- a/src/NzbDrone.Core/Notifications/Plex/PlexException.cs +++ b/src/NzbDrone.Core/Notifications/Plex/PlexException.cs @@ -5,15 +5,18 @@ namespace NzbDrone.Core.Notifications.Plex { public class PlexException : NzbDroneException { - public PlexException(string message) : base(message) + public PlexException(string message) + : base(message) { } - public PlexException(string message, params object[] args) : base(message, args) + public PlexException(string message, params object[] args) + : base(message, args) { } - public PlexException(string message, Exception innerException) : base(message, innerException) + public PlexException(string message, Exception innerException) + : base(message, innerException) { } } diff --git a/src/NzbDrone.Core/Notifications/Plex/PlexVersionException.cs b/src/NzbDrone.Core/Notifications/Plex/PlexVersionException.cs index 439cb57ac..42c7889da 100644 --- a/src/NzbDrone.Core/Notifications/Plex/PlexVersionException.cs +++ b/src/NzbDrone.Core/Notifications/Plex/PlexVersionException.cs @@ -4,11 +4,13 @@ namespace NzbDrone.Core.Notifications.Plex { public class PlexVersionException : NzbDroneException { - public PlexVersionException(string message) : base(message) + public PlexVersionException(string message) + : base(message) { } - public PlexVersionException(string message, params object[] args) : base(message, args) + public PlexVersionException(string message, params object[] args) + : base(message, args) { } } diff --git a/src/NzbDrone.Core/Notifications/Plex/Server/PlexServer.cs b/src/NzbDrone.Core/Notifications/Plex/Server/PlexServer.cs index dbda0a22a..ba1caa0a4 100644 --- a/src/NzbDrone.Core/Notifications/Plex/Server/PlexServer.cs +++ b/src/NzbDrone.Core/Notifications/Plex/Server/PlexServer.cs @@ -19,7 +19,7 @@ public class PlexServer : NotificationBase private readonly IPlexTvService _plexTvService; private readonly Logger _logger; - class PlexUpdateQueue + private class PlexUpdateQueue { public Dictionary Pending { get; } = new Dictionary(); public bool Refreshing { get; set; } @@ -89,8 +89,10 @@ public override void ProcessQueue() { return; } + queue.Refreshing = true; } + try { while (true) diff --git a/src/NzbDrone.Core/Notifications/Plex/Server/PlexServerProxy.cs b/src/NzbDrone.Core/Notifications/Plex/Server/PlexServerProxy.cs index 537af484f..5b802857e 100644 --- a/src/NzbDrone.Core/Notifications/Plex/Server/PlexServerProxy.cs +++ b/src/NzbDrone.Core/Notifications/Plex/Server/PlexServerProxy.cs @@ -26,7 +26,7 @@ public class PlexServerProxy : IPlexServerProxy private readonly IConfigService _configService; private readonly Logger _logger; - public PlexServerProxy(IHttpClient httpClient, IConfigService configService,Logger logger) + public PlexServerProxy(IHttpClient httpClient, IConfigService configService, Logger logger) { _httpClient = httpClient; _configService = configService; @@ -132,7 +132,6 @@ public string GetMetadataId(int sectionId, int tvdbId, string language, PlexServ items = Json.Deserialize(response) .Items; } - else { items = Json.Deserialize>(response) @@ -217,7 +216,7 @@ private void CheckForError(string response) } var error = response.Contains("_children") ? - Json.Deserialize(response) : + Json.Deserialize(response) : Json.Deserialize>(response).MediaContainer; if (error != null && !error.Error.IsNullOrWhiteSpace()) diff --git a/src/NzbDrone.Core/Notifications/Plex/Server/PlexServerService.cs b/src/NzbDrone.Core/Notifications/Plex/Server/PlexServerService.cs index 72b50357a..1b4914ec1 100644 --- a/src/NzbDrone.Core/Notifications/Plex/Server/PlexServerService.cs +++ b/src/NzbDrone.Core/Notifications/Plex/Server/PlexServerService.cs @@ -80,7 +80,6 @@ public void UpdateLibrary(IEnumerable multipleSeries, PlexServerSettings _logger.Debug("Finished sending Update Request to Plex Server (took {0} ms)", watch.ElapsedMilliseconds); } - catch (Exception ex) { _logger.Warn(ex, "Failed to Update Plex host: " + settings.Host); diff --git a/src/NzbDrone.Core/Notifications/PushBullet/PushBullet.cs b/src/NzbDrone.Core/Notifications/PushBullet/PushBullet.cs index e5eb34a29..43e7dfa68 100644 --- a/src/NzbDrone.Core/Notifications/PushBullet/PushBullet.cs +++ b/src/NzbDrone.Core/Notifications/PushBullet/PushBullet.cs @@ -33,6 +33,7 @@ public override void OnEpisodeFileDelete(EpisodeDeleteMessage deleteMessage) { _proxy.SendNotification(EPISODE_DELETED_TITLE, deleteMessage.Message, Settings); } + public override void OnSeriesDelete(SeriesDeleteMessage deleteMessage) { _proxy.SendNotification(SERIES_DELETED_TITLE, deleteMessage.Message, Settings); @@ -78,10 +79,10 @@ public override object RequestAction(string action, IDictionary options = devices.Where(d => d.Nickname.IsNotNullOrWhiteSpace()) .OrderBy(d => d.Nickname, StringComparer.InvariantCultureIgnoreCase) .Select(d => new - { - id = d.Id, - name = d.Nickname - }) + { + id = d.Id, + name = d.Nickname + }) }; } diff --git a/src/NzbDrone.Core/Notifications/PushBullet/PushBulletException.cs b/src/NzbDrone.Core/Notifications/PushBullet/PushBulletException.cs index ce8b8417d..f8207ef01 100644 --- a/src/NzbDrone.Core/Notifications/PushBullet/PushBulletException.cs +++ b/src/NzbDrone.Core/Notifications/PushBullet/PushBulletException.cs @@ -5,11 +5,13 @@ namespace NzbDrone.Core.Notifications.PushBullet { public class PushBulletException : NzbDroneException { - public PushBulletException(string message) : base(message) + public PushBulletException(string message) + : base(message) { } - public PushBulletException(string message, Exception innerException, params object[] args) : base(message, innerException, args) + public PushBulletException(string message, Exception innerException, params object[] args) + : base(message, innerException, args) { } } diff --git a/src/NzbDrone.Core/Notifications/PushBullet/PushBulletProxy.cs b/src/NzbDrone.Core/Notifications/PushBullet/PushBulletProxy.cs index abe2c3f50..563e21d46 100644 --- a/src/NzbDrone.Core/Notifications/PushBullet/PushBulletProxy.cs +++ b/src/NzbDrone.Core/Notifications/PushBullet/PushBulletProxy.cs @@ -162,7 +162,6 @@ private HttpRequestBuilder BuildDeviceRequest(string deviceId) { requestBuilder.AddFormParameter("device_id", integerId); } - else { requestBuilder.AddFormParameter("device_iden", deviceId); diff --git a/src/NzbDrone.Core/Notifications/Pushover/InvalidResponseException.cs b/src/NzbDrone.Core/Notifications/Pushover/InvalidResponseException.cs index 7e6fc1f4a..6f9c139a2 100644 --- a/src/NzbDrone.Core/Notifications/Pushover/InvalidResponseException.cs +++ b/src/NzbDrone.Core/Notifications/Pushover/InvalidResponseException.cs @@ -8,7 +8,8 @@ public InvalidResponseException() { } - public InvalidResponseException(string message) : base(message) + public InvalidResponseException(string message) + : base(message) { } } diff --git a/src/NzbDrone.Core/Notifications/Pushover/PushoverProxy.cs b/src/NzbDrone.Core/Notifications/Pushover/PushoverProxy.cs index ced1e5896..91e1f4444 100644 --- a/src/NzbDrone.Core/Notifications/Pushover/PushoverProxy.cs +++ b/src/NzbDrone.Core/Notifications/Pushover/PushoverProxy.cs @@ -14,9 +14,10 @@ public interface IPushoverProxy public class PushoverProxy : IPushoverProxy { + private const string URL = "https://api.pushover.net/1/messages.json"; + private readonly IHttpClient _httpClient; private readonly Logger _logger; - private const string URL = "https://api.pushover.net/1/messages.json"; public PushoverProxy(IHttpClient httpClient, Logger logger) { @@ -46,7 +47,6 @@ public void SendNotification(string title, string message, PushoverSettings sett requestBuilder.AddFormParameter("sound", settings.Sound); } - var request = requestBuilder.Build(); _httpClient.Post(request); diff --git a/src/NzbDrone.Core/Notifications/Pushover/PushoverSettings.cs b/src/NzbDrone.Core/Notifications/Pushover/PushoverSettings.cs index 72eff802b..a4e80cf43 100644 --- a/src/NzbDrone.Core/Notifications/Pushover/PushoverSettings.cs +++ b/src/NzbDrone.Core/Notifications/Pushover/PushoverSettings.cs @@ -1,8 +1,8 @@ +using System.Collections.Generic; using FluentValidation; using NzbDrone.Core.Annotations; using NzbDrone.Core.ThingiProvider; using NzbDrone.Core.Validation; -using System.Collections.Generic; namespace NzbDrone.Core.Notifications.Pushover { @@ -36,7 +36,7 @@ public PushoverSettings() [FieldDefinition(2, Label = "Devices", HelpText = "List of device names (leave blank to send to all devices)", Type = FieldType.Tag)] public IEnumerable Devices { get; set; } - [FieldDefinition(3, Label = "Priority", Type = FieldType.Select, SelectOptions = typeof(PushoverPriority) )] + [FieldDefinition(3, Label = "Priority", Type = FieldType.Select, SelectOptions = typeof(PushoverPriority))] public int Priority { get; set; } [FieldDefinition(4, Label = "Retry", Type = FieldType.Textbox, HelpText = "Interval to retry Emergency alerts, minimum 30 seconds")] diff --git a/src/NzbDrone.Core/Notifications/SendGrid/SendGrid.cs b/src/NzbDrone.Core/Notifications/SendGrid/SendGrid.cs index 265f4d1be..18bf9ea01 100644 --- a/src/NzbDrone.Core/Notifications/SendGrid/SendGrid.cs +++ b/src/NzbDrone.Core/Notifications/SendGrid/SendGrid.cs @@ -33,6 +33,7 @@ public override void OnEpisodeFileDelete(EpisodeDeleteMessage deleteMessage) { _proxy.SendNotification(EPISODE_DELETED_TITLE, deleteMessage.Message, Settings); } + public override void OnSeriesDelete(SeriesDeleteMessage deleteMessage) { _proxy.SendNotification(SERIES_DELETED_TITLE, deleteMessage.Message, Settings); diff --git a/src/NzbDrone.Core/Notifications/SeriesDeleteMessage.cs b/src/NzbDrone.Core/Notifications/SeriesDeleteMessage.cs index 9a02e306b..a4832b01b 100644 --- a/src/NzbDrone.Core/Notifications/SeriesDeleteMessage.cs +++ b/src/NzbDrone.Core/Notifications/SeriesDeleteMessage.cs @@ -14,7 +14,8 @@ public override string ToString() { return Message; } - public SeriesDeleteMessage (Series series, bool deleteFiles) + + public SeriesDeleteMessage(Series series, bool deleteFiles) { Series = series; DeletedFiles = deleteFiles; @@ -25,4 +26,3 @@ public SeriesDeleteMessage (Series series, bool deleteFiles) } } } - diff --git a/src/NzbDrone.Core/Notifications/Slack/Slack.cs b/src/NzbDrone.Core/Notifications/Slack/Slack.cs index 210a22dcc..458e88bea 100644 --- a/src/NzbDrone.Core/Notifications/Slack/Slack.cs +++ b/src/NzbDrone.Core/Notifications/Slack/Slack.cs @@ -8,7 +8,6 @@ using NzbDrone.Core.Tv; using NzbDrone.Core.Validation; - namespace NzbDrone.Core.Notifications.Slack { public class Slack : NotificationBase @@ -154,7 +153,6 @@ public ValidationFailure TestMessage() var payload = CreatePayload(message); _proxy.SendPayload(payload, Settings); - } catch (SlackExeption ex) { @@ -196,6 +194,7 @@ private SlackPayload CreatePayload(string message, List attachments return payload; } + private string GetTitle(Series series, List episodes) { if (series.SeriesType == SeriesTypes.Daily) diff --git a/src/NzbDrone.Core/Notifications/Slack/SlackExeption.cs b/src/NzbDrone.Core/Notifications/Slack/SlackExeption.cs index 51697d27e..952860b6d 100644 --- a/src/NzbDrone.Core/Notifications/Slack/SlackExeption.cs +++ b/src/NzbDrone.Core/Notifications/Slack/SlackExeption.cs @@ -5,11 +5,13 @@ namespace NzbDrone.Core.Notifications.Slack { public class SlackExeption : NzbDroneException { - public SlackExeption(string message) : base(message) + public SlackExeption(string message) + : base(message) { } - public SlackExeption(string message, Exception innerException, params object[] args) : base(message, innerException, args) + public SlackExeption(string message, Exception innerException, params object[] args) + : base(message, innerException, args) { } } diff --git a/src/NzbDrone.Core/Notifications/Synology/SynologyException.cs b/src/NzbDrone.Core/Notifications/Synology/SynologyException.cs index f7534671b..4c70e61b1 100644 --- a/src/NzbDrone.Core/Notifications/Synology/SynologyException.cs +++ b/src/NzbDrone.Core/Notifications/Synology/SynologyException.cs @@ -4,11 +4,13 @@ namespace NzbDrone.Core.Notifications.Synology { public class SynologyException : NzbDroneException { - public SynologyException(string message) : base(message) + public SynologyException(string message) + : base(message) { } - public SynologyException(string message, params object[] args) : base(message, args) + public SynologyException(string message, params object[] args) + : base(message, args) { } } diff --git a/src/NzbDrone.Core/Notifications/Synology/SynologyIndexer.cs b/src/NzbDrone.Core/Notifications/Synology/SynologyIndexer.cs index 538e77581..1c8b3920b 100644 --- a/src/NzbDrone.Core/Notifications/Synology/SynologyIndexer.cs +++ b/src/NzbDrone.Core/Notifications/Synology/SynologyIndexer.cs @@ -20,7 +20,6 @@ public SynologyIndexer(ISynologyIndexerProxy indexerProxy) public override string Link => "https://www.synology.com"; public override string Name => "Synology Indexer"; - public override void OnDownload(DownloadMessage message) { if (Settings.UpdateLibrary) diff --git a/src/NzbDrone.Core/Notifications/Synology/SynologyIndexerSettings.cs b/src/NzbDrone.Core/Notifications/Synology/SynologyIndexerSettings.cs index 5f9be1a2f..7b1084570 100644 --- a/src/NzbDrone.Core/Notifications/Synology/SynologyIndexerSettings.cs +++ b/src/NzbDrone.Core/Notifications/Synology/SynologyIndexerSettings.cs @@ -9,7 +9,6 @@ public class SynologyIndexerSettingsValidator : AbstractValidator Episodes {get; set;} + public List Episodes { get; set; } } } diff --git a/src/NzbDrone.Core/Notifications/Trakt/Resource/TraktShowIdsResource.cs b/src/NzbDrone.Core/Notifications/Trakt/Resource/TraktShowIdsResource.cs index 669a4e979..8f4aaaefa 100644 --- a/src/NzbDrone.Core/Notifications/Trakt/Resource/TraktShowIdsResource.cs +++ b/src/NzbDrone.Core/Notifications/Trakt/Resource/TraktShowIdsResource.cs @@ -1,5 +1,3 @@ -using NzbDrone.Core.Tv; -using System.Collections.Generic; namespace NzbDrone.Core.Notifications.Trakt.Resource { public class TraktShowIdsResource diff --git a/src/NzbDrone.Core/Notifications/Trakt/TraktInterlacedTypes.cs b/src/NzbDrone.Core/Notifications/Trakt/TraktInterlacedTypes.cs index 4d76d5895..7459a83d9 100644 --- a/src/NzbDrone.Core/Notifications/Trakt/TraktInterlacedTypes.cs +++ b/src/NzbDrone.Core/Notifications/Trakt/TraktInterlacedTypes.cs @@ -17,4 +17,4 @@ static TraktInterlacedTypes() public static HashSet interlacedTypes => _interlacedTypes; } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Notifications/Trakt/TraktProxy.cs b/src/NzbDrone.Core/Notifications/Trakt/TraktProxy.cs index bbfc230bb..8307e34c1 100644 --- a/src/NzbDrone.Core/Notifications/Trakt/TraktProxy.cs +++ b/src/NzbDrone.Core/Notifications/Trakt/TraktProxy.cs @@ -39,7 +39,7 @@ public void AddToCollection(TraktCollectShowsResource payload, string accessToke request.Headers.ContentType = "application/json"; request.SetContent(payload.ToJson()); - + try { _httpClient.Execute(request); @@ -115,7 +115,7 @@ public HttpRequest BuildTraktRequest(string resource, HttpMethod method, string var request = new HttpRequestBuilder(URL).Resource(resource).Build(); request.Method = method; - request.Headers.Accept = HttpAccept.Json.Value; + request.Headers.Accept = HttpAccept.Json.Value; request.Headers.Add("trakt-api-version", "2"); request.Headers.Add("trakt-api-key", ClientId); diff --git a/src/NzbDrone.Core/Notifications/Trakt/TraktService.cs b/src/NzbDrone.Core/Notifications/Trakt/TraktService.cs index e54c5aba4..ef5856f15 100644 --- a/src/NzbDrone.Core/Notifications/Trakt/TraktService.cs +++ b/src/NzbDrone.Core/Notifications/Trakt/TraktService.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Linq; using System.Net; using FluentValidation.Results; using NLog; @@ -8,12 +7,9 @@ using NzbDrone.Common.Http; using NzbDrone.Core.MediaFiles; using NzbDrone.Core.MediaFiles.MediaInfo; -using NzbDrone.Core.Tv; using NzbDrone.Core.Notifications.Trakt.Resource; using NzbDrone.Core.Qualities; -using NzbDrone.Core.MetadataSource.SkyHook.Resource; -using NzbDrone.Core.Indexers.HDBits; -using NzbDrone.Core.IndexerSearch; +using NzbDrone.Core.Tv; namespace NzbDrone.Core.Notifications.Trakt { @@ -60,7 +56,7 @@ public ValidationFailure Test(TraktSettings settings) try { GetUserName(settings.AccessToken); - + return null; } catch (HttpException ex) @@ -68,18 +64,18 @@ public ValidationFailure Test(TraktSettings settings) if (ex.Response.StatusCode == HttpStatusCode.Unauthorized) { _logger.Error(ex, "Access Token is invalid: " + ex.Message); - + return new ValidationFailure("Token", "Access Token is invalid"); } _logger.Error(ex, "Unable to send test message: " + ex.Message); - + return new ValidationFailure("Token", "Unable to send test message"); } catch (Exception ex) { _logger.Error(ex, "Unable to send test message: " + ex.Message); - + return new ValidationFailure("", "Unable to send test message"); } } @@ -222,8 +218,8 @@ private string MapMediaType(QualitySource source) private string MapResolution(int resolution, string scanType) { var traktResolution = string.Empty; - //var interlacedTypes = new string[] { "Interlaced", "MBAFF", "PAFF" }; + //var interlacedTypes = new string[] { "Interlaced", "MBAFF", "PAFF" }; var scanIdentifier = scanType.IsNotNullOrWhiteSpace() && TraktInterlacedTypes.interlacedTypes.Contains(scanType) ? "i" : "p"; switch (resolution) diff --git a/src/NzbDrone.Core/Notifications/Twitter/OAuthToken.cs b/src/NzbDrone.Core/Notifications/Twitter/OAuthToken.cs index dde4bc1aa..8992ca0f8 100644 --- a/src/NzbDrone.Core/Notifications/Twitter/OAuthToken.cs +++ b/src/NzbDrone.Core/Notifications/Twitter/OAuthToken.cs @@ -1,4 +1,3 @@ - namespace NzbDrone.Core.Notifications.Twitter { public class OAuthToken diff --git a/src/NzbDrone.Core/Notifications/Twitter/Twitter.cs b/src/NzbDrone.Core/Notifications/Twitter/Twitter.cs index 1774b25fd..2f701dc24 100644 --- a/src/NzbDrone.Core/Notifications/Twitter/Twitter.cs +++ b/src/NzbDrone.Core/Notifications/Twitter/Twitter.cs @@ -8,7 +8,6 @@ namespace NzbDrone.Core.Notifications.Twitter { public class Twitter : NotificationBase { - private readonly ITwitterService _twitterService; public Twitter(ITwitterService twitterService) @@ -87,6 +86,7 @@ public override object RequestAction(string action, IDictionary accessTokenSecret = oauthToken.AccessTokenSecret }; } + return new { }; } @@ -99,5 +99,4 @@ public override ValidationResult Test() return new ValidationResult(failures); } } - } diff --git a/src/NzbDrone.Core/Notifications/Twitter/TwitterException.cs b/src/NzbDrone.Core/Notifications/Twitter/TwitterException.cs index 99146fa71..77676fbf2 100644 --- a/src/NzbDrone.Core/Notifications/Twitter/TwitterException.cs +++ b/src/NzbDrone.Core/Notifications/Twitter/TwitterException.cs @@ -5,19 +5,23 @@ namespace NzbDrone.Core.Notifications.Twitter { public class TwitterException : NzbDroneException { - public TwitterException(string message, params object[] args) : base(message, args) + public TwitterException(string message, params object[] args) + : base(message, args) { } - public TwitterException(string message) : base(message) + public TwitterException(string message) + : base(message) { } - public TwitterException(string message, Exception innerException, params object[] args) : base(message, innerException, args) + public TwitterException(string message, Exception innerException, params object[] args) + : base(message, innerException, args) { } - public TwitterException(string message, Exception innerException) : base(message, innerException) + public TwitterException(string message, Exception innerException) + : base(message, innerException) { } } diff --git a/src/NzbDrone.Core/Notifications/Twitter/TwitterService.cs b/src/NzbDrone.Core/Notifications/Twitter/TwitterService.cs index 4e8af4780..9e5db17e4 100644 --- a/src/NzbDrone.Core/Notifications/Twitter/TwitterService.cs +++ b/src/NzbDrone.Core/Notifications/Twitter/TwitterService.cs @@ -1,10 +1,10 @@ -using FluentValidation.Results; -using NLog; -using System; -using System.Net; +using System; using System.Collections.Specialized; using System.IO; +using System.Net; using System.Web; +using FluentValidation.Results; +using NLog; using NzbDrone.Common.Extensions; using NzbDrone.Common.Http; using NzbDrone.Common.OAuth; @@ -46,7 +46,7 @@ public OAuthToken GetOAuthToken(string consumerKey, string consumerSecret, strin var oAuthRequest = OAuthRequest.ForAccessToken(consumerKey, consumerSecret, oauthToken, "", oauthVerifier); oAuthRequest.RequestUrl = "https://api.twitter.com/oauth/access_token"; var qscoll = OAuthQuery(oAuthRequest); - + return new OAuthToken { AccessToken = qscoll["oauth_token"], @@ -82,7 +82,6 @@ public void SendNotification(string message, TwitterSettings settings) { twitter.DirectMessage(message, settings.Mention); } - else { if (settings.Mention.IsNotNullOrWhiteSpace()) @@ -90,7 +89,7 @@ public void SendNotification(string message, TwitterSettings settings) message += string.Format(" @{0}", settings.Mention); } - twitter.UpdateStatus(message); + twitter.UpdateStatus(message); } } catch (WebException ex) @@ -131,6 +130,7 @@ public ValidationFailure Test(TwitterSettings settings) _logger.Error(ex, "Unable to send test message"); return new ValidationFailure("Host", "Unable to send test message"); } + return null; } } diff --git a/src/NzbDrone.Core/Notifications/Twitter/TwitterSettings.cs b/src/NzbDrone.Core/Notifications/Twitter/TwitterSettings.cs index 180490de7..c8ff353ce 100644 --- a/src/NzbDrone.Core/Notifications/Twitter/TwitterSettings.cs +++ b/src/NzbDrone.Core/Notifications/Twitter/TwitterSettings.cs @@ -14,6 +14,7 @@ public TwitterSettingsValidator() RuleFor(c => c.ConsumerSecret).NotEmpty(); RuleFor(c => c.AccessToken).NotEmpty(); RuleFor(c => c.AccessTokenSecret).NotEmpty(); + //TODO: Validate that it is a valid username (numbers, letters and underscores - I think) RuleFor(c => c.Mention).NotEmpty().When(c => c.DirectMessage); diff --git a/src/NzbDrone.Core/Notifications/Webhook/Webhook.cs b/src/NzbDrone.Core/Notifications/Webhook/Webhook.cs index c7701af55..9f84128a1 100644 --- a/src/NzbDrone.Core/Notifications/Webhook/Webhook.cs +++ b/src/NzbDrone.Core/Notifications/Webhook/Webhook.cs @@ -1,10 +1,10 @@ -using System.Collections.Generic; +using System.Collections.Generic; using System.IO; using System.Linq; using FluentValidation.Results; -using NzbDrone.Core.Tv; using NzbDrone.Common.Extensions; using NzbDrone.Core.MediaFiles; +using NzbDrone.Core.Tv; using NzbDrone.Core.Validation; namespace NzbDrone.Core.Notifications.Webhook @@ -59,10 +59,8 @@ public override void OnDownload(DownloadMessage message) { payload.DeletedFiles = message.OldFiles.ConvertAll(x => new WebhookEpisodeFile(x) { - Path = Path.Combine(message.Series.Path, - x.RelativePath) - } - ); + Path = Path.Combine(message.Series.Path, x.RelativePath) + }); } _proxy.SendWebhook(payload, Settings); @@ -158,15 +156,16 @@ private ValidationFailure SendWebhookTest() Path = "C:\\testpath", TvdbId = 1234 }, - Episodes = new List() { - new WebhookEpisode() - { - Id = 123, - EpisodeNumber = 1, - SeasonNumber = 1, - Title = "Test title" - } + Episodes = new List() + { + new WebhookEpisode() + { + Id = 123, + EpisodeNumber = 1, + SeasonNumber = 1, + Title = "Test title" } + } }; _proxy.SendWebhook(payload, Settings); diff --git a/src/NzbDrone.Core/Notifications/Webhook/WebhookEpisode.cs b/src/NzbDrone.Core/Notifications/Webhook/WebhookEpisode.cs index c6e812d6f..5851e97d0 100644 --- a/src/NzbDrone.Core/Notifications/Webhook/WebhookEpisode.cs +++ b/src/NzbDrone.Core/Notifications/Webhook/WebhookEpisode.cs @@ -1,11 +1,13 @@ -using NzbDrone.Core.Tv; -using System; +using System; +using NzbDrone.Core.Tv; namespace NzbDrone.Core.Notifications.Webhook { public class WebhookEpisode { - public WebhookEpisode() { } + public WebhookEpisode() + { + } public WebhookEpisode(Episode episode) { @@ -24,4 +26,4 @@ public WebhookEpisode(Episode episode) public string AirDate { get; set; } public DateTime? AirDateUtc { get; set; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Notifications/Webhook/WebhookEpisodeDeletePayload.cs b/src/NzbDrone.Core/Notifications/Webhook/WebhookEpisodeDeletePayload.cs index d12d8b1dc..efc1ab3af 100644 --- a/src/NzbDrone.Core/Notifications/Webhook/WebhookEpisodeDeletePayload.cs +++ b/src/NzbDrone.Core/Notifications/Webhook/WebhookEpisodeDeletePayload.cs @@ -11,4 +11,3 @@ public class WebhookEpisodeDeletePayload : WebhookPayload public DeleteMediaFileReason DeleteReason { get; set; } } } - diff --git a/src/NzbDrone.Core/Notifications/Webhook/WebhookEpisodeFile.cs b/src/NzbDrone.Core/Notifications/Webhook/WebhookEpisodeFile.cs index 346e6a836..1da424ef7 100644 --- a/src/NzbDrone.Core/Notifications/Webhook/WebhookEpisodeFile.cs +++ b/src/NzbDrone.Core/Notifications/Webhook/WebhookEpisodeFile.cs @@ -4,7 +4,9 @@ namespace NzbDrone.Core.Notifications.Webhook { public class WebhookEpisodeFile { - public WebhookEpisodeFile() { } + public WebhookEpisodeFile() + { + } public WebhookEpisodeFile(EpisodeFile episodeFile) { @@ -27,4 +29,4 @@ public WebhookEpisodeFile(EpisodeFile episodeFile) public string SceneName { get; set; } public long Size { get; set; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Notifications/Webhook/WebhookException.cs b/src/NzbDrone.Core/Notifications/Webhook/WebhookException.cs index b422d8621..07d4c4666 100644 --- a/src/NzbDrone.Core/Notifications/Webhook/WebhookException.cs +++ b/src/NzbDrone.Core/Notifications/Webhook/WebhookException.cs @@ -5,11 +5,13 @@ namespace NzbDrone.Core.Notifications.Webhook { public class WebhookException : NzbDroneException { - public WebhookException(string message) : base(message) + public WebhookException(string message) + : base(message) { } - public WebhookException(string message, Exception innerException, params object[] args) : base(message, innerException, args) + public WebhookException(string message, Exception innerException, params object[] args) + : base(message, innerException, args) { } } diff --git a/src/NzbDrone.Core/Notifications/Webhook/WebhookMethod.cs b/src/NzbDrone.Core/Notifications/Webhook/WebhookMethod.cs index a3d27a575..920c8b080 100644 --- a/src/NzbDrone.Core/Notifications/Webhook/WebhookMethod.cs +++ b/src/NzbDrone.Core/Notifications/Webhook/WebhookMethod.cs @@ -7,4 +7,4 @@ public enum WebhookMethod POST = HttpMethod.POST, PUT = HttpMethod.PUT } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Notifications/Webhook/WebhookPayload.cs b/src/NzbDrone.Core/Notifications/Webhook/WebhookPayload.cs index 08281a50a..f16d8e20d 100644 --- a/src/NzbDrone.Core/Notifications/Webhook/WebhookPayload.cs +++ b/src/NzbDrone.Core/Notifications/Webhook/WebhookPayload.cs @@ -4,4 +4,4 @@ public class WebhookPayload { public WebhookEventType EventType { get; set; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Notifications/Webhook/WebhookProxy.cs b/src/NzbDrone.Core/Notifications/Webhook/WebhookProxy.cs index 8d998ac8d..489eeb41f 100644 --- a/src/NzbDrone.Core/Notifications/Webhook/WebhookProxy.cs +++ b/src/NzbDrone.Core/Notifications/Webhook/WebhookProxy.cs @@ -1,6 +1,6 @@ +using NzbDrone.Common.Extensions; using NzbDrone.Common.Http; using NzbDrone.Common.Serializer; -using NzbDrone.Common.Extensions; namespace NzbDrone.Core.Notifications.Webhook { @@ -34,6 +34,7 @@ public void SendWebhook(WebhookPayload body, WebhookSettings settings) { request.AddBasicAuthentication(settings.Username, settings.Password); } + _httpClient.Execute(request); } catch (HttpException ex) diff --git a/src/NzbDrone.Core/Notifications/Webhook/WebhookRelease.cs b/src/NzbDrone.Core/Notifications/Webhook/WebhookRelease.cs index dfab9c889..836b7cafd 100644 --- a/src/NzbDrone.Core/Notifications/Webhook/WebhookRelease.cs +++ b/src/NzbDrone.Core/Notifications/Webhook/WebhookRelease.cs @@ -5,7 +5,9 @@ namespace NzbDrone.Core.Notifications.Webhook { public class WebhookRelease { - public WebhookRelease() { } + public WebhookRelease() + { + } public WebhookRelease(QualityModel quality, RemoteEpisode remoteEpisode) { @@ -24,4 +26,4 @@ public WebhookRelease(QualityModel quality, RemoteEpisode remoteEpisode) public string Indexer { get; set; } public long Size { get; set; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Notifications/Webhook/WebhookRenamedEpisodeFile.cs b/src/NzbDrone.Core/Notifications/Webhook/WebhookRenamedEpisodeFile.cs index a1da2ed1a..4abb43097 100644 --- a/src/NzbDrone.Core/Notifications/Webhook/WebhookRenamedEpisodeFile.cs +++ b/src/NzbDrone.Core/Notifications/Webhook/WebhookRenamedEpisodeFile.cs @@ -4,7 +4,8 @@ namespace NzbDrone.Core.Notifications.Webhook { public class WebhookRenamedEpisodeFile : WebhookEpisodeFile { - public WebhookRenamedEpisodeFile(RenamedEpisodeFile renamedEpisode) : base(renamedEpisode.EpisodeFile) + public WebhookRenamedEpisodeFile(RenamedEpisodeFile renamedEpisode) + : base(renamedEpisode.EpisodeFile) { PreviousRelativePath = renamedEpisode.PreviousRelativePath; PreviousPath = renamedEpisode.PreviousPath; @@ -13,4 +14,4 @@ public WebhookRenamedEpisodeFile(RenamedEpisodeFile renamedEpisode) : base(renam public string PreviousRelativePath { get; set; } public string PreviousPath { get; set; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Notifications/Webhook/WebhookSeries.cs b/src/NzbDrone.Core/Notifications/Webhook/WebhookSeries.cs index cba4e8ba7..c3f22c998 100644 --- a/src/NzbDrone.Core/Notifications/Webhook/WebhookSeries.cs +++ b/src/NzbDrone.Core/Notifications/Webhook/WebhookSeries.cs @@ -12,7 +12,9 @@ public class WebhookSeries public string ImdbId { get; set; } public SeriesTypes Type { get; set; } - public WebhookSeries() { } + public WebhookSeries() + { + } public WebhookSeries(Series series) { @@ -25,4 +27,4 @@ public WebhookSeries(Series series) Type = series.SeriesType; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Notifications/Webhook/WebhookSeriesDeletePayload.cs b/src/NzbDrone.Core/Notifications/Webhook/WebhookSeriesDeletePayload.cs index 55f84aec2..0e6ec19aa 100644 --- a/src/NzbDrone.Core/Notifications/Webhook/WebhookSeriesDeletePayload.cs +++ b/src/NzbDrone.Core/Notifications/Webhook/WebhookSeriesDeletePayload.cs @@ -8,4 +8,3 @@ public class WebhookSeriesDeletePayload : WebhookPayload public bool DeletedFiles { get; set; } } } - diff --git a/src/NzbDrone.Core/Notifications/Xbmc/Model/XbmcVersion.cs b/src/NzbDrone.Core/Notifications/Xbmc/Model/XbmcVersion.cs index c4fc4358e..1c6ca0c06 100644 --- a/src/NzbDrone.Core/Notifications/Xbmc/Model/XbmcVersion.cs +++ b/src/NzbDrone.Core/Notifications/Xbmc/Model/XbmcVersion.cs @@ -1,4 +1,4 @@ -using System; +using System; namespace NzbDrone.Core.Notifications.Xbmc.Model { @@ -26,23 +26,35 @@ public XbmcVersion(int major, int minor, int patch) public int CompareTo(XbmcVersion other) { - if(other.Major > Major) + if (other.Major > Major) + { return -1; + } - if(other.Major < Major) + if (other.Major < Major) + { return 1; + } if (other.Minor > Minor) + { return -1; + } if (other.Minor < Minor) + { return 1; + } if (other.Patch > Patch) + { return -1; + } if (other.Patch < Patch) + { return 1; + } return 0; } @@ -92,28 +104,49 @@ public override string ToString() public override int GetHashCode() { - unchecked // Overflow is fine, just wrap + unchecked { + // Overflow is fine, just wrap int hash = 17; - hash = hash * 23 + Major.GetHashCode(); - hash = hash * 23 + Minor.GetHashCode(); - hash = hash * 23 + Patch.GetHashCode(); + hash = (hash * 23) + Major.GetHashCode(); + hash = (hash * 23) + Minor.GetHashCode(); + hash = (hash * 23) + Patch.GetHashCode(); return hash; } } public bool Equals(XbmcVersion other) { - if (ReferenceEquals(null, other)) return false; - if (ReferenceEquals(this, other)) return true; - return (Equals(other.Major, Major) && Equals(other.Minor, Minor) && Equals(other.Patch, Patch)); + if (ReferenceEquals(null, other)) + { + return false; + } + + if (ReferenceEquals(this, other)) + { + return true; + } + + return Equals(other.Major, Major) && Equals(other.Minor, Minor) && Equals(other.Patch, Patch); } public override bool Equals(object obj) { - if (ReferenceEquals(null, obj)) return false; - if (ReferenceEquals(this, obj)) return true; - if (obj.GetType() != typeof(XbmcVersion)) return false; + if (ReferenceEquals(null, obj)) + { + return false; + } + + if (ReferenceEquals(this, obj)) + { + return true; + } + + if (obj.GetType() != typeof(XbmcVersion)) + { + return false; + } + return Equals((XbmcVersion)obj); } diff --git a/src/NzbDrone.Core/Notifications/Xbmc/XbmcJsonApiProxy.cs b/src/NzbDrone.Core/Notifications/Xbmc/XbmcJsonApiProxy.cs index 35cc69036..ba22e5609 100644 --- a/src/NzbDrone.Core/Notifications/Xbmc/XbmcJsonApiProxy.cs +++ b/src/NzbDrone.Core/Notifications/Xbmc/XbmcJsonApiProxy.cs @@ -97,7 +97,6 @@ private string ProcessRequest(XbmcSettings settings, string method, params objec private void CheckForError(HttpResponse response) { - if (string.IsNullOrWhiteSpace(response.Content)) { throw new XbmcJsonException("Invalid response from XBMC, the response is not valid JSON"); diff --git a/src/NzbDrone.Core/Notifications/Xbmc/XbmcService.cs b/src/NzbDrone.Core/Notifications/Xbmc/XbmcService.cs index 837877c93..040631a0e 100644 --- a/src/NzbDrone.Core/Notifications/Xbmc/XbmcService.cs +++ b/src/NzbDrone.Core/Notifications/Xbmc/XbmcService.cs @@ -74,7 +74,10 @@ public string GetSeriesPath(XbmcSettings settings, Series series) return tvdbId == series.TvdbId || s.Label == series.Title; }); - if (matchingSeries != null) return matchingSeries.File; + if (matchingSeries != null) + { + return matchingSeries.File; + } return null; } diff --git a/src/NzbDrone.Core/Organizer/EpisodeSortingType.cs b/src/NzbDrone.Core/Organizer/EpisodeSortingType.cs index d68549f07..77da1145d 100644 --- a/src/NzbDrone.Core/Organizer/EpisodeSortingType.cs +++ b/src/NzbDrone.Core/Organizer/EpisodeSortingType.cs @@ -7,4 +7,4 @@ public class EpisodeSortingType public string Pattern { get; set; } public string EpisodeSeparator { get; set; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Organizer/Exception.cs b/src/NzbDrone.Core/Organizer/Exception.cs index c4e80b17d..18efe94cc 100644 --- a/src/NzbDrone.Core/Organizer/Exception.cs +++ b/src/NzbDrone.Core/Organizer/Exception.cs @@ -4,11 +4,13 @@ namespace NzbDrone.Core.Organizer { public class NamingFormatException : NzbDroneException { - public NamingFormatException(string message, params object[] args) : base(message, args) + public NamingFormatException(string message, params object[] args) + : base(message, args) { } - public NamingFormatException(string message) : base(message) + public NamingFormatException(string message) + : base(message) { } } diff --git a/src/NzbDrone.Core/Organizer/FileNameBuilder.cs b/src/NzbDrone.Core/Organizer/FileNameBuilder.cs index a573874f0..6c57e5ec9 100644 --- a/src/NzbDrone.Core/Organizer/FileNameBuilder.cs +++ b/src/NzbDrone.Core/Organizer/FileNameBuilder.cs @@ -32,6 +32,9 @@ public interface IBuildFileNames public class FileNameBuilder : IBuildFileNames { + private const string MediaInfoVideoDynamicRangeToken = "{MediaInfo VideoDynamicRange}"; + private const string MediaInfoVideoDynamicRangeTypeToken = "{MediaInfo VideoDynamicRangeType}"; + private readonly INamingConfigService _namingConfigService; private readonly IQualityDefinitionService _qualityDefinitionService; private readonly IPreferredWordService _preferredWordService; @@ -172,6 +175,7 @@ private string BuildFileName(List episodes, Series series, EpisodeFile { maxPathSegmentLength -= extension.GetByteCount(); } + var maxEpisodeTitleLength = maxPathSegmentLength - GetLengthWithoutEpisodeTitle(component, namingConfig); AddEpisodeTitleTokens(tokenHandlers, episodes, maxEpisodeTitleLength); @@ -196,14 +200,14 @@ public string BuildFileName(List episodes, Series series, EpisodeFile e public string BuildFilePath(List episodes, Series series, EpisodeFile episodeFile, string extension, NamingConfig namingConfig = null, PreferredWordMatchResults preferredWords = null) { Ensure.That(extension, () => extension).IsNotNullOrWhiteSpace(); - + var seasonPath = BuildSeasonPath(series, episodes.First().SeasonNumber); var remainingPathLength = LongPathSupport.MaxFilePathLength - seasonPath.GetByteCount() - 1; var fileName = BuildFileName(episodes, series, episodeFile, extension, remainingPathLength, namingConfig, preferredWords); return Path.Combine(seasonPath, fileName); } - + public string BuildSeasonPath(Series series, int seasonNumber) { var path = series.Path; @@ -513,9 +517,8 @@ private string AddAbsoluteNumberingTokens(string pattern, Dictionary {episodes.First()}; + var eps = new List { episodes.First() }; - if (episodes.Count > 1) eps.Add(episodes.Last()); + if (episodes.Count > 1) + { + eps.Add(episodes.Last()); + } absoluteEpisodePattern = FormatAbsoluteNumberTokens(absoluteEpisodePattern, formatPattern, eps); break; @@ -600,19 +606,17 @@ private void AddQualityTokens(Dictionary> token var qualityProper = GetQualityProper(series, episodeFile.Quality); var qualityReal = GetQualityReal(series, episodeFile.Quality); - tokenHandlers["{Quality Full}"] = m => String.Format("{0} {1} {2}", qualityTitle, qualityProper, qualityReal); + tokenHandlers["{Quality Full}"] = m => string.Format("{0} {1} {2}", qualityTitle, qualityProper, qualityReal); tokenHandlers["{Quality Title}"] = m => qualityTitle; tokenHandlers["{Quality Proper}"] = m => qualityProper; tokenHandlers["{Quality Real}"] = m => qualityReal; } - private const string MediaInfoVideoDynamicRangeToken = "{MediaInfo VideoDynamicRange}"; - private const string MediaInfoVideoDynamicRangeTypeToken = "{MediaInfo VideoDynamicRangeType}"; private static readonly IReadOnlyDictionary MinimumMediaInfoSchemaRevisions = new Dictionary(FileNameBuilderTokenEqualityComparer.Instance) { - {MediaInfoVideoDynamicRangeToken, 5}, - {MediaInfoVideoDynamicRangeTypeToken, 5} + { MediaInfoVideoDynamicRangeToken, 5 }, + { MediaInfoVideoDynamicRangeTypeToken, 5 } }; private void AddMediaInfoTokens(Dictionary> tokenHandlers, EpisodeFile episodeFile) @@ -674,8 +678,8 @@ private void AddPreferredWords(Dictionary> toke preferredWords = _preferredWordService.GetMatchingPreferredWords(series, episodeFile.GetSceneOrFileName()); } - tokenHandlers["{Preferred Words}"] = m => { - + tokenHandlers["{Preferred Words}"] = m => + { var profileName = ""; if (m.CustomFormat != null) @@ -689,7 +693,7 @@ private void AddPreferredWords(Dictionary> toke } if (preferredWords.ByReleaseProfile.TryGetValue(profileName, out var profilePreferredWords)) - { + { return string.Join(" ", profilePreferredWords); } @@ -703,14 +707,16 @@ private string GetLanguagesToken(string mediaInfoLanguages, string filter, bool foreach (var item in mediaInfoLanguages.Split('/')) { if (!string.IsNullOrWhiteSpace(item)) + { tokens.Add(item.Trim()); + } } var cultures = CultureInfo.GetCultures(CultureTypes.NeutralCultures); for (int i = 0; i < tokens.Count; i++) { if (tokens[i] == "Swedis") - { + { // Probably typo in mediainfo (should be 'Swedish') tokens[i] = "SV"; continue; @@ -728,7 +734,9 @@ private string GetLanguagesToken(string mediaInfoLanguages, string filter, bool var cultureInfo = cultures.FirstOrDefault(p => p.EnglishName.RemoveAccent() == tokens[i]); if (cultureInfo != null) + { tokens[i] = cultureInfo.TwoLetterISOLanguageName.ToUpper(); + } } catch { @@ -736,7 +744,7 @@ private string GetLanguagesToken(string mediaInfoLanguages, string filter, bool } tokens = tokens.Distinct().ToList(); - + var filteredTokens = tokens; // Exclude or filter @@ -758,7 +766,6 @@ private string GetLanguagesToken(string mediaInfoLanguages, string filter, bool filteredTokens.Add("--"); } - if (skipEnglishOnly && filteredTokens.Count == 1 && filteredTokens.First() == "EN") { return string.Empty; @@ -782,7 +789,7 @@ private void UpdateMediaInfoIfNeeded(string pattern, EpisodeFile episodeFile, Se { return; } - + var schemaRevision = episodeFile.MediaInfo != null ? episodeFile.MediaInfo.SchemaRevision : 0; var matches = TitleRegex.Matches(pattern); @@ -806,11 +813,17 @@ private string ReplaceToken(Match match, Dictionary !char.IsLetter(t) || char.IsLower(t))) @@ -901,7 +914,10 @@ private string FormatRangeNumberTokens(string seasonEpisodePattern, string forma { var eps = new List { episodes.First() }; - if (episodes.Count > 1) eps.Add(episodes.Last()); + if (episodes.Count > 1) + { + eps.Add(episodes.Last()); + } return FormatNumberTokens(seasonEpisodePattern, formatPattern, eps); } @@ -914,7 +930,10 @@ private string ReplaceSeasonTokens(string pattern, int seasonNumber) private string ReplaceNumberToken(string token, int value) { var split = token.Trim('{', '}').Split(':'); - if (split.Length == 1) return value.ToString("0"); + if (split.Length == 1) + { + return value.ToString("0"); + } return value.ToString(split[1]); } @@ -1044,7 +1063,7 @@ private string GetQualityProper(Series series, QualityModel quality) return "Proper"; } - return String.Empty; + return string.Empty; } private string GetQualityReal(Series series, QualityModel quality) diff --git a/src/NzbDrone.Core/Organizer/FileNameBuilderTokenEqualityComparer.cs b/src/NzbDrone.Core/Organizer/FileNameBuilderTokenEqualityComparer.cs index fde022c10..e5ffe79f5 100644 --- a/src/NzbDrone.Core/Organizer/FileNameBuilderTokenEqualityComparer.cs +++ b/src/NzbDrone.Core/Organizer/FileNameBuilderTokenEqualityComparer.cs @@ -11,7 +11,6 @@ public class FileNameBuilderTokenEqualityComparer : IEqualityComparer private FileNameBuilderTokenEqualityComparer() { - } public bool Equals(string s1, string s2) diff --git a/src/NzbDrone.Core/Organizer/FileNameSampleService.cs b/src/NzbDrone.Core/Organizer/FileNameSampleService.cs index 4c663b28e..e5e706361 100644 --- a/src/NzbDrone.Core/Organizer/FileNameSampleService.cs +++ b/src/NzbDrone.Core/Organizer/FileNameSampleService.cs @@ -1,9 +1,9 @@ using System.Collections.Generic; using NzbDrone.Core.MediaFiles; -using NzbDrone.Core.Qualities; -using NzbDrone.Core.Tv; using NzbDrone.Core.MediaFiles.MediaInfo; using NzbDrone.Core.Profiles.Releases; +using NzbDrone.Core.Qualities; +using NzbDrone.Core.Tv; namespace NzbDrone.Core.Organizer { @@ -172,7 +172,7 @@ public FileNameSampleService(IBuildFileNames buildFileNames) _preferredWords = new PreferredWordMatchResults() { - All = new List() {"iNTERNAL" } + All = new List() { "iNTERNAL" } }; } diff --git a/src/NzbDrone.Core/Organizer/FileNameValidation.cs b/src/NzbDrone.Core/Organizer/FileNameValidation.cs index 3bc15e94f..8efe5fc4d 100644 --- a/src/NzbDrone.Core/Organizer/FileNameValidation.cs +++ b/src/NzbDrone.Core/Organizer/FileNameValidation.cs @@ -69,7 +69,6 @@ public class ValidStandardEpisodeFormatValidator : PropertyValidator public ValidStandardEpisodeFormatValidator() : base("Must contain season and episode numbers OR Original Title") { - } protected override bool IsValid(PropertyValidatorContext context) @@ -91,7 +90,6 @@ public class ValidDailyEpisodeFormatValidator : PropertyValidator public ValidDailyEpisodeFormatValidator() : base("Must contain Air Date OR Season and Episode OR Original Title") { - } protected override bool IsValid(PropertyValidatorContext context) @@ -114,7 +112,6 @@ public class ValidAnimeEpisodeFormatValidator : PropertyValidator public ValidAnimeEpisodeFormatValidator() : base("Must contain Absolute Episode number OR Season and Episode OR Original Title") { - } protected override bool IsValid(PropertyValidatorContext context) @@ -139,7 +136,6 @@ public class IllegalCharactersValidator : PropertyValidator public IllegalCharactersValidator() : base("Contains illegal characters: {InvalidCharacters}") { - } protected override bool IsValid(PropertyValidatorContext context) diff --git a/src/NzbDrone.Core/Organizer/NamingConfigRepository.cs b/src/NzbDrone.Core/Organizer/NamingConfigRepository.cs index 6c32eee62..ca0138b67 100644 --- a/src/NzbDrone.Core/Organizer/NamingConfigRepository.cs +++ b/src/NzbDrone.Core/Organizer/NamingConfigRepository.cs @@ -5,7 +5,6 @@ namespace NzbDrone.Core.Organizer { public interface INamingConfigRepository : IBasicRepository { - } public class NamingConfigRepository : BasicRepository, INamingConfigRepository @@ -14,6 +13,5 @@ public NamingConfigRepository(IMainDatabase database, IEventAggregator eventAggr : base(database, eventAggregator) { } - } } diff --git a/src/NzbDrone.Core/Parser/InvalidDateException.cs b/src/NzbDrone.Core/Parser/InvalidDateException.cs index 722517d0e..97c5da581 100644 --- a/src/NzbDrone.Core/Parser/InvalidDateException.cs +++ b/src/NzbDrone.Core/Parser/InvalidDateException.cs @@ -4,11 +4,13 @@ namespace NzbDrone.Core.Parser { public class InvalidDateException : NzbDroneException { - public InvalidDateException(string message, params object[] args) : base(message, args) + public InvalidDateException(string message, params object[] args) + : base(message, args) { } - public InvalidDateException(string message) : base(message) + public InvalidDateException(string message) + : base(message) { } } diff --git a/src/NzbDrone.Core/Parser/InvalidSeasonException.cs b/src/NzbDrone.Core/Parser/InvalidSeasonException.cs index 23ce77954..0599c2926 100644 --- a/src/NzbDrone.Core/Parser/InvalidSeasonException.cs +++ b/src/NzbDrone.Core/Parser/InvalidSeasonException.cs @@ -4,11 +4,13 @@ namespace NzbDrone.Core.Parser { public class InvalidSeasonException : NzbDroneException { - public InvalidSeasonException(string message, params object[] args) : base(message, args) + public InvalidSeasonException(string message, params object[] args) + : base(message, args) { } - public InvalidSeasonException(string message) : base(message) + public InvalidSeasonException(string message) + : base(message) { } } diff --git a/src/NzbDrone.Core/Parser/IsoLanguages.cs b/src/NzbDrone.Core/Parser/IsoLanguages.cs index efd8f9d2c..f5d6ef5b2 100644 --- a/src/NzbDrone.Core/Parser/IsoLanguages.cs +++ b/src/NzbDrone.Core/Parser/IsoLanguages.cs @@ -27,6 +27,7 @@ public static class IsoLanguages new IsoLanguage("fi", "fin", Language.Finnish), new IsoLanguage("tr", "tur", Language.Turkish), new IsoLanguage("pt", "por", Language.Portuguese), + // new IsoLanguage("nl", "nld", Language.Flemish), new IsoLanguage("el", "ell", Language.Greek), new IsoLanguage("ko", "kor", Language.Korean), diff --git a/src/NzbDrone.Core/Parser/LanguageParser.cs b/src/NzbDrone.Core/Parser/LanguageParser.cs index d54248bba..c2b62ab4e 100644 --- a/src/NzbDrone.Core/Parser/LanguageParser.cs +++ b/src/NzbDrone.Core/Parser/LanguageParser.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.IO; using System.Linq; @@ -25,7 +25,6 @@ public static class LanguageParser private static readonly Regex CaseSensitiveLanguageRegex = new Regex(@"(?:(?i)(?\bLT\b)|(?\bCZ\b)|(?\bPL\b)|(?\bBG\b))(?:(?i)(?![\W|_|^]SUB))", RegexOptions.Compiled); - private static readonly Regex SubtitleLanguageRegex = new Regex(".+?[-_. ](?[a-z]{2,3})([-_. ](?full|forced|foreign|default|cc|psdh|sdh))*$", RegexOptions.Compiled | RegexOptions.IgnoreCase); public static Language ParseLanguage(string title, bool defaultToEnglish = true) @@ -33,79 +32,127 @@ public static Language ParseLanguage(string title, bool defaultToEnglish = true) foreach (var regex in CleanSeriesTitleRegex) { if (regex.TryReplace(ref title)) + { break; + } } var lowerTitle = title.ToLower(); if (lowerTitle.Contains("french")) + { return Language.French; + } if (lowerTitle.Contains("spanish")) + { return Language.Spanish; + } if (lowerTitle.Contains("danish")) + { return Language.Danish; + } if (lowerTitle.Contains("dutch")) + { return Language.Dutch; + } if (lowerTitle.Contains("japanese")) + { return Language.Japanese; + } if (lowerTitle.Contains("icelandic")) + { return Language.Icelandic; + } if (lowerTitle.Contains("mandarin") || lowerTitle.Contains("cantonese") || lowerTitle.Contains("chinese")) + { return Language.Chinese; + } if (lowerTitle.Contains("korean")) + { return Language.Korean; + } if (lowerTitle.Contains("russian")) + { return Language.Russian; + } if (lowerTitle.Contains("polish")) + { return Language.Polish; + } if (lowerTitle.Contains("vietnamese")) + { return Language.Vietnamese; + } if (lowerTitle.Contains("swedish")) + { return Language.Swedish; + } if (lowerTitle.Contains("norwegian")) + { return Language.Norwegian; + } if (lowerTitle.Contains("finnish")) + { return Language.Finnish; + } if (lowerTitle.Contains("turkish")) + { return Language.Turkish; + } if (lowerTitle.Contains("portuguese")) + { return Language.Portuguese; + } if (lowerTitle.Contains("hungarian")) + { return Language.Hungarian; + } if (lowerTitle.Contains("hebrew")) + { return Language.Hebrew; + } if (lowerTitle.Contains("arabic")) + { return Language.Arabic; + } if (lowerTitle.Contains("hindi")) + { return Language.Hindi; + } if (lowerTitle.Contains("malayalam")) + { return Language.Malayalam; + } if (lowerTitle.Contains("ukrainian")) + { return Language.Ukrainian; + } if (lowerTitle.Contains("bulgarian")) + { return Language.Bulgarian; + } var regexLanguage = RegexLanguage(title); @@ -115,7 +162,9 @@ public static Language ParseLanguage(string title, bool defaultToEnglish = true) } if (lowerTitle.Contains("english")) + { return Language.English; + } return defaultToEnglish ? Language.English : Language.Unknown; } @@ -154,7 +203,7 @@ public static Language ParseSubtitleLanguage(string fileName) return Language.Unknown; } - + public static IEnumerable ParseLanguageTags(string fileName) { try @@ -180,61 +229,97 @@ private static Language RegexLanguage(string title) var caseSensitiveMatch = CaseSensitiveLanguageRegex.Match(title); if (caseSensitiveMatch.Groups["lithuanian"].Captures.Cast().Any()) + { return Language.Lithuanian; + } if (caseSensitiveMatch.Groups["czech"].Captures.Cast().Any()) + { return Language.Czech; - + } + if (caseSensitiveMatch.Groups["polish"].Captures.Cast().Any()) + { return Language.Polish; + } if (caseSensitiveMatch.Groups["bulgarian"].Captures.Cast().Any()) + { return Language.Bulgarian; + } // Case insensitive var match = LanguageRegex.Match(title); if (match.Groups["italian"].Captures.Cast().Any()) + { return Language.Italian; + } if (match.Groups["german"].Captures.Cast().Any()) + { return Language.German; + } if (match.Groups["flemish"].Captures.Cast().Any()) + { return Language.Flemish; + } if (match.Groups["greek"].Captures.Cast().Any()) + { return Language.Greek; + } if (match.Groups["french"].Success) + { return Language.French; + } if (match.Groups["russian"].Success) + { return Language.Russian; + } if (match.Groups["dutch"].Success) + { return Language.Dutch; + } if (match.Groups["hungarian"].Success) + { return Language.Hungarian; + } if (match.Groups["hebrew"].Success) + { return Language.Hebrew; + } if (match.Groups["polish"].Success) + { return Language.Polish; + } if (match.Groups["chinese"].Success) + { return Language.Chinese; + } if (match.Groups["bulgarian"].Success) + { return Language.Bulgarian; + } if (match.Groups["ukrainian"].Success) + { return Language.Ukrainian; + } if (match.Groups["spanish"].Success) + { return Language.Spanish; + } return Language.Unknown; } diff --git a/src/NzbDrone.Core/Parser/Model/LocalEpisode.cs b/src/NzbDrone.Core/Parser/Model/LocalEpisode.cs index 86556bc65..2ef542331 100644 --- a/src/NzbDrone.Core/Parser/Model/LocalEpisode.cs +++ b/src/NzbDrone.Core/Parser/Model/LocalEpisode.cs @@ -1,10 +1,10 @@ -using System.Linq; using System.Collections.Generic; +using System.Linq; using NzbDrone.Common.Extensions; +using NzbDrone.Core.Languages; +using NzbDrone.Core.MediaFiles.MediaInfo; using NzbDrone.Core.Qualities; using NzbDrone.Core.Tv; -using NzbDrone.Core.MediaFiles.MediaInfo; -using NzbDrone.Core.Languages; namespace NzbDrone.Core.Parser.Model { @@ -32,8 +32,8 @@ public LocalEpisode() public int PreferredWordScore { get; set; } public bool OtherVideoFiles { get; set; } - public int SeasonNumber - { + public int SeasonNumber + { get { var seasons = Episodes.Select(c => c.SeasonNumber).Distinct().ToList(); @@ -49,7 +49,7 @@ public int SeasonNumber } return seasons.Single(); - } + } } public bool IsSpecial => SeasonNumber == 0; diff --git a/src/NzbDrone.Core/Parser/Model/ParsedEpisodeInfo.cs b/src/NzbDrone.Core/Parser/Model/ParsedEpisodeInfo.cs index b2c409419..994a77698 100644 --- a/src/NzbDrone.Core/Parser/Model/ParsedEpisodeInfo.cs +++ b/src/NzbDrone.Core/Parser/Model/ParsedEpisodeInfo.cs @@ -1,7 +1,7 @@ using System.Linq; using NzbDrone.Common.Extensions; -using NzbDrone.Core.Qualities; using NzbDrone.Core.Languages; +using NzbDrone.Core.Qualities; namespace NzbDrone.Core.Parser.Model { @@ -42,9 +42,9 @@ public bool IsDaily return !string.IsNullOrWhiteSpace(AirDate); } - //This prevents manually downloading a release from blowing up in mono - //TODO: Is there a better way? - private set { } + private set + { + } } public bool IsAbsoluteNumbering @@ -54,37 +54,36 @@ public bool IsAbsoluteNumbering return AbsoluteEpisodeNumbers.Any(); } - //This prevents manually downloading a release from blowing up in mono - //TODO: Is there a better way? - private set { } + private set + { + } } public bool IsPossibleSpecialEpisode { get { - // if we don't have any episode numbers we are likely a special episode and need to do a search by episode title - return (AirDate.IsNullOrWhiteSpace() && + return ((AirDate.IsNullOrWhiteSpace() && SeriesTitle.IsNullOrWhiteSpace() && - (EpisodeNumbers.Length == 0 || SeasonNumber == 0) || !SeriesTitle.IsNullOrWhiteSpace() && Special) || - EpisodeNumbers.Length == 1 && EpisodeNumbers[0] == 0; + (EpisodeNumbers.Length == 0 || SeasonNumber == 0)) || (!SeriesTitle.IsNullOrWhiteSpace() && Special)) || + (EpisodeNumbers.Length == 1 && EpisodeNumbers[0] == 0); } - //This prevents manually downloading a release from blowing up in mono - //TODO: Is there a better way? - private set {} + private set + { + } } + public bool IsPossibleSceneSeasonSpecial { get { - // SxxE00 episodes return SeasonNumber != 0 && EpisodeNumbers.Length == 1 && EpisodeNumbers[0] == 0; } - //This prevents manually downloading a release from blowing up in mono - //TODO: Is there a better way? - private set { } + private set + { + } } public override string ToString() @@ -110,9 +109,13 @@ public override string ToString() else if (Special) { if (SeasonNumber != 0) + { episodeString = string.Format("[Unknown Season {0:00} Special]", SeasonNumber); + } else + { episodeString = "[Unknown Special]"; + } } return string.Format("{0} - {1} {2}", SeriesTitle, episodeString, Quality); diff --git a/src/NzbDrone.Core/Parser/Model/ReleaseInfo.cs b/src/NzbDrone.Core/Parser/Model/ReleaseInfo.cs index ca09b209d..5c6fc8098 100644 --- a/src/NzbDrone.Core/Parser/Model/ReleaseInfo.cs +++ b/src/NzbDrone.Core/Parser/Model/ReleaseInfo.cs @@ -35,9 +35,9 @@ public int Age return DateTime.UtcNow.Subtract(PublishDate).Days; } - //This prevents manually downloading a release from blowing up in mono - //TODO: Is there a better way? - private set { } + private set + { + } } public double AgeHours @@ -47,9 +47,9 @@ public double AgeHours return DateTime.UtcNow.Subtract(PublishDate).TotalHours; } - //This prevents manually downloading a release from blowing up in mono - //TODO: Is there a better way? - private set { } + private set + { + } } public double AgeMinutes @@ -59,9 +59,9 @@ public double AgeMinutes return DateTime.UtcNow.Subtract(PublishDate).TotalMinutes; } - //This prevents manually downloading a release from blowing up in mono - //TODO: Is there a better way? - private set { } + private set + { + } } public override string ToString() @@ -92,4 +92,4 @@ public virtual string ToString(string format) } } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Parser/Model/TorrentInfo.cs b/src/NzbDrone.Core/Parser/Model/TorrentInfo.cs index 59aab44a0..7a3909f37 100644 --- a/src/NzbDrone.Core/Parser/Model/TorrentInfo.cs +++ b/src/NzbDrone.Core/Parser/Model/TorrentInfo.cs @@ -49,4 +49,4 @@ public override string ToString(string format) return stringBuilder.ToString(); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Parser/Parser.cs b/src/NzbDrone.Core/Parser/Parser.cs index 5a043dcf3..dacb2dc3f 100644 --- a/src/NzbDrone.Core/Parser/Parser.cs +++ b/src/NzbDrone.Core/Parser/Parser.cs @@ -3,13 +3,14 @@ using System.Globalization; using System.IO; using System.Linq; +using System.Text; using System.Text.RegularExpressions; using NLog; using NzbDrone.Common.Extensions; using NzbDrone.Common.Instrumentation; +using NzbDrone.Core.Languages; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Tv; -using System.Text; namespace NzbDrone.Core.Parser { @@ -27,10 +28,10 @@ public static class Parser // Chinese LoliHouse/ZERO/Lilith-Raws releases don't use the expected brackets, normalize using brackets new RegexReplace(@"^\[(?[^\]]*?(?:LoliHouse|ZERO|Lilith-Raws)[^\]]*?)\](?[^\[\]]+?)(?: - (?<episode>[0-9-]+)\s*|\[第?(?<episode>[0-9]+(?:-[0-9]+)?)话?(?:END|完)?\])\[", "[${subgroup}][${title}][${episode}][", RegexOptions.Compiled), - + // Most Chinese anime releases contain additional brackets/separators for chinese and non-chinese titles, remove junk and replace with normal anime pattern new RegexReplace(@"^\[(?<subgroup>[^\]]+)\](?:\s?★[^\[ -]+\s?)?\[?(?:(?<chinesetitle>[^\]]*?[\u4E00-\u9FCC][^\]]*?)(?:\]\[|\s*[_/·]\s*))?(?<title>[^\]]+?)\]?(?:\[\d{4}\])?\[第?(?<episode>[0-9]+(?:-[0-9]+)?)(?:话|集)?(?:END|完)?\]", "[${subgroup}] ${title} - ${episode} ", RegexOptions.Compiled), - + // Some Chinese anime releases contain both Chinese and English titles, remove the Chinese title and replace with normal anime pattern new RegexReplace(@"^\[(?<subgroup>[^\]]+)\](?:\s)(?:(?<chinesetitle>[^\]]*?[\u4E00-\u9FCC][^\]]*?)(?:\s/\s))(?<title>[^\]]+?)(?:[- ]+)(?<episode>[0-9]+(?:-[0-9]+)?)话?(?:END|完)?", "[${subgroup}] ${title} - ${episode} ", RegexOptions.Compiled) }; @@ -53,7 +54,7 @@ public static class Parser //Multi-Part episodes without a title (S01E05.S01E06) new Regex(@"^(?:\W*S(?<season>(?<!\d+)(?:\d{1,2}|\d{4})(?!\d+))(?:e{1,2}(?<episode>\d{1,3}(?!\d+)))+){2,}", RegexOptions.IgnoreCase | RegexOptions.Compiled), - + //Multi-Part episodes without a title (1x05.1x06) new Regex(@"^(?:\W*(?<season>(?<!\d+)(?:\d{1,2}|\d{4})(?!\d+))(?:x{1,2}(?<episode>\d{1,3}(?!\d+)))+){2,}", RegexOptions.IgnoreCase | RegexOptions.Compiled), @@ -89,7 +90,7 @@ public static class Parser //Anime - [SubGroup] Title with season number in brackets Absolute Episode Number new Regex(@"^\[(?<subgroup>.+?)\][-_. ]?(?<title>[^-]+?)[_. ]+?\(Season[_. ](?<season>\d+)\)[-_. ]+?(?:[-_. ]?(?<absoluteepisode>\d{2,3}(\.\d{1,2})?(?!\d+)))+(?:[-_. ]+(?<special>special|ova|ovd))?.*?(?<hash>\[\w{8}\])?(?:$|\.mkv)", RegexOptions.IgnoreCase | RegexOptions.Compiled), - + //Anime - [SubGroup] Title with trailing number Absolute Episode Number new Regex(@"^\[(?<subgroup>.+?)\][-_. ]?(?<title>[^-]+?)(?:(?<![-_. ]|\b[0]\d+) - )(?:[-_. ]?(?<absoluteepisode>\d{2,3}(\.\d{1,2})?(?!\d+)))+(?:[-_. ]+(?<special>special|ova|ovd))?.*?(?<hash>\[\w{8}\])?(?:$|\.mkv)", RegexOptions.IgnoreCase | RegexOptions.Compiled), @@ -113,7 +114,7 @@ public static class Parser //Multi-episode Repeated (S01E05 - S01E06) new Regex(@"^(?<title>.+?)(?:(?:[-_\W](?<![()\[!]))+S(?<season>(?<!\d+)(?:\d{1,2}|\d{4})(?!\d+))(?:(?:e|[-_. ]e){1,2}(?<episode>\d{1,3}(?!\d+)))+){2,}", RegexOptions.IgnoreCase | RegexOptions.Compiled), - + //Multi-episode Repeated (1x05 - 1x06) new Regex(@"^(?<title>.+?)(?:(?:[-_\W](?<![()\[!]))+(?<season>(?<!\d+)(?:\d{1,2}|\d{4})(?!\d+))(?:x{1,2}(?<episode>\d{1,3}(?!\d+)))+){2,}", RegexOptions.IgnoreCase | RegexOptions.Compiled), @@ -137,7 +138,7 @@ public static class Parser //Anime - Title Absolute Episode Number [SubGroup] [Hash] new Regex(@"^(?<title>.+?)(?:(?:_|-|\s|\.)+(?<absoluteepisode>\d{3}(\.\d{1,2})(?!\d+)))+(?:.+?)\[(?<subgroup>.+?)\].*?(?<hash>\[\w{8}\])?(?:$|\.)", RegexOptions.IgnoreCase | RegexOptions.Compiled), - + //Anime - Title Absolute Episode Number (Year) [SubGroup] new Regex(@"^(?<title>.+?)[-_. ]+(?<absoluteepisode>(?<!\d+)\d{2}(?!\d+))[-_. ](\(\d{4}\))[-_. ]\[(?<subgroup>.+?)\]", RegexOptions.IgnoreCase | RegexOptions.Compiled), @@ -156,7 +157,7 @@ public static class Parser // Multi-episode with title (S01E05-06, S01E05-6) new Regex(@"^(?<title>.+?)(?:[-_\W](?<![()\[!]))+S(?<season>(?<!\d+)(?:\d{1,2})(?!\d+))E(?<episode>\d{1,2}(?!\d+))(?:-(?<episode>\d{1,2}(?!\d+)))+(?:[-_. ]|$)", - RegexOptions.IgnoreCase | RegexOptions.Compiled), + RegexOptions.IgnoreCase | RegexOptions.Compiled), //Episodes with a title, Single episodes (S01E05, 1x05, etc) & Multi-episode (S01E05E06, S01E05-06, S01E05 E06, etc) new Regex(@"^(?<title>.+?)(?:(?:[-_\W](?<![()\[!]))+S?(?<season>(?<!\d+)(?:\d{1,2})(?!\d+))(?:[ex]|\W[ex]){1,2}(?<episode>\d{2,3}(?!\d+))(?:(?:\-|[ex]|\W[ex]|_){1,2}(?<episode>\d{2,3}(?!\d+)))*)\W?(?!\\)", @@ -250,7 +251,7 @@ public static class Parser // Series Title - [02x01] - Episode 1 // Series Title - [02x01x02] - Episode 1 new Regex(@"^(?<title>.+?)?(?:[-_\W](?<![()\[!]))+\[(?<season>(?<!\d+)\d{1,2})(?:(?:-|x){1,2}(?<episode>\d{2}))+\].+?(?:\.|$)", - RegexOptions.IgnoreCase | RegexOptions.Compiled), + RegexOptions.IgnoreCase | RegexOptions.Compiled), // Anime - Title with season number - Absolute Episode Number (Title S01 - EP14) new Regex(@"^(?<title>.+?S\d{1,2})[-_. ]{3,}(?:EP)?(?<absoluteepisode>\d{2,3}(\.\d{1,2})?(?!\d+|[-]))", @@ -359,7 +360,6 @@ public static class Parser RegexOptions.IgnoreCase | RegexOptions.Compiled) }; - private static readonly Regex[] SpecialEpisodeTitleRegex = new Regex[] { new Regex(@"\.S\d+E00\.(?<episodetitle>.+?)(?:\.(?:720p|1080p|2160p|HDTV|WEB|WEBRip|WEB-DL)\.|$)", @@ -408,7 +408,7 @@ public static class Parser // additional Generic match for mixed-case hashes. - Started appearing Jan 2021 new Regex(@"^[0-9a-zA-Z]{39}", RegexOptions.Compiled), - + // additional Generic match for mixed-case hashes. - Started appearing Jan 2021 new Regex(@"^[0-9a-zA-Z]{24}", RegexOptions.Compiled), }; @@ -459,10 +459,8 @@ public static class Parser private static readonly Regex ReleaseGroupRegex = new Regex(@"-(?<releasegroup>[a-z0-9]+(?<part2>-[a-z0-9]+)?(?!.+?(?:480p|576p|720p|1080p|2160p)))(?<!(?:WEB-DL|Blu-Ray|480p|576p|720p|1080p|2160p|DTS-HD|DTS-X|DTS-MA|DTS-ES|-ES|-EN|-CAT|[ ._]\d{4}-\d{2}|-\d{2})(?:\k<part2>)?)(?:\b|[-._ ]|$)|[-._ ]\[(?<releasegroup>[a-z0-9]+)\]$", RegexOptions.IgnoreCase | RegexOptions.Compiled); - private static readonly Regex InvalidReleaseGroupRegex = new Regex(@"^([se]\d+|[0-9a-f]{8})$", RegexOptions.IgnoreCase | RegexOptions.Compiled); - private static readonly Regex AnimeReleaseGroupRegex = new Regex(@"^(?:\[(?<subgroup>(?!\s).+?(?<!\s))\](?:_|-|\s|\.)?)", RegexOptions.IgnoreCase | RegexOptions.Compiled); @@ -511,7 +509,10 @@ public static ParsedEpisodeInfo ParsePath(string path) public static string SimplifyTitle(string title) { - if (!ValidateBeforeParsing(title)) return title; + if (!ValidateBeforeParsing(title)) + { + return title; + } Logger.Debug("Parsing string '{0}'", title); @@ -539,7 +540,10 @@ public static ParsedEpisodeInfo ParseTitle(string title) { try { - if (!ValidateBeforeParsing(title)) return null; + if (!ValidateBeforeParsing(title)) + { + return null; + } Logger.Debug("Parsing string '{0}'", title); @@ -654,7 +658,9 @@ public static ParsedEpisodeInfo ParseTitle(string title) catch (Exception e) { if (!title.ToLower().Contains("password") && !title.ToLower().Contains("yenc")) + { Logger.Error(e, "An error has occurred while trying to parse {0}", title); + } } Logger.Debug("Unable to parse {0}", title); @@ -681,7 +687,9 @@ public static string CleanSeriesTitle(this string title) //If Title only contains numbers return it as is. if (long.TryParse(title, out number)) + { return title; + } // Replace `%` with `percent` to deal with the 3% case title = PercentRegex.Replace(title, "percent"); @@ -726,8 +734,11 @@ public static string ParseReleaseGroup(string title) foreach (var replace in PreSubstitutionRegex) { if (replace.TryReplace(ref title)) + { break; + } } + title = WebsitePrefixRegex.Replace(title); title = CleanTorrentSuffixRegex.Replace(title); @@ -786,6 +797,7 @@ public static string RemoveFileExtension(string title) { return string.Empty; } + return m.Value; }); @@ -875,7 +887,9 @@ private static ParsedEpisodeInfo ParseMatchCollection(MatchCollection matchColle if ((first % 1) != 0 || (last % 1) != 0) { if (absoluteEpisodeCaptures.Count != 1) + { return null; // Multiple matches not allowed for specials + } result.SpecialAbsoluteEpisodeNumbers = new decimal[] { first }; result.Special = true; @@ -951,7 +965,6 @@ private static ParsedEpisodeInfo ParseMatchCollection(MatchCollection matchColle result.SeasonNumber = 1; } } - else { // Try to Parse as a daily show @@ -1117,7 +1130,6 @@ private static decimal ParseDecimal(string value) return number; } - throw new FormatException(string.Format("{0} isn't a number", value)); } } diff --git a/src/NzbDrone.Core/Parser/ParsingService.cs b/src/NzbDrone.Core/Parser/ParsingService.cs index 2b23b078c..d5f6a9b4f 100644 --- a/src/NzbDrone.Core/Parser/ParsingService.cs +++ b/src/NzbDrone.Core/Parser/ParsingService.cs @@ -104,6 +104,7 @@ private Series GetSeriesByAllTitles(ParsedEpisodeInfo parsedEpisodeInfo) { foundSeries = series; } + foundTvdbId = tvdbId; } @@ -510,7 +511,7 @@ private List<Episode> GetAnimeEpisodes(Series series, ParsedEpisodeInfo parsedEp episodes = _episodeService.FindEpisodesBySceneNumbering(series.Id, parsedEpisodeInfo.SeasonNumber, absoluteEpisodeNumber); if (episodes.Empty()) - { + { var episode = _episodeService.FindEpisode(series.Id, parsedEpisodeInfo.SeasonNumber, absoluteEpisodeNumber); episodes.AddIfNotNull(episode); } @@ -603,7 +604,6 @@ private List<Episode> GetStandardEpisodes(Series series, ParsedEpisodeInfo parse { result.Add(episodeInfo); } - else { _logger.Debug("Unable to find {0}", parsedEpisodeInfo); diff --git a/src/NzbDrone.Core/Parser/QualityParser.cs b/src/NzbDrone.Core/Parser/QualityParser.cs index 56748fb19..031190e7f 100644 --- a/src/NzbDrone.Core/Parser/QualityParser.cs +++ b/src/NzbDrone.Core/Parser/QualityParser.cs @@ -47,7 +47,6 @@ public class QualityParser RegexOptions.Compiled); private static readonly Regex ResolutionRegex = new Regex(@"\b(?:(?<R360p>360p)|(?<R480p>480p|640x480|848x480)|(?<R540p>540p)|(?<R576p>576p)|(?<R720p>720p|1280x720|960p)|(?<R1080p>1080p|1920x1080|1440p|FHD|1080i|4kto1080p)|(?<R2160p>2160p|3840x2160|4k[-_. ](?:UHD|HEVC|BD|H265)|(?:UHD|HEVC|BD|H265)[-_. ]4k))\b", - RegexOptions.Compiled | RegexOptions.IgnoreCase); //Handle cases where no resolution is in the release name; assume if UHD then 4k @@ -562,16 +561,50 @@ private static Resolution ParseResolution(string name) var matchimplied = ImpliedResolutionRegex.Match(name); - if (!match.Success & !matchimplied.Success) return Resolution.Unknown; - if (match.Groups["R360p"].Success) return Resolution.R360P; - if (match.Groups["R480p"].Success) return Resolution.R480P; - if (match.Groups["R540p"].Success) return Resolution.R540p; - if (match.Groups["R576p"].Success) return Resolution.R576p; - if (match.Groups["R720p"].Success) return Resolution.R720p; - if (match.Groups["R1080p"].Success) return Resolution.R1080p; - if (match.Groups["R2160p"].Success) return Resolution.R2160p; + if (!match.Success & !matchimplied.Success) + { + return Resolution.Unknown; + } - if (matchimplied.Groups["R2160p"].Success) return Resolution.R2160p; + if (match.Groups["R360p"].Success) + { + return Resolution.R360P; + } + + if (match.Groups["R480p"].Success) + { + return Resolution.R480P; + } + + if (match.Groups["R540p"].Success) + { + return Resolution.R540p; + } + + if (match.Groups["R576p"].Success) + { + return Resolution.R576p; + } + + if (match.Groups["R720p"].Success) + { + return Resolution.R720p; + } + + if (match.Groups["R1080p"].Success) + { + return Resolution.R1080p; + } + + if (match.Groups["R2160p"].Success) + { + return Resolution.R2160p; + } + + if (matchimplied.Groups["R2160p"].Success) + { + return Resolution.R2160p; + } return Resolution.Unknown; } @@ -580,9 +613,20 @@ private static Quality OtherSourceMatch(string name) { var match = OtherSourceRegex.Match(name); - if (!match.Success) return Quality.Unknown; - if (match.Groups["sdtv"].Success) return Quality.SDTV; - if (match.Groups["hdtv"].Success) return Quality.HDTV720p; + if (!match.Success) + { + return Quality.Unknown; + } + + if (match.Groups["sdtv"].Success) + { + return Quality.SDTV; + } + + if (match.Groups["hdtv"].Success) + { + return Quality.HDTV720p; + } return Quality.Unknown; } diff --git a/src/NzbDrone.Core/Parser/RegexReplace.cs b/src/NzbDrone.Core/Parser/RegexReplace.cs index ee9c5ba82..e98c940ed 100644 --- a/src/NzbDrone.Core/Parser/RegexReplace.cs +++ b/src/NzbDrone.Core/Parser/RegexReplace.cs @@ -28,18 +28,27 @@ public RegexReplace(string pattern, MatchEvaluator replacement, RegexOptions reg public string Replace(string input) { if (_replacementFunc != null) + { return _regex.Replace(input, _replacementFunc); + } else + { return _regex.Replace(input, _replacementFormat); + } } public bool TryReplace(ref string input) { var result = _regex.IsMatch(input); if (_replacementFunc != null) + { input = _regex.Replace(input, _replacementFunc); + } else + { input = _regex.Replace(input, _replacementFormat); + } + return result; } diff --git a/src/NzbDrone.Core/Parser/SceneChecker.cs b/src/NzbDrone.Core/Parser/SceneChecker.cs index 188027153..b09459074 100644 --- a/src/NzbDrone.Core/Parser/SceneChecker.cs +++ b/src/NzbDrone.Core/Parser/SceneChecker.cs @@ -6,8 +6,15 @@ public static class SceneChecker //It's better not to use a title that might be scene than to use one that isn't scene public static bool IsSceneTitle(string title) { - if (!title.Contains(".")) return false; - if (title.Contains(" ")) return false; + if (!title.Contains(".")) + { + return false; + } + + if (title.Contains(" ")) + { + return false; + } var parsedTitle = Parser.ParseTitle(title); diff --git a/src/NzbDrone.Core/Profiles/Delay/DelayProfileRepository.cs b/src/NzbDrone.Core/Profiles/Delay/DelayProfileRepository.cs index 8ad771ff3..d268fbb6c 100644 --- a/src/NzbDrone.Core/Profiles/Delay/DelayProfileRepository.cs +++ b/src/NzbDrone.Core/Profiles/Delay/DelayProfileRepository.cs @@ -5,7 +5,6 @@ namespace NzbDrone.Core.Profiles.Delay { public interface IDelayProfileRepository : IBasicRepository<DelayProfile> { - } public class DelayProfileRepository : BasicRepository<DelayProfile>, IDelayProfileRepository diff --git a/src/NzbDrone.Core/Profiles/Delay/DelayProfileService.cs b/src/NzbDrone.Core/Profiles/Delay/DelayProfileService.cs index 282a5c04b..b95072763 100644 --- a/src/NzbDrone.Core/Profiles/Delay/DelayProfileService.cs +++ b/src/NzbDrone.Core/Profiles/Delay/DelayProfileService.cs @@ -31,12 +31,12 @@ public DelayProfileService(IDelayProfileRepository repo, ICacheManager cacheMana } public DelayProfile Add(DelayProfile profile) - { + { profile.Order = _repo.Count(); var result = _repo.Insert(profile); _bestForTagsCache.Clear(); - + return result; } @@ -55,7 +55,10 @@ public void Delete(int id) for (int i = 0; i < all.Count; i++) { - if (all[i].Id == 1) continue; + if (all[i].Id == 1) + { + continue; + } all[i].Order = i + 1; } @@ -127,18 +130,15 @@ public List<DelayProfile> Reorder(int id, int? afterId) { delayProfile.Order = afterOrder + 1; } - else if (delayProfile.Id == after?.Id) { delayProfile.Order = afterOrder; } - else if (delayProfile.Order > afterOrder) { delayProfile.Order = afterCount; afterCount++; } - else if (delayProfile.Order > movingOrder) { delayProfile.Order--; diff --git a/src/NzbDrone.Core/Profiles/Delay/DelayProfileTagInUseValidator.cs b/src/NzbDrone.Core/Profiles/Delay/DelayProfileTagInUseValidator.cs index 4e7ad94fb..cfd08a2f4 100644 --- a/src/NzbDrone.Core/Profiles/Delay/DelayProfileTagInUseValidator.cs +++ b/src/NzbDrone.Core/Profiles/Delay/DelayProfileTagInUseValidator.cs @@ -17,14 +17,20 @@ public DelayProfileTagInUseValidator(IDelayProfileService delayProfileService) protected override bool IsValid(PropertyValidatorContext context) { - if (context.PropertyValue == null) return true; + if (context.PropertyValue == null) + { + return true; + } dynamic instance = context.ParentContext.InstanceToValidate; var instanceId = (int)instance.Id; var collection = context.PropertyValue as HashSet<int>; - if (collection == null || collection.Empty()) return true; + if (collection == null || collection.Empty()) + { + return true; + } return _delayProfileService.All().None(d => d.Id != instanceId && d.Tags.Intersect(collection).Any()); } diff --git a/src/NzbDrone.Core/Profiles/Languages/LanguageProfileInUseException.cs b/src/NzbDrone.Core/Profiles/Languages/LanguageProfileInUseException.cs index bfba8045d..ba8c0e93d 100644 --- a/src/NzbDrone.Core/Profiles/Languages/LanguageProfileInUseException.cs +++ b/src/NzbDrone.Core/Profiles/Languages/LanguageProfileInUseException.cs @@ -7,7 +7,6 @@ public class LanguageProfileInUseException : NzbDroneException public LanguageProfileInUseException(int profileId) : base("Language profile [{0}] is in use.", profileId) { - } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Profiles/Languages/LanguageProfileService.cs b/src/NzbDrone.Core/Profiles/Languages/LanguageProfileService.cs index b55e3140f..0d5303f6c 100644 --- a/src/NzbDrone.Core/Profiles/Languages/LanguageProfileService.cs +++ b/src/NzbDrone.Core/Profiles/Languages/LanguageProfileService.cs @@ -1,11 +1,11 @@ using System.Collections.Generic; using System.Linq; using NLog; +using NzbDrone.Core.ImportLists; +using NzbDrone.Core.Languages; using NzbDrone.Core.Lifecycle; using NzbDrone.Core.Messaging.Events; -using NzbDrone.Core.Languages; using NzbDrone.Core.Tv; -using NzbDrone.Core.ImportLists; namespace NzbDrone.Core.Profiles.Languages { @@ -98,9 +98,9 @@ private LanguageProfile AddDefaultProfile(string name, Language cutoff, params L var profile = new LanguageProfile { - Name = name, - Cutoff = cutoff, - Languages = languages, + Name = name, + Cutoff = cutoff, + Languages = languages, }; return Add(profile); @@ -108,7 +108,10 @@ private LanguageProfile AddDefaultProfile(string name, Language cutoff, params L public void Handle(ApplicationStartedEvent message) { - if (All().Any()) return; + if (All().Any()) + { + return; + } _logger.Info("Setting up default language profiles"); diff --git a/src/NzbDrone.Core/Profiles/Qualities/QualityIndex.cs b/src/NzbDrone.Core/Profiles/Qualities/QualityIndex.cs index 95b115b2f..638796c56 100644 --- a/src/NzbDrone.Core/Profiles/Qualities/QualityIndex.cs +++ b/src/NzbDrone.Core/Profiles/Qualities/QualityIndex.cs @@ -49,7 +49,7 @@ public int CompareTo(QualityIndex right, bool respectGroupOrder) return GroupIndex.CompareTo(right.GroupIndex); } - return indexCompare;; + return indexCompare; } } } diff --git a/src/NzbDrone.Core/Profiles/Qualities/QualityProfileQualityItem.cs b/src/NzbDrone.Core/Profiles/Qualities/QualityProfileQualityItem.cs index 9b94c69da..4b5369749 100644 --- a/src/NzbDrone.Core/Profiles/Qualities/QualityProfileQualityItem.cs +++ b/src/NzbDrone.Core/Profiles/Qualities/QualityProfileQualityItem.cs @@ -29,7 +29,7 @@ public List<Quality> GetQualities() return Items.Select(s => s.Quality).ToList(); } - return new List<Quality>{ Quality }; + return new List<Quality> { Quality }; } public override string ToString() diff --git a/src/NzbDrone.Core/Profiles/Qualities/QualityProfileService.cs b/src/NzbDrone.Core/Profiles/Qualities/QualityProfileService.cs index 763d337b4..208fb52b9 100644 --- a/src/NzbDrone.Core/Profiles/Qualities/QualityProfileService.cs +++ b/src/NzbDrone.Core/Profiles/Qualities/QualityProfileService.cs @@ -70,14 +70,18 @@ public bool Exists(int id) { return _profileRepository.Exists(id); } - + public void Handle(ApplicationStartedEvent message) { - if (All().Any()) return; + if (All().Any()) + { + return; + } _logger.Info("Setting up default quality profiles"); - AddDefaultProfile("Any", Quality.SDTV, + AddDefaultProfile("Any", + Quality.SDTV, Quality.SDTV, Quality.WEBRip480p, Quality.WEBDL480p, @@ -91,31 +95,36 @@ public void Handle(ApplicationStartedEvent message) Quality.Bluray720p, Quality.Bluray1080p); - AddDefaultProfile("SD", Quality.SDTV, + AddDefaultProfile("SD", + Quality.SDTV, Quality.SDTV, Quality.WEBRip480p, Quality.WEBDL480p, Quality.DVD); - AddDefaultProfile("HD-720p", Quality.HDTV720p, + AddDefaultProfile("HD-720p", + Quality.HDTV720p, Quality.HDTV720p, Quality.WEBRip720p, Quality.WEBDL720p, Quality.Bluray720p); - AddDefaultProfile("HD-1080p", Quality.HDTV1080p, + AddDefaultProfile("HD-1080p", + Quality.HDTV1080p, Quality.HDTV1080p, Quality.WEBRip1080p, Quality.WEBDL1080p, Quality.Bluray1080p); - AddDefaultProfile("Ultra-HD", Quality.HDTV2160p, + AddDefaultProfile("Ultra-HD", + Quality.HDTV2160p, Quality.HDTV2160p, Quality.WEBRip2160p, Quality.WEBDL2160p, Quality.Bluray2160p); - AddDefaultProfile("HD - 720p/1080p", Quality.HDTV720p, + AddDefaultProfile("HD - 720p/1080p", + Quality.HDTV720p, Quality.HDTV720p, Quality.HDTV1080p, Quality.WEBRip720p, diff --git a/src/NzbDrone.Core/Profiles/Releases/PreferredWordService.cs b/src/NzbDrone.Core/Profiles/Releases/PreferredWordService.cs index 5e2214de9..73505cb7b 100644 --- a/src/NzbDrone.Core/Profiles/Releases/PreferredWordService.cs +++ b/src/NzbDrone.Core/Profiles/Releases/PreferredWordService.cs @@ -1,9 +1,8 @@ -using NLog; -using NzbDrone.Core.Tv; using System.Collections.Generic; using System.Linq; +using NLog; using NzbDrone.Common.Extensions; -using System; +using NzbDrone.Core.Tv; namespace NzbDrone.Core.Profiles.Releases { diff --git a/src/NzbDrone.Core/Profiles/Releases/TermMatcherService.cs b/src/NzbDrone.Core/Profiles/Releases/TermMatcherService.cs index 21448d367..056ced72f 100644 --- a/src/NzbDrone.Core/Profiles/Releases/TermMatcherService.cs +++ b/src/NzbDrone.Core/Profiles/Releases/TermMatcherService.cs @@ -45,7 +45,6 @@ private ITermMatcher CreateMatcherInternal(string term) else { return new CaseInsensitiveTermMatcher(term); - } } } diff --git a/src/NzbDrone.Core/ProgressMessaging/ProgressMessageContext.cs b/src/NzbDrone.Core/ProgressMessaging/ProgressMessageContext.cs index a87ec5586..fba9ca3f3 100644 --- a/src/NzbDrone.Core/ProgressMessaging/ProgressMessageContext.cs +++ b/src/NzbDrone.Core/ProgressMessaging/ProgressMessageContext.cs @@ -10,7 +10,7 @@ public static class ProgressMessageContext [ThreadStatic] private static bool _reentrancyLock; - + public static CommandModel CommandModel { get { return _commandModel; } @@ -20,7 +20,9 @@ public static CommandModel CommandModel public static bool LockReentrancy() { if (_reentrancyLock) + { return false; + } _reentrancyLock = true; return true; diff --git a/src/NzbDrone.Core/ProgressMessaging/ProgressMessageTarget.cs b/src/NzbDrone.Core/ProgressMessaging/ProgressMessageTarget.cs index 6b69d3046..37885c47d 100644 --- a/src/NzbDrone.Core/ProgressMessaging/ProgressMessageTarget.cs +++ b/src/NzbDrone.Core/ProgressMessaging/ProgressMessageTarget.cs @@ -1,5 +1,5 @@ -using NLog.Config; -using NLog; +using NLog; +using NLog.Config; using NLog.Targets; using NzbDrone.Core.Lifecycle; using NzbDrone.Core.Messaging.Commands; @@ -23,9 +23,16 @@ protected override void Write(LogEventInfo logEvent) { var command = ProgressMessageContext.CommandModel; - if (!IsClientMessage(logEvent, command)) return; - - if (!ProgressMessageContext.LockReentrancy()) return; + if (!IsClientMessage(logEvent, command)) + { + return; + } + + if (!ProgressMessageContext.LockReentrancy()) + { + return; + } + try { _commandQueueManager.SetMessage(command, logEvent.FormattedMessage); diff --git a/src/NzbDrone.Core/Properties/AssemblyInfo.cs b/src/NzbDrone.Core/Properties/AssemblyInfo.cs index 709f9de53..1f23e6a44 100644 --- a/src/NzbDrone.Core/Properties/AssemblyInfo.cs +++ b/src/NzbDrone.Core/Properties/AssemblyInfo.cs @@ -1,3 +1,3 @@ using System.Runtime.CompilerServices; -[assembly: InternalsVisibleTo("Sonarr.Core.Test")] \ No newline at end of file +[assembly: InternalsVisibleTo("Sonarr.Core.Test")] diff --git a/src/NzbDrone.Core/Qualities/Quality.cs b/src/NzbDrone.Core/Qualities/Quality.cs index 88dbda5fd..939013eaa 100644 --- a/src/NzbDrone.Core/Qualities/Quality.cs +++ b/src/NzbDrone.Core/Qualities/Quality.cs @@ -36,15 +36,30 @@ public override int GetHashCode() public bool Equals(Quality other) { - if (ReferenceEquals(null, other)) return false; - if (ReferenceEquals(this, other)) return true; + if (ReferenceEquals(null, other)) + { + return false; + } + + if (ReferenceEquals(this, other)) + { + return true; + } + return Id.Equals(other.Id); } public override bool Equals(object obj) { - if (ReferenceEquals(null, obj)) return false; - if (ReferenceEquals(this, obj)) return true; + if (ReferenceEquals(null, obj)) + { + return false; + } + + if (ReferenceEquals(this, obj)) + { + return true; + } return Equals(obj as Quality); } @@ -70,13 +85,34 @@ public override bool Equals(object obj) public static Quality WEBDL480p => new Quality(8, "WEBDL-480p", QualitySource.Web, 480); public static Quality HDTV1080p => new Quality(9, "HDTV-1080p", QualitySource.Television, 1080); public static Quality RAWHD => new Quality(10, "Raw-HD", QualitySource.TelevisionRaw, 1080); + //public static Quality HDTV480p { get { return new Quality(11, "HDTV-480p", QualitySource.Television, 480); } } - public static Quality WEBRip480p { get { return new Quality(12, "WEBRip-480p", QualitySource.WebRip, 480); } } - public static Quality Bluray480p { get { return new Quality(13, "Bluray-480p", QualitySource.Bluray, 480); } } - public static Quality WEBRip720p { get { return new Quality(14, "WEBRip-720p", QualitySource.WebRip, 720); } } - public static Quality WEBRip1080p { get { return new Quality(15, "WEBRip-1080p", QualitySource.WebRip, 1080); } } + public static Quality WEBRip480p + { + get { return new Quality(12, "WEBRip-480p", QualitySource.WebRip, 480); } + } + + public static Quality Bluray480p + { + get { return new Quality(13, "Bluray-480p", QualitySource.Bluray, 480); } + } + + public static Quality WEBRip720p + { + get { return new Quality(14, "WEBRip-720p", QualitySource.WebRip, 720); } + } + + public static Quality WEBRip1080p + { + get { return new Quality(15, "WEBRip-1080p", QualitySource.WebRip, 1080); } + } + public static Quality HDTV2160p => new Quality(16, "HDTV-2160p", QualitySource.Television, 2160); - public static Quality WEBRip2160p { get { return new Quality(17, "WEBRip-2160p", QualitySource.WebRip, 2160); } } + public static Quality WEBRip2160p + { + get { return new Quality(17, "WEBRip-2160p", QualitySource.WebRip, 2160); } + } + public static Quality WEBDL2160p => new Quality(18, "WEBDL-2160p", QualitySource.Web, 2160); public static Quality Bluray2160p => new Quality(19, "Bluray-2160p", QualitySource.Bluray, 2160); public static Quality Bluray1080pRemux => new Quality(20, "Bluray-1080p Remux", QualitySource.BlurayRaw, 1080); @@ -145,7 +181,10 @@ static Quality() public static Quality FindById(int id) { - if (id == 0) return Unknown; + if (id == 0) + { + return Unknown; + } if (!AllLookup.TryGetValue(id, out var quality)) { diff --git a/src/NzbDrone.Core/Qualities/QualityDefinition.cs b/src/NzbDrone.Core/Qualities/QualityDefinition.cs index 6417c05db..4d73a646d 100644 --- a/src/NzbDrone.Core/Qualities/QualityDefinition.cs +++ b/src/NzbDrone.Core/Qualities/QualityDefinition.cs @@ -1,7 +1,6 @@ using Newtonsoft.Json; using NzbDrone.Core.Datastore; - namespace NzbDrone.Core.Qualities { public class QualityDefinition : ModelBase @@ -18,7 +17,6 @@ public class QualityDefinition : ModelBase public QualityDefinition() { - } public QualityDefinition(Quality quality) @@ -32,4 +30,4 @@ public override string ToString() return Quality.Name; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Qualities/QualityDefinitionRepository.cs b/src/NzbDrone.Core/Qualities/QualityDefinitionRepository.cs index 49941710c..8663b6b4a 100644 --- a/src/NzbDrone.Core/Qualities/QualityDefinitionRepository.cs +++ b/src/NzbDrone.Core/Qualities/QualityDefinitionRepository.cs @@ -1,7 +1,6 @@ using NzbDrone.Core.Datastore; using NzbDrone.Core.Messaging.Events; - namespace NzbDrone.Core.Qualities { public interface IQualityDefinitionRepository : IBasicRepository<QualityDefinition> diff --git a/src/NzbDrone.Core/Qualities/QualityDefinitionService.cs b/src/NzbDrone.Core/Qualities/QualityDefinitionService.cs index 015170943..ba9582e07 100644 --- a/src/NzbDrone.Core/Qualities/QualityDefinitionService.cs +++ b/src/NzbDrone.Core/Qualities/QualityDefinitionService.cs @@ -1,11 +1,11 @@ -using System.Collections.Generic; +using System; +using System.Collections.Generic; using System.Linq; using NLog; -using NzbDrone.Core.Lifecycle; -using NzbDrone.Core.Messaging.Events; -using System; using NzbDrone.Common.Cache; +using NzbDrone.Core.Lifecycle; using NzbDrone.Core.Messaging.Commands; +using NzbDrone.Core.Messaging.Events; using NzbDrone.Core.Qualities.Commands; namespace NzbDrone.Core.Qualities @@ -58,17 +58,17 @@ public QualityDefinition GetById(int id) { return GetAll().Values.Single(v => v.Id == id); } - + public QualityDefinition Get(Quality quality) { return GetAll()[quality]; } - + private void InsertMissingDefinitions() { List<QualityDefinition> insertList = new List<QualityDefinition>(); List<QualityDefinition> updateList = new List<QualityDefinition>(); - + var allDefinitions = Quality.DefaultQualityDefinitions.OrderBy(d => d.Weight).ToList(); var existingDefinitions = _repo.All().ToList(); @@ -80,7 +80,6 @@ private void InsertMissingDefinitions() { insertList.Add(definition); } - else { updateList.Add(existing); @@ -91,7 +90,7 @@ private void InsertMissingDefinitions() _repo.InsertMany(insertList); _repo.UpdateMany(updateList); _repo.DeleteMany(existingDefinitions); - + _cache.Clear(); } diff --git a/src/NzbDrone.Core/Qualities/QualityModel.cs b/src/NzbDrone.Core/Qualities/QualityModel.cs index 7695464d1..7ed2dee13 100644 --- a/src/NzbDrone.Core/Qualities/QualityModel.cs +++ b/src/NzbDrone.Core/Qualities/QualityModel.cs @@ -22,7 +22,6 @@ public class QualityModel : IEmbeddedDocument, IEquatable<QualityModel>, ICompar public QualityModel() : this(Quality.Unknown, new Revision()) { - } public QualityModel(Quality quality, Revision revision = null) @@ -38,18 +37,19 @@ public override string ToString() public override int GetHashCode() { - unchecked // Overflow is fine, just wrap + unchecked { + // Overflow is fine, just wrap int hash = 17; - hash = hash * 23 + Revision.GetHashCode(); - hash = hash * 23 + Quality.GetHashCode(); + hash = (hash * 23) + Revision.GetHashCode(); + hash = (hash * 23) + Quality.GetHashCode(); return hash; } } public int CompareTo(object obj) { - var other = (QualityModel) obj; + var other = (QualityModel)obj; var definition = Quality.DefaultQualityDefinitions.First(q => q.Quality == Quality); var otherDefinition = Quality.DefaultQualityDefinitions.First(q => q.Quality == other.Quality); @@ -88,16 +88,30 @@ public int CompareTo(object obj) public bool Equals(QualityModel other) { - if (ReferenceEquals(null, other)) return false; - if (ReferenceEquals(this, other)) return true; + if (ReferenceEquals(null, other)) + { + return false; + } + + if (ReferenceEquals(this, other)) + { + return true; + } return other.Quality.Equals(Quality) && other.Revision.Equals(Revision); } public override bool Equals(object obj) { - if (ReferenceEquals(null, obj)) return false; - if (ReferenceEquals(this, obj)) return true; + if (ReferenceEquals(null, obj)) + { + return false; + } + + if (ReferenceEquals(this, obj)) + { + return true; + } return Equals(obj as QualityModel); } diff --git a/src/NzbDrone.Core/Qualities/Revision.cs b/src/NzbDrone.Core/Qualities/Revision.cs index e8e7108e5..4847150ff 100644 --- a/src/NzbDrone.Core/Qualities/Revision.cs +++ b/src/NzbDrone.Core/Qualities/Revision.cs @@ -8,7 +8,7 @@ public class Revision : IEquatable<Revision>, IComparable<Revision> private Revision() { } - + public Revision(int version = 1, int real = 0, bool isRepack = false) { Version = version; @@ -22,17 +22,35 @@ public Revision(int version = 1, int real = 0, bool isRepack = false) public bool Equals(Revision other) { - if (ReferenceEquals(null, other)) return false; + if (ReferenceEquals(null, other)) + { + return false; + } return other.Version.Equals(Version) && other.Real.Equals(Real); } public int CompareTo(Revision other) { - if (Real > other.Real) return 1; - if (Real < other.Real) return -1; - if (Version > other.Version) return 1; - if (Version < other.Version) return -1; + if (Real > other.Real) + { + return 1; + } + + if (Real < other.Real) + { + return -1; + } + + if (Version > other.Version) + { + return 1; + } + + if (Version < other.Version) + { + return -1; + } return 0; } @@ -58,8 +76,15 @@ public override int GetHashCode() public override bool Equals(object obj) { - if (ReferenceEquals(null, obj)) return false; - if (ReferenceEquals(this, obj)) return true; + if (ReferenceEquals(null, obj)) + { + return false; + } + + if (ReferenceEquals(this, obj)) + { + return true; + } return Equals(obj as Revision); } @@ -76,32 +101,60 @@ public override bool Equals(object obj) public static bool operator >(Revision left, Revision right) { - if (ReferenceEquals(null, left)) return false; - if (ReferenceEquals(null, right)) return true; + if (ReferenceEquals(null, left)) + { + return false; + } + + if (ReferenceEquals(null, right)) + { + return true; + } return left.CompareTo(right) > 0; } public static bool operator <(Revision left, Revision right) { - if (ReferenceEquals(null, left)) return true; - if (ReferenceEquals(null, right)) return false; + if (ReferenceEquals(null, left)) + { + return true; + } + + if (ReferenceEquals(null, right)) + { + return false; + } return left.CompareTo(right) < 0; } public static bool operator >=(Revision left, Revision right) { - if (ReferenceEquals(null, left)) return false; - if (ReferenceEquals(null, right)) return true; + if (ReferenceEquals(null, left)) + { + return false; + } + + if (ReferenceEquals(null, right)) + { + return true; + } return left.CompareTo(right) >= 0; } public static bool operator <=(Revision left, Revision right) { - if (ReferenceEquals(null, left)) return true; - if (ReferenceEquals(null, right)) return false; + if (ReferenceEquals(null, left)) + { + return true; + } + + if (ReferenceEquals(null, right)) + { + return false; + } return left.CompareTo(right) <= 0; } diff --git a/src/NzbDrone.Core/RemotePathMappings/RemotePathMapping.cs b/src/NzbDrone.Core/RemotePathMappings/RemotePathMapping.cs index 2a1322b5b..1aa7f18a9 100644 --- a/src/NzbDrone.Core/RemotePathMappings/RemotePathMapping.cs +++ b/src/NzbDrone.Core/RemotePathMappings/RemotePathMapping.cs @@ -1,6 +1,5 @@ using NzbDrone.Core.Datastore; - namespace NzbDrone.Core.RemotePathMappings { public class RemotePathMapping : ModelBase @@ -9,4 +8,4 @@ public class RemotePathMapping : ModelBase public string RemotePath { get; set; } public string LocalPath { get; set; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/RemotePathMappings/RemotePathMappingRepository.cs b/src/NzbDrone.Core/RemotePathMappings/RemotePathMappingRepository.cs index a7df3c35a..dc2274362 100644 --- a/src/NzbDrone.Core/RemotePathMappings/RemotePathMappingRepository.cs +++ b/src/NzbDrone.Core/RemotePathMappings/RemotePathMappingRepository.cs @@ -5,12 +5,10 @@ namespace NzbDrone.Core.RemotePathMappings { public interface IRemotePathMappingRepository : IBasicRepository<RemotePathMapping> { - } public class RemotePathMappingRepository : BasicRepository<RemotePathMapping>, IRemotePathMappingRepository { - public RemotePathMappingRepository(IMainDatabase database, IEventAggregator eventAggregator) : base(database, eventAggregator) { @@ -18,4 +16,4 @@ public RemotePathMappingRepository(IMainDatabase database, IEventAggregator even protected override bool PublishModelEvents => true; } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/RemotePathMappings/RemotePathMappingService.cs b/src/NzbDrone.Core/RemotePathMappings/RemotePathMappingService.cs index 5e7b0d889..859bcbee4 100644 --- a/src/NzbDrone.Core/RemotePathMappings/RemotePathMappingService.cs +++ b/src/NzbDrone.Core/RemotePathMappings/RemotePathMappingService.cs @@ -1,11 +1,11 @@ -using System.Linq; -using System; +using System; using System.Collections.Generic; using System.IO; +using System.Linq; using NLog; +using NzbDrone.Common.Cache; using NzbDrone.Common.Disk; using NzbDrone.Common.Extensions; -using NzbDrone.Common.Cache; using NzbDrone.Core.Download; namespace NzbDrone.Core.RemotePathMappings @@ -160,4 +160,4 @@ public OsPath RemapLocalToRemote(string host, OsPath localPath) return localPath; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/RootFolders/RootFolder.cs b/src/NzbDrone.Core/RootFolders/RootFolder.cs index 0ae3b0155..7e6c5444b 100644 --- a/src/NzbDrone.Core/RootFolders/RootFolder.cs +++ b/src/NzbDrone.Core/RootFolders/RootFolder.cs @@ -1,7 +1,6 @@ using System.Collections.Generic; using NzbDrone.Core.Datastore; - namespace NzbDrone.Core.RootFolders { public class RootFolder : ModelBase diff --git a/src/NzbDrone.Core/RootFolders/RootFolderRepository.cs b/src/NzbDrone.Core/RootFolders/RootFolderRepository.cs index 6983b67fc..21a1a5264 100644 --- a/src/NzbDrone.Core/RootFolders/RootFolderRepository.cs +++ b/src/NzbDrone.Core/RootFolders/RootFolderRepository.cs @@ -5,12 +5,10 @@ namespace NzbDrone.Core.RootFolders { public interface IRootFolderRepository : IBasicRepository<RootFolder> { - } public class RootFolderRepository : BasicRepository<RootFolder>, IRootFolderRepository { - public RootFolderRepository(IMainDatabase database, IEventAggregator eventAggregator) : base(database, eventAggregator) { @@ -18,4 +16,4 @@ public RootFolderRepository(IMainDatabase database, IEventAggregator eventAggreg protected override bool PublishModelEvents => true; } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/RootFolders/RootFolderService.cs b/src/NzbDrone.Core/RootFolders/RootFolderService.cs index b88e1e58d..1262ec0c9 100644 --- a/src/NzbDrone.Core/RootFolders/RootFolderService.cs +++ b/src/NzbDrone.Core/RootFolders/RootFolderService.cs @@ -1,7 +1,7 @@ -using System.Linq; using System; using System.Collections.Generic; using System.IO; +using System.Linq; using System.Threading.Tasks; using NLog; using NzbDrone.Common; @@ -41,7 +41,6 @@ public class RootFolderService : IRootFolderService ".grab" }; - public RootFolderService(IRootFolderRepository rootFolderRepository, IDiskProvider diskProvider, ISeriesRepository seriesRepository, @@ -74,6 +73,7 @@ public List<RootFolder> AllWithUnmappedFolders() GetDetails(folder, seriesPaths, true); } } + //We don't want an exception to prevent the root folders from loading in the UI, so they can still be deleted catch (Exception ex) { diff --git a/src/NzbDrone.Core/RootFolders/UnmappedFolder.cs b/src/NzbDrone.Core/RootFolders/UnmappedFolder.cs index de5b28c5e..3a8a919de 100644 --- a/src/NzbDrone.Core/RootFolders/UnmappedFolder.cs +++ b/src/NzbDrone.Core/RootFolders/UnmappedFolder.cs @@ -5,4 +5,4 @@ public class UnmappedFolder public string Name { get; set; } public string Path { get; set; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Security/X509CertificateValidationService.cs b/src/NzbDrone.Core/Security/X509CertificateValidationService.cs index b4578bc0e..3493cd20a 100644 --- a/src/NzbDrone.Core/Security/X509CertificateValidationService.cs +++ b/src/NzbDrone.Core/Security/X509CertificateValidationService.cs @@ -69,7 +69,7 @@ private IPAddress[] GetIPAddresses(string host) { if (IPAddress.TryParse(host, out var ipAddress)) { - return new []{ ipAddress }; + return new[] { ipAddress }; } return Dns.GetHostEntry(host).AddressList; diff --git a/src/NzbDrone.Core/SeriesStats/SeasonStatistics.cs b/src/NzbDrone.Core/SeriesStats/SeasonStatistics.cs index 1b6c5c001..8c730bed6 100644 --- a/src/NzbDrone.Core/SeriesStats/SeasonStatistics.cs +++ b/src/NzbDrone.Core/SeriesStats/SeasonStatistics.cs @@ -1,8 +1,8 @@ -using NzbDrone.Common.Extensions; -using NzbDrone.Core.Datastore; using System; using System.Collections.Generic; using System.Linq; +using NzbDrone.Common.Extensions; +using NzbDrone.Core.Datastore; namespace NzbDrone.Core.SeriesStats { @@ -27,7 +27,10 @@ public DateTime? NextAiring try { - if (!DateTime.TryParse(NextAiringString, out nextAiring)) return null; + if (!DateTime.TryParse(NextAiringString, out nextAiring)) + { + return null; + } } catch (ArgumentOutOfRangeException) { @@ -47,7 +50,10 @@ public DateTime? PreviousAiring try { - if (!DateTime.TryParse(PreviousAiringString, out previousAiring)) return null; + if (!DateTime.TryParse(PreviousAiringString, out previousAiring)) + { + return null; + } } catch (ArgumentOutOfRangeException) { diff --git a/src/NzbDrone.Core/SeriesStats/SeriesStatistics.cs b/src/NzbDrone.Core/SeriesStats/SeriesStatistics.cs index 44f477c0b..fb6215e18 100644 --- a/src/NzbDrone.Core/SeriesStats/SeriesStatistics.cs +++ b/src/NzbDrone.Core/SeriesStats/SeriesStatistics.cs @@ -24,7 +24,10 @@ public DateTime? NextAiring try { - if (!DateTime.TryParse(NextAiringString, out nextAiring)) return null; + if (!DateTime.TryParse(NextAiringString, out nextAiring)) + { + return null; + } } catch (ArgumentOutOfRangeException) { @@ -44,7 +47,10 @@ public DateTime? PreviousAiring try { - if (!DateTime.TryParse(PreviousAiringString, out previousAiring)) return null; + if (!DateTime.TryParse(PreviousAiringString, out previousAiring)) + { + return null; + } } catch (ArgumentOutOfRangeException) { diff --git a/src/NzbDrone.Core/SeriesStats/SeriesStatisticsService.cs b/src/NzbDrone.Core/SeriesStats/SeriesStatisticsService.cs index 2c1900f9a..2914a4216 100644 --- a/src/NzbDrone.Core/SeriesStats/SeriesStatisticsService.cs +++ b/src/NzbDrone.Core/SeriesStats/SeriesStatisticsService.cs @@ -29,7 +29,10 @@ public SeriesStatistics SeriesStatistics(int seriesId) { var stats = _seriesStatisticsRepository.SeriesStatistics(seriesId); - if (stats == null || stats.Count == 0) return new SeriesStatistics(); + if (stats == null || stats.Count == 0) + { + return new SeriesStatistics(); + } return MapSeriesStatistics(stats); } diff --git a/src/NzbDrone.Core/Tags/TagDetails.cs b/src/NzbDrone.Core/Tags/TagDetails.cs index 4369f3c72..574f3baff 100644 --- a/src/NzbDrone.Core/Tags/TagDetails.cs +++ b/src/NzbDrone.Core/Tags/TagDetails.cs @@ -18,7 +18,7 @@ public bool InUse { get { - return (SeriesIds.Any() || NotificationIds.Any() || RestrictionIds.Any() || DelayProfileIds.Any() || ImportListIds.Any() || IndexerIds.Any()); + return SeriesIds.Any() || NotificationIds.Any() || RestrictionIds.Any() || DelayProfileIds.Any() || ImportListIds.Any() || IndexerIds.Any(); } } } diff --git a/src/NzbDrone.Core/Tags/TagService.cs b/src/NzbDrone.Core/Tags/TagService.cs index ac1ededfd..863d248af 100644 --- a/src/NzbDrone.Core/Tags/TagService.cs +++ b/src/NzbDrone.Core/Tags/TagService.cs @@ -124,8 +124,7 @@ public List<TagDetails> Details() RestrictionIds = restrictions.Where(c => c.Tags.Contains(tag.Id)).Select(c => c.Id).ToList(), SeriesIds = series.Where(c => c.Tags.Contains(tag.Id)).Select(c => c.Id).ToList(), IndexerIds = indexers.Where(c => c.Tags.Contains(tag.Id)).Select(c => c.Id).ToList() - } - ); + }); } return details; diff --git a/src/NzbDrone.Core/ThingiProvider/ConfigContractNotFoundException.cs b/src/NzbDrone.Core/ThingiProvider/ConfigContractNotFoundException.cs index 47d6ecdf3..83e4013ea 100644 --- a/src/NzbDrone.Core/ThingiProvider/ConfigContractNotFoundException.cs +++ b/src/NzbDrone.Core/ThingiProvider/ConfigContractNotFoundException.cs @@ -8,6 +8,5 @@ public ConfigContractNotFoundException(string contract) : base("Couldn't find config contract " + contract) { } - } } diff --git a/src/NzbDrone.Core/ThingiProvider/Events/ProviderUpdatedEvent.cs b/src/NzbDrone.Core/ThingiProvider/Events/ProviderUpdatedEvent.cs index 66222ad52..d1fbda8e0 100644 --- a/src/NzbDrone.Core/ThingiProvider/Events/ProviderUpdatedEvent.cs +++ b/src/NzbDrone.Core/ThingiProvider/Events/ProviderUpdatedEvent.cs @@ -11,4 +11,4 @@ public ProviderUpdatedEvent(ProviderDefinition definition) Definition = definition; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/ThingiProvider/IProvider.cs b/src/NzbDrone.Core/ThingiProvider/IProvider.cs index 386d2bfaf..ea92d71cd 100644 --- a/src/NzbDrone.Core/ThingiProvider/IProvider.cs +++ b/src/NzbDrone.Core/ThingiProvider/IProvider.cs @@ -14,4 +14,4 @@ public interface IProvider ValidationResult Test(); object RequestAction(string stage, IDictionary<string, string> query); } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/ThingiProvider/IProviderConfig.cs b/src/NzbDrone.Core/ThingiProvider/IProviderConfig.cs index 595e3866c..af3dc2317 100644 --- a/src/NzbDrone.Core/ThingiProvider/IProviderConfig.cs +++ b/src/NzbDrone.Core/ThingiProvider/IProviderConfig.cs @@ -6,4 +6,4 @@ public interface IProviderConfig { NzbDroneValidationResult Validate(); } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/ThingiProvider/IProviderFactory.cs b/src/NzbDrone.Core/ThingiProvider/IProviderFactory.cs index 6889d22e9..0196d1858 100644 --- a/src/NzbDrone.Core/ThingiProvider/IProviderFactory.cs +++ b/src/NzbDrone.Core/ThingiProvider/IProviderFactory.cs @@ -24,4 +24,4 @@ public interface IProviderFactory<TProvider, TProviderDefinition> object RequestAction(TProviderDefinition definition, string action, IDictionary<string, string> query); List<TProviderDefinition> AllForTag(int tagId); } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/ThingiProvider/IProviderRepository.cs b/src/NzbDrone.Core/ThingiProvider/IProviderRepository.cs index 8e7087344..ca7f00135 100644 --- a/src/NzbDrone.Core/ThingiProvider/IProviderRepository.cs +++ b/src/NzbDrone.Core/ThingiProvider/IProviderRepository.cs @@ -2,8 +2,9 @@ namespace NzbDrone.Core.ThingiProvider { - public interface IProviderRepository<TProvider> : IBasicRepository<TProvider> where TProvider : ModelBase, new() + public interface IProviderRepository<TProvider> : IBasicRepository<TProvider> + where TProvider : ModelBase, new() { // void DeleteImplementations(string implementation); } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/ThingiProvider/NullConfig.cs b/src/NzbDrone.Core/ThingiProvider/NullConfig.cs index 9016f6644..f58f4fd95 100644 --- a/src/NzbDrone.Core/ThingiProvider/NullConfig.cs +++ b/src/NzbDrone.Core/ThingiProvider/NullConfig.cs @@ -11,4 +11,4 @@ public NzbDroneValidationResult Validate() return new NzbDroneValidationResult(); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/ThingiProvider/ProviderRepository.cs b/src/NzbDrone.Core/ThingiProvider/ProviderRepository.cs index 1554ef789..019b50ee6 100644 --- a/src/NzbDrone.Core/ThingiProvider/ProviderRepository.cs +++ b/src/NzbDrone.Core/ThingiProvider/ProviderRepository.cs @@ -17,4 +17,4 @@ protected ProviderRepository(IMainDatabase database, IEventAggregator eventAggre // DataMapper.Delete<TProviderDefinition>(c => c.Implementation == implementation); // } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/ThingiProvider/Status/ProviderStatusRepository.cs b/src/NzbDrone.Core/ThingiProvider/Status/ProviderStatusRepository.cs index 2c1b184f1..46369dd99 100644 --- a/src/NzbDrone.Core/ThingiProvider/Status/ProviderStatusRepository.cs +++ b/src/NzbDrone.Core/ThingiProvider/Status/ProviderStatusRepository.cs @@ -15,7 +15,6 @@ public interface IProviderStatusRepository<TModel> : IBasicRepository<TModel> public class ProviderStatusRepository<TModel> : BasicRepository<TModel>, IProviderStatusRepository<TModel> where TModel : ProviderStatusBase, new() - { public ProviderStatusRepository(IMainDatabase database, IEventAggregator eventAggregator) : base(database, eventAggregator) diff --git a/src/NzbDrone.Core/TinyTwitter.cs b/src/NzbDrone.Core/TinyTwitter.cs index 91af2f1ff..9179f47f0 100644 --- a/src/NzbDrone.Core/TinyTwitter.cs +++ b/src/NzbDrone.Core/TinyTwitter.cs @@ -1,5 +1,4 @@ -using Newtonsoft.Json; -using System; +using System; using System.Collections.Generic; using System.IO; using System.Linq; @@ -7,6 +6,7 @@ using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions; +using Newtonsoft.Json; namespace TinyTwitter { @@ -50,7 +50,6 @@ public void UpdateStatus(string message) * and added this banner so it's not blindly updated. * **/ - public void DirectMessage(string message, string screenName) { new RequestBuilder(_oauth, "POST", "https://api.twitter.com/1.1/direct_messages/new.json") diff --git a/src/NzbDrone.Core/Tv/AddSeriesService.cs b/src/NzbDrone.Core/Tv/AddSeriesService.cs index 5cedf5b4c..1f34d4c1f 100644 --- a/src/NzbDrone.Core/Tv/AddSeriesService.cs +++ b/src/NzbDrone.Core/Tv/AddSeriesService.cs @@ -54,9 +54,8 @@ public Series AddSeries(Series newSeries) return newSeries; } - public List<Series> AddSeries(List<Series> newSeries, bool ignoreErrors = false) + public List<Series> AddSeries(List<Series> newSeries, bool ignoreErrors = false) { - var added = DateTime.UtcNow; var seriesToAdd = new List<Series>(); var existingSeries = _seriesService.GetAllSeries(); @@ -82,17 +81,20 @@ public List<Series> AddSeries(List<Series> newSeries, bool ignoreErrors = false) _logger.Debug("TVDB ID {0} was not added due to validation failure: Series already exists in database", s.TvdbId); continue; } + if (seriesToAdd.Any(f => f.TvdbId == series.TvdbId)) { _logger.Debug("TVDB ID {0} was not added due to validation failure: Series already exists on list", s.TvdbId); continue; } + var duplicateSlug = seriesToAdd.FirstOrDefault(f => f.TitleSlug == series.TitleSlug); if (duplicateSlug != null) { _logger.Debug("TVDB ID {0} was not added due to validation failure: Duplicate Slug {1} used by series {2}", s.TvdbId, s.TitleSlug, duplicateSlug.TvdbId); continue; } + seriesToAdd.Add(series); } catch (ValidationException ex) @@ -120,7 +122,7 @@ private Series AddSkyhookData(Series newSeries) catch (SeriesNotFoundException) { _logger.Error("TVDB ID {0} was not found, it may have been removed from TheTVDB. Path: {1}", newSeries.TvdbId, newSeries.Path); - + throw new ValidationException(new List<ValidationFailure> { new ValidationFailure("TvdbId", $"A series with this ID was not found. Path: {newSeries.Path}", newSeries.TvdbId) diff --git a/src/NzbDrone.Core/Tv/EpisodeAddedService.cs b/src/NzbDrone.Core/Tv/EpisodeAddedService.cs index 049a18963..f49746e65 100644 --- a/src/NzbDrone.Core/Tv/EpisodeAddedService.cs +++ b/src/NzbDrone.Core/Tv/EpisodeAddedService.cs @@ -47,7 +47,7 @@ public void SearchForRecentlyAdded(int seriesId) _commandQueueManager.Push(new EpisodeSearchCommand(missing.Select(e => e.Id).ToList())); } } - + _addedEpisodesCache.Remove(seriesId.ToString()); } diff --git a/src/NzbDrone.Core/Tv/EpisodeCutoffService.cs b/src/NzbDrone.Core/Tv/EpisodeCutoffService.cs index 2f2cee225..29d298dd0 100644 --- a/src/NzbDrone.Core/Tv/EpisodeCutoffService.cs +++ b/src/NzbDrone.Core/Tv/EpisodeCutoffService.cs @@ -2,10 +2,10 @@ using System.Linq; using NLog; using NzbDrone.Core.Datastore; -using NzbDrone.Core.Qualities; using NzbDrone.Core.Languages; -using NzbDrone.Core.Profiles.Qualities; using NzbDrone.Core.Profiles.Languages; +using NzbDrone.Core.Profiles.Qualities; +using NzbDrone.Core.Qualities; namespace NzbDrone.Core.Tv { @@ -33,7 +33,7 @@ public PagingSpec<Episode> EpisodesWhereCutoffUnmet(PagingSpec<Episode> pagingSp var languagesBelowCutoff = new List<LanguagesBelowCutoff>(); var profiles = _qualityProfileService.All(); var languageProfiles = _languageProfileService.All(); - + //Get all items less than the cutoff foreach (var profile in profiles) { diff --git a/src/NzbDrone.Core/Tv/EpisodeMonitoredService.cs b/src/NzbDrone.Core/Tv/EpisodeMonitoredService.cs index 07dfadc3d..eaf1a6235 100644 --- a/src/NzbDrone.Core/Tv/EpisodeMonitoredService.cs +++ b/src/NzbDrone.Core/Tv/EpisodeMonitoredService.cs @@ -128,16 +128,17 @@ public void SetEpisodeMonitoredStatus(Series series, MonitoringOptions monitorin { season.Monitored = true; } - // Don't monitor season 1 if only the pilot episode is monitored else if (seasonNumber == firstSeason && monitoringOptions.Monitor == MonitorTypes.Pilot) { + // Don't monitor season 1 if only the pilot episode is monitored season.Monitored = false; } - // Monitor the season if it has any monitor episodes else if (monitoredSeasons.Contains(seasonNumber)) { + // Monitor the season if it has any monitor episodes season.Monitored = true; } + // Don't monitor the season else { @@ -220,7 +221,6 @@ private void ToggleEpisodesMonitoredState(List<Episode> episodes, Func<Episode, { ToggleEpisodesMonitoredState(episodes.Where(predicate), true); ToggleEpisodesMonitoredState(episodes.Where(e => !predicate(e)), false); - } } } diff --git a/src/NzbDrone.Core/Tv/EpisodeRepository.cs b/src/NzbDrone.Core/Tv/EpisodeRepository.cs index a8e1a703a..56eb3c16a 100644 --- a/src/NzbDrone.Core/Tv/EpisodeRepository.cs +++ b/src/NzbDrone.Core/Tv/EpisodeRepository.cs @@ -5,10 +5,10 @@ using NLog; using NzbDrone.Core.Datastore; using NzbDrone.Core.Datastore.Extensions; -using NzbDrone.Core.Messaging.Events; -using NzbDrone.Core.MediaFiles; -using NzbDrone.Core.Qualities; using NzbDrone.Core.Languages; +using NzbDrone.Core.MediaFiles; +using NzbDrone.Core.Messaging.Events; +using NzbDrone.Core.Qualities; namespace NzbDrone.Core.Tv { @@ -150,7 +150,6 @@ public List<Episode> EpisodesBetweenDates(DateTime startDate, DateTime endDate, .Where<Episode>(e => e.AirDateUtc >= startDate) .AndWhere(e => e.AirDateUtc <= endDate); - if (!includeUnmonitored) { query.AndWhere(e => e.Monitored) @@ -184,7 +183,7 @@ public void SetMonitoredBySeason(int seriesId, int seasonNumber, bool monitored) public void SetMonitored(IEnumerable<int> ids, bool monitored) { var mapper = DataMapper; - + mapper.AddParameter("monitored", monitored); var sqlUpdate = $"UPDATE Episodes SET Monitored = @monitored WHERE Id IN ({string.Join(", ", ids)}) AND Monitored != @monitored"; @@ -231,9 +230,10 @@ private SortBuilder<Episode> EpisodesWhereCutoffUnmetQuery(PagingSpec<Episode> p .AndWhere(e => e.EpisodeFileId != 0) .AndWhere(e => e.SeasonNumber >= startingSeasonNumber) .AndWhere( - String.Format("({0} OR {1})", - BuildLanguageCutoffWhereClause(languagesBelowCutoff), + string.Format("({0} OR {1})", + BuildLanguageCutoffWhereClause(languagesBelowCutoff), BuildQualityCutoffWhereClause(qualitiesBelowCutoff))) + //.AndWhere(BuildQualityCutoffWhereClause(qualitiesBelowCutoff, languagesBelowCutoff)) .OrderBy(pagingSpec.OrderByClause(), pagingSpec.ToSortDirection()) .Skip(pagingSpec.PagingOffset()) @@ -248,20 +248,19 @@ private string BuildAirDateUtcCutoffWhereClause(DateTime currentTime) private string BuildLanguageCutoffWhereClause(List<LanguagesBelowCutoff> languagesBelowCutoff) { - var clauses = new List<String>(); + var clauses = new List<string>(); foreach (var language in languagesBelowCutoff) { foreach (var belowCutoff in language.LanguageIds) { - clauses.Add(String.Format("([t1].[LanguageProfileId] = {0} AND [t2].[Language] = {1})", language.ProfileId, belowCutoff)); + clauses.Add(string.Format("([t1].[LanguageProfileId] = {0} AND [t2].[Language] = {1})", language.ProfileId, belowCutoff)); } } - return String.Format("({0})", String.Join(" OR ", clauses)); + return string.Format("({0})", string.Join(" OR ", clauses)); } - private string BuildQualityCutoffWhereClause(List<QualitiesBelowCutoff> qualitiesBelowCutoff) { var clauses = new List<string>(); @@ -283,9 +282,15 @@ private Episode FindOneByAirDate(int seriesId, string date) .AndWhere(s => s.AirDate == date) .ToList(); - if (!episodes.Any()) return null; + if (!episodes.Any()) + { + return null; + } - if (episodes.Count == 1) return episodes.First(); + if (episodes.Count == 1) + { + return episodes.First(); + } _logger.Debug("Multiple episodes with the same air date were found, will exclude specials"); diff --git a/src/NzbDrone.Core/Tv/EpisodeService.cs b/src/NzbDrone.Core/Tv/EpisodeService.cs index 8c0b7e5be..1cc3ae12b 100644 --- a/src/NzbDrone.Core/Tv/EpisodeService.cs +++ b/src/NzbDrone.Core/Tv/EpisodeService.cs @@ -128,7 +128,7 @@ public Episode FindEpisodeByTitle(int seriesId, int seasonNumber, string release } }); - var matches = possibleMatches + var matches = possibleMatches .Where(e => e.Episode.Title.Length > 0 && e.Position >= 0) .OrderBy(e => e.Position) .ThenByDescending(e => e.Length) @@ -224,7 +224,6 @@ public void Handle(EpisodeFileDeletedEvent message) var unmonitorForReason = message.Reason != DeleteMediaFileReason.Upgrade && message.Reason != DeleteMediaFileReason.ManualOverride; - _episodeRepository.ClearFileId(episode, unmonitorForReason && _configService.AutoUnmonitorPreviouslyDownloadedEpisodes); } } @@ -242,9 +241,15 @@ private Episode FindOneByAirDate(int seriesId, string date, int? part) { var episodes = _episodeRepository.Find(seriesId, date); - if (!episodes.Any()) return null; + if (!episodes.Any()) + { + return null; + } - if (episodes.Count == 1) return episodes.First(); + if (episodes.Count == 1) + { + return episodes.First(); + } _logger.Debug("Multiple episodes with the same air date were found, will exclude specials"); diff --git a/src/NzbDrone.Core/Tv/Events/EpisodeInfoRefreshedEvent.cs b/src/NzbDrone.Core/Tv/Events/EpisodeInfoRefreshedEvent.cs index d991af5c0..090ea270e 100644 --- a/src/NzbDrone.Core/Tv/Events/EpisodeInfoRefreshedEvent.cs +++ b/src/NzbDrone.Core/Tv/Events/EpisodeInfoRefreshedEvent.cs @@ -18,4 +18,4 @@ public EpisodeInfoRefreshedEvent(Series series, IList<Episode> added, IList<Epis Removed = new ReadOnlyCollection<Episode>(removed); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Tv/Events/SeriesDeletedEvent.cs b/src/NzbDrone.Core/Tv/Events/SeriesDeletedEvent.cs index 02dbdbd25..bdc9f89ca 100644 --- a/src/NzbDrone.Core/Tv/Events/SeriesDeletedEvent.cs +++ b/src/NzbDrone.Core/Tv/Events/SeriesDeletedEvent.cs @@ -15,4 +15,4 @@ public SeriesDeletedEvent(Series series, bool deleteFiles, bool addImportListExc AddImportListExclusion = addImportListExclusion; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Tv/Events/SeriesEditedEvent.cs b/src/NzbDrone.Core/Tv/Events/SeriesEditedEvent.cs index 790cd9c16..601ab99ef 100644 --- a/src/NzbDrone.Core/Tv/Events/SeriesEditedEvent.cs +++ b/src/NzbDrone.Core/Tv/Events/SeriesEditedEvent.cs @@ -15,4 +15,4 @@ public SeriesEditedEvent(Series series, Series oldSeries, bool episodesChanged = EpisodesChanged = episodesChanged; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Tv/Events/SeriesRefreshCompleteEvent.cs b/src/NzbDrone.Core/Tv/Events/SeriesRefreshCompleteEvent.cs index 45c6360b4..de03a5cb2 100644 --- a/src/NzbDrone.Core/Tv/Events/SeriesRefreshCompleteEvent.cs +++ b/src/NzbDrone.Core/Tv/Events/SeriesRefreshCompleteEvent.cs @@ -5,4 +5,4 @@ namespace NzbDrone.Core.Tv.Events public class SeriesRefreshCompleteEvent : IEvent { } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Tv/Events/SeriesRefreshStartingEvent.cs b/src/NzbDrone.Core/Tv/Events/SeriesRefreshStartingEvent.cs index e330b0004..cb3b6fc5f 100644 --- a/src/NzbDrone.Core/Tv/Events/SeriesRefreshStartingEvent.cs +++ b/src/NzbDrone.Core/Tv/Events/SeriesRefreshStartingEvent.cs @@ -11,4 +11,4 @@ public SeriesRefreshStartingEvent(bool manualTrigger) ManualTrigger = manualTrigger; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Tv/Events/SeriesUpdatedEvent.cs b/src/NzbDrone.Core/Tv/Events/SeriesUpdatedEvent.cs index 8dafe0563..32bb77995 100644 --- a/src/NzbDrone.Core/Tv/Events/SeriesUpdatedEvent.cs +++ b/src/NzbDrone.Core/Tv/Events/SeriesUpdatedEvent.cs @@ -11,4 +11,4 @@ public SeriesUpdatedEvent(Series series) Series = series; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Tv/MultipleSeriesFoundException.cs b/src/NzbDrone.Core/Tv/MultipleSeriesFoundException.cs index 608e82c26..37e13ecd7 100644 --- a/src/NzbDrone.Core/Tv/MultipleSeriesFoundException.cs +++ b/src/NzbDrone.Core/Tv/MultipleSeriesFoundException.cs @@ -4,7 +4,8 @@ namespace NzbDrone.Core.Tv { public class MultipleSeriesFoundException : NzbDroneException { - public MultipleSeriesFoundException(string message, params object[] args) : base(message, args) + public MultipleSeriesFoundException(string message, params object[] args) + : base(message, args) { } } diff --git a/src/NzbDrone.Core/Tv/RefreshEpisodeService.cs b/src/NzbDrone.Core/Tv/RefreshEpisodeService.cs index 8cfd052f2..df2466557 100644 --- a/src/NzbDrone.Core/Tv/RefreshEpisodeService.cs +++ b/src/NzbDrone.Core/Tv/RefreshEpisodeService.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using NLog; @@ -105,7 +105,9 @@ public void RefreshEpisodeInfo(Series series, IEnumerable<Episode> remoteEpisode if (failCount != 0) { _logger.Info("Finished episode refresh for series: {0}. Successful: {1} - Failed: {2} ", - series.Title, successCount, failCount); + series.Title, + successCount, + failCount); } else { @@ -124,7 +126,6 @@ private bool GetMonitoredStatus(Episode episode, IEnumerable<Season> seasons) return season == null || season.Monitored; } - private void UnmonitorReaddedEpisodes(Series series, List<Episode> episodes, bool hasExisting) { if (series.AddOptions != null) @@ -214,7 +215,10 @@ private Episode GetEpisodeToUpdate(Series series, Episode episode, List<Episode> { var matchingEpisode = existingEpisodes.FirstOrDefault(e => e.AbsoluteEpisodeNumber == episode.AbsoluteEpisodeNumber); - if (matchingEpisode != null) return matchingEpisode; + if (matchingEpisode != null) + { + return matchingEpisode; + } } } @@ -238,4 +242,4 @@ private IEnumerable<Episode> OrderEpisodes(Series series, List<Episode> episodes return episodes.OrderBy(e => e.SeasonNumber).ThenBy(e => e.EpisodeNumber); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Tv/RefreshSeriesService.cs b/src/NzbDrone.Core/Tv/RefreshSeriesService.cs index 18bc4c493..7ef62f68e 100644 --- a/src/NzbDrone.Core/Tv/RefreshSeriesService.cs +++ b/src/NzbDrone.Core/Tv/RefreshSeriesService.cs @@ -31,7 +31,6 @@ public RefreshSeriesService(IProvideSeriesInfo seriesInfo, ISeriesService seriesService, IRefreshEpisodeService refreshEpisodeService, IEventAggregator eventAggregator, - IDiskScanService diskScanService, ICheckIfSeriesShouldBeRefreshed checkIfSeriesShouldBeRefreshed, IConfigService configService, @@ -73,6 +72,7 @@ private Series RefreshSeriesInfo(int seriesId) _logger.Debug("Series marked as deleted on tvdb for {0}", series.Title); _eventAggregator.PublishEvent(new SeriesUpdatedEvent(series)); } + throw; } @@ -145,7 +145,6 @@ private List<Season> UpdateSeasons(Series series, Series seriesInfo) _logger.Debug("New season ({0}) for series: [{1}] {2}, setting monitored to {3}", season.SeasonNumber, series.TvdbId, series.Title, series.Monitored.ToString().ToLowerInvariant()); season.Monitored = series.Monitored; } - else { season.Monitored = existingSeason.Monitored; @@ -242,7 +241,6 @@ public void Execute(RefreshSeriesCommand message) RescanSeries(seriesLocal, false, trigger); } - else { _logger.Info("Skipping refresh of series: {0}", seriesLocal.Title); diff --git a/src/NzbDrone.Core/Tv/Season.cs b/src/NzbDrone.Core/Tv/Season.cs index e233c734f..b581f26b8 100644 --- a/src/NzbDrone.Core/Tv/Season.cs +++ b/src/NzbDrone.Core/Tv/Season.cs @@ -14,4 +14,4 @@ public Season() public bool Monitored { get; set; } public List<MediaCover.MediaCover> Images { get; set; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Tv/Series.cs b/src/NzbDrone.Core/Tv/Series.cs index 9de6a86ee..74484ab39 100644 --- a/src/NzbDrone.Core/Tv/Series.cs +++ b/src/NzbDrone.Core/Tv/Series.cs @@ -3,8 +3,8 @@ using Marr.Data; using NzbDrone.Common.Extensions; using NzbDrone.Core.Datastore; -using NzbDrone.Core.Profiles.Qualities; using NzbDrone.Core.Profiles.Languages; +using NzbDrone.Core.Profiles.Qualities; namespace NzbDrone.Core.Tv { diff --git a/src/NzbDrone.Core/Tv/SeriesRepository.cs b/src/NzbDrone.Core/Tv/SeriesRepository.cs index e15b2df16..348c7340f 100644 --- a/src/NzbDrone.Core/Tv/SeriesRepository.cs +++ b/src/NzbDrone.Core/Tv/SeriesRepository.cs @@ -4,7 +4,6 @@ using NzbDrone.Core.Exceptions; using NzbDrone.Core.Messaging.Events; - namespace NzbDrone.Core.Tv { public interface ISeriesRepository : IBasicRepository<Series> diff --git a/src/NzbDrone.Core/Tv/SeriesService.cs b/src/NzbDrone.Core/Tv/SeriesService.cs index e62dc97ea..8f2b1e865 100644 --- a/src/NzbDrone.Core/Tv/SeriesService.cs +++ b/src/NzbDrone.Core/Tv/SeriesService.cs @@ -104,11 +104,13 @@ public Series FindByTitleInexact(string title) // no series matched return null; } + if (list.Count == 1) { // return the first series if there is only one return list.Single(); } + // build ordered list of series by position in the search string var query = list.Select(series => new @@ -117,7 +119,7 @@ public Series FindByTitleInexact(string title) length = series.CleanTitle.Length, series = series }) - .Where(s => (s.position>=0)) + .Where(s => (s.position >= 0)) .ToList() .OrderBy(s => s.position) .ThenByDescending(s => s.length) diff --git a/src/NzbDrone.Core/Tv/SeriesTitleNormalizer.cs b/src/NzbDrone.Core/Tv/SeriesTitleNormalizer.cs index 484321e8a..15959031d 100644 --- a/src/NzbDrone.Core/Tv/SeriesTitleNormalizer.cs +++ b/src/NzbDrone.Core/Tv/SeriesTitleNormalizer.cs @@ -6,7 +6,10 @@ public static class SeriesTitleNormalizer { private static readonly Dictionary<int, string> PreComputedTitles = new Dictionary<int, string> { - { 281588, "a to z" } + { 281588, "a to z" }, + { 289260, "ad bible continues" }, + { 328534, "ap bio" }, + { 77904, "ateam" } }; public static string Normalize(string title, int tvdbId) diff --git a/src/NzbDrone.Core/Tv/SeriesTitleSlugValidator.cs b/src/NzbDrone.Core/Tv/SeriesTitleSlugValidator.cs index eb3ecb69b..90664f00f 100644 --- a/src/NzbDrone.Core/Tv/SeriesTitleSlugValidator.cs +++ b/src/NzbDrone.Core/Tv/SeriesTitleSlugValidator.cs @@ -16,8 +16,10 @@ public SeriesTitleSlugValidator(ISeriesService seriesService) protected override bool IsValid(PropertyValidatorContext context) { - if (context.PropertyValue == null) return true; - + if (context.PropertyValue == null) + { + return true; + } dynamic instance = context.ParentContext.InstanceToValidate; var instanceId = (int)instance.Id; diff --git a/src/NzbDrone.Core/Tv/SeriesTypes.cs b/src/NzbDrone.Core/Tv/SeriesTypes.cs index 176ff7655..c5b758f9c 100644 --- a/src/NzbDrone.Core/Tv/SeriesTypes.cs +++ b/src/NzbDrone.Core/Tv/SeriesTypes.cs @@ -6,4 +6,4 @@ public enum SeriesTypes Daily = 1, Anime = 2, } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Update/ConfigureUpdateMechanism.cs b/src/NzbDrone.Core/Update/ConfigureUpdateMechanism.cs index b1c2b951e..79e91bce1 100644 --- a/src/NzbDrone.Core/Update/ConfigureUpdateMechanism.cs +++ b/src/NzbDrone.Core/Update/ConfigureUpdateMechanism.cs @@ -11,7 +11,6 @@ namespace NzbDrone.Core.Update { public interface IUpdaterConfigProvider { - } public class UpdaterConfigProvider : IUpdaterConfigProvider, IHandle<ApplicationStartedEvent> diff --git a/src/NzbDrone.Core/Update/Events/UpdateInstalledEvent.cs b/src/NzbDrone.Core/Update/Events/UpdateInstalledEvent.cs index d16b8095c..ccd122620 100644 --- a/src/NzbDrone.Core/Update/Events/UpdateInstalledEvent.cs +++ b/src/NzbDrone.Core/Update/Events/UpdateInstalledEvent.cs @@ -14,4 +14,4 @@ public UpdateInstalledEvent(Version previousVersion, Version newVersion) NewVersion = newVersion; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Update/History/UpdateHistoryRepository.cs b/src/NzbDrone.Core/Update/History/UpdateHistoryRepository.cs index 66ae01fbd..e6de4a2f4 100644 --- a/src/NzbDrone.Core/Update/History/UpdateHistoryRepository.cs +++ b/src/NzbDrone.Core/Update/History/UpdateHistoryRepository.cs @@ -20,7 +20,6 @@ public class UpdateHistoryRepository : BasicRepository<UpdateHistory>, IUpdateHi public UpdateHistoryRepository(ILogDatabase logDatabase, IEventAggregator eventAggregator) : base(logDatabase, eventAggregator) { - } public UpdateHistory LastInstalled() diff --git a/src/NzbDrone.Core/Update/InstallUpdateService.cs b/src/NzbDrone.Core/Update/InstallUpdateService.cs index c4fa62daa..74e063ef4 100644 --- a/src/NzbDrone.Core/Update/InstallUpdateService.cs +++ b/src/NzbDrone.Core/Update/InstallUpdateService.cs @@ -60,6 +60,7 @@ public InstallUpdateService(ICheckUpdateService checkUpdateService, { throw new ArgumentNullException(nameof(configFileProvider)); } + _checkUpdateService = checkUpdateService; _appFolderInfo = appFolderInfo; _commandQueueManager = commandQueueManager; @@ -248,7 +249,6 @@ private UpdatePackage GetUpdatePackage(CommandTrigger updateTrigger) return null; } - // Safety net, ConfigureUpdateMechanism should take care of invalid settings if (_configFileProvider.UpdateMechanism == UpdateMechanism.BuiltIn && _deploymentInfoProvider.IsExternalUpdateMechanism) { @@ -332,7 +332,6 @@ public void Handle(ApplicationStartingEvent message) return; } - _logger.Info("Installing post-install update from {0} to {1}", BuildInfo.Version, latestAvailable.Version); _diskProvider.DeleteFile(updateMarker); diff --git a/src/NzbDrone.Core/Update/UpdateCheckService.cs b/src/NzbDrone.Core/Update/UpdateCheckService.cs index fc40e2194..4f0e7d4ec 100644 --- a/src/NzbDrone.Core/Update/UpdateCheckService.cs +++ b/src/NzbDrone.Core/Update/UpdateCheckService.cs @@ -13,7 +13,6 @@ public class CheckUpdateService : ICheckUpdateService private readonly IUpdatePackageProvider _updatePackageProvider; private readonly IConfigFileProvider _configFileProvider; - public CheckUpdateService(IUpdatePackageProvider updatePackageProvider, IConfigFileProvider configFileProvider) { diff --git a/src/NzbDrone.Core/Validation/FileChmodValidator.cs b/src/NzbDrone.Core/Validation/FileChmodValidator.cs index d0150a868..3e90bf9fa 100644 --- a/src/NzbDrone.Core/Validation/FileChmodValidator.cs +++ b/src/NzbDrone.Core/Validation/FileChmodValidator.cs @@ -15,9 +15,12 @@ public FolderChmodValidator(IDiskProvider diskProvider) protected override bool IsValid(PropertyValidatorContext context) { - if (context.PropertyValue == null) return false; + if (context.PropertyValue == null) + { + return false; + } return _diskProvider.IsValidFolderPermissionMask(context.PropertyValue.ToString()); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Validation/FolderValidator.cs b/src/NzbDrone.Core/Validation/FolderValidator.cs index 32bcb141c..9eedeb459 100644 --- a/src/NzbDrone.Core/Validation/FolderValidator.cs +++ b/src/NzbDrone.Core/Validation/FolderValidator.cs @@ -12,8 +12,12 @@ public FolderValidator() protected override bool IsValid(PropertyValidatorContext context) { - if (context.PropertyValue == null) return false; + if (context.PropertyValue == null) + { + return false; + } + return context.PropertyValue.ToString().IsPathValid(); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Validation/LanguageProfileExistsValidator.cs b/src/NzbDrone.Core/Validation/LanguageProfileExistsValidator.cs index 90450e3e5..0e3b1e7db 100644 --- a/src/NzbDrone.Core/Validation/LanguageProfileExistsValidator.cs +++ b/src/NzbDrone.Core/Validation/LanguageProfileExistsValidator.cs @@ -15,9 +15,12 @@ public LanguageProfileExistsValidator(ILanguageProfileService profileService) protected override bool IsValid(PropertyValidatorContext context) { - if (context.PropertyValue == null) return true; + if (context.PropertyValue == null) + { + return true; + } return _profileService.Exists((int)context.PropertyValue); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Validation/NzbDroneValidationFailure.cs b/src/NzbDrone.Core/Validation/NzbDroneValidationFailure.cs index c8db4a84b..0cd3c9026 100644 --- a/src/NzbDrone.Core/Validation/NzbDroneValidationFailure.cs +++ b/src/NzbDrone.Core/Validation/NzbDroneValidationFailure.cs @@ -11,13 +11,11 @@ public class NzbDroneValidationFailure : ValidationFailure public NzbDroneValidationFailure(string propertyName, string error) : base(propertyName, error) { - } public NzbDroneValidationFailure(string propertyName, string error, object attemptedValue) : base(propertyName, error, attemptedValue) { - } public NzbDroneValidationFailure(ValidationFailure validationFailure) diff --git a/src/NzbDrone.Core/Validation/NzbDroneValidationResult.cs b/src/NzbDrone.Core/Validation/NzbDroneValidationResult.cs index d675fbb7a..5de154984 100644 --- a/src/NzbDrone.Core/Validation/NzbDroneValidationResult.cs +++ b/src/NzbDrone.Core/Validation/NzbDroneValidationResult.cs @@ -31,6 +31,7 @@ public NzbDroneValidationResult(IEnumerable<ValidationFailure> failures) { failure = new NzbDroneValidationFailure(failureBase); } + if (failure.IsWarning) { warnings.Add(failure); @@ -55,4 +56,4 @@ public NzbDroneValidationResult(IEnumerable<ValidationFailure> failures) public override bool IsValid => Errors.Empty(); } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Validation/Paths/FolderWritableValidator.cs b/src/NzbDrone.Core/Validation/Paths/FolderWritableValidator.cs index bf88cf3be..c58b5a273 100644 --- a/src/NzbDrone.Core/Validation/Paths/FolderWritableValidator.cs +++ b/src/NzbDrone.Core/Validation/Paths/FolderWritableValidator.cs @@ -16,9 +16,12 @@ public FolderWritableValidator(IDiskProvider diskProvider) protected override bool IsValid(PropertyValidatorContext context) { - if (context.PropertyValue == null) return false; + if (context.PropertyValue == null) + { + return false; + } - return (_diskProvider.FolderWritable(context.PropertyValue.ToString())); + return _diskProvider.FolderWritable(context.PropertyValue.ToString()); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Validation/Paths/MappedNetworkDriveValidator.cs b/src/NzbDrone.Core/Validation/Paths/MappedNetworkDriveValidator.cs index b3de0437e..48e3da21e 100644 --- a/src/NzbDrone.Core/Validation/Paths/MappedNetworkDriveValidator.cs +++ b/src/NzbDrone.Core/Validation/Paths/MappedNetworkDriveValidator.cs @@ -22,14 +22,28 @@ public MappedNetworkDriveValidator(IRuntimeInfo runtimeInfo, IDiskProvider diskP protected override bool IsValid(PropertyValidatorContext context) { - if (context.PropertyValue == null) return false; - if (OsInfo.IsNotWindows) return true; - if (!_runtimeInfo.IsWindowsService) return true; + if (context.PropertyValue == null) + { + return false; + } + + if (OsInfo.IsNotWindows) + { + return true; + } + + if (!_runtimeInfo.IsWindowsService) + { + return true; + } var path = context.PropertyValue.ToString(); - if (!DriveRegex.IsMatch(path)) return true; - + if (!DriveRegex.IsMatch(path)) + { + return true; + } + var mount = _diskProvider.GetMount(path); if (mount != null && mount.DriveType == DriveType.Network) @@ -40,4 +54,4 @@ protected override bool IsValid(PropertyValidatorContext context) return true; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Validation/Paths/PathExistsValidator.cs b/src/NzbDrone.Core/Validation/Paths/PathExistsValidator.cs index 8e3e39aed..77398b5e8 100644 --- a/src/NzbDrone.Core/Validation/Paths/PathExistsValidator.cs +++ b/src/NzbDrone.Core/Validation/Paths/PathExistsValidator.cs @@ -15,9 +15,12 @@ public PathExistsValidator(IDiskProvider diskProvider) protected override bool IsValid(PropertyValidatorContext context) { - if (context.PropertyValue == null) return false; + if (context.PropertyValue == null) + { + return false; + } - return (_diskProvider.FolderExists(context.PropertyValue.ToString())); + return _diskProvider.FolderExists(context.PropertyValue.ToString()); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Validation/Paths/PathValidator.cs b/src/NzbDrone.Core/Validation/Paths/PathValidator.cs index b652672b8..c546d3e79 100644 --- a/src/NzbDrone.Core/Validation/Paths/PathValidator.cs +++ b/src/NzbDrone.Core/Validation/Paths/PathValidator.cs @@ -21,8 +21,12 @@ public PathValidator() protected override bool IsValid(PropertyValidatorContext context) { - if (context.PropertyValue == null) return false; + if (context.PropertyValue == null) + { + return false; + } + return context.PropertyValue.ToString().IsPathValid(); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Validation/Paths/RootFolderValidator.cs b/src/NzbDrone.Core/Validation/Paths/RootFolderValidator.cs index 43bd1e650..8494ac28b 100644 --- a/src/NzbDrone.Core/Validation/Paths/RootFolderValidator.cs +++ b/src/NzbDrone.Core/Validation/Paths/RootFolderValidator.cs @@ -16,9 +16,12 @@ public RootFolderValidator(IRootFolderService rootFolderService) protected override bool IsValid(PropertyValidatorContext context) { - if (context.PropertyValue == null) return true; + if (context.PropertyValue == null) + { + return true; + } - return (!_rootFolderService.All().Exists(r => r.Path.PathEquals(context.PropertyValue.ToString()))); + return !_rootFolderService.All().Exists(r => r.Path.PathEquals(context.PropertyValue.ToString())); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Validation/Paths/SeriesAncestorValidator.cs b/src/NzbDrone.Core/Validation/Paths/SeriesAncestorValidator.cs index ff014aea7..ad6daf850 100644 --- a/src/NzbDrone.Core/Validation/Paths/SeriesAncestorValidator.cs +++ b/src/NzbDrone.Core/Validation/Paths/SeriesAncestorValidator.cs @@ -17,7 +17,10 @@ public SeriesAncestorValidator(ISeriesService seriesService) protected override bool IsValid(PropertyValidatorContext context) { - if (context.PropertyValue == null) return true; + if (context.PropertyValue == null) + { + return true; + } return !_seriesService.GetAllSeriesPaths().Any(s => context.PropertyValue.ToString().IsParentPath(s)); } diff --git a/src/NzbDrone.Core/Validation/Paths/SeriesExistsValidator.cs b/src/NzbDrone.Core/Validation/Paths/SeriesExistsValidator.cs index 21e4ea629..337a53a3b 100644 --- a/src/NzbDrone.Core/Validation/Paths/SeriesExistsValidator.cs +++ b/src/NzbDrone.Core/Validation/Paths/SeriesExistsValidator.cs @@ -16,11 +16,14 @@ public SeriesExistsValidator(ISeriesService seriesService) protected override bool IsValid(PropertyValidatorContext context) { - if (context.PropertyValue == null) return true; + if (context.PropertyValue == null) + { + return true; + } var tvdbId = Convert.ToInt32(context.PropertyValue.ToString()); - return (!_seriesService.GetAllSeries().Exists(s => s.TvdbId == tvdbId)); + return !_seriesService.GetAllSeries().Exists(s => s.TvdbId == tvdbId); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Validation/Paths/SeriesPathValidator.cs b/src/NzbDrone.Core/Validation/Paths/SeriesPathValidator.cs index fa4d8fa59..2194913b2 100644 --- a/src/NzbDrone.Core/Validation/Paths/SeriesPathValidator.cs +++ b/src/NzbDrone.Core/Validation/Paths/SeriesPathValidator.cs @@ -16,12 +16,15 @@ public SeriesPathValidator(ISeriesService seriesService) protected override bool IsValid(PropertyValidatorContext context) { - if (context.PropertyValue == null) return true; + if (context.PropertyValue == null) + { + return true; + } dynamic instance = context.ParentContext.InstanceToValidate; var instanceId = (int)instance.Id; - return (!_seriesService.GetAllSeries().Exists(s => s.Path.PathEquals(context.PropertyValue.ToString()) && s.Id != instanceId)); + return !_seriesService.GetAllSeries().Exists(s => s.Path.PathEquals(context.PropertyValue.ToString()) && s.Id != instanceId); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Validation/Paths/StartupFolderValidator.cs b/src/NzbDrone.Core/Validation/Paths/StartupFolderValidator.cs index 1fa1f0451..9f097f8d2 100644 --- a/src/NzbDrone.Core/Validation/Paths/StartupFolderValidator.cs +++ b/src/NzbDrone.Core/Validation/Paths/StartupFolderValidator.cs @@ -7,7 +7,6 @@ namespace NzbDrone.Core.Validation.Paths public class StartupFolderValidator : PropertyValidator { private readonly IAppFolderInfo _appFolderInfo; - public StartupFolderValidator(IAppFolderInfo appFolderInfo) : base("Path cannot be {relationship} the start up folder") @@ -17,7 +16,10 @@ public StartupFolderValidator(IAppFolderInfo appFolderInfo) protected override bool IsValid(PropertyValidatorContext context) { - if (context.PropertyValue == null) return true; + if (context.PropertyValue == null) + { + return true; + } var startupFolder = _appFolderInfo.StartUpFolder; var folder = context.PropertyValue.ToString(); @@ -39,4 +41,4 @@ protected override bool IsValid(PropertyValidatorContext context) return true; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Validation/ProfileExistsValidator.cs b/src/NzbDrone.Core/Validation/ProfileExistsValidator.cs index 8e90c965a..6970b875f 100644 --- a/src/NzbDrone.Core/Validation/ProfileExistsValidator.cs +++ b/src/NzbDrone.Core/Validation/ProfileExistsValidator.cs @@ -15,9 +15,12 @@ public ProfileExistsValidator(IQualityProfileService qualityProfileService) protected override bool IsValid(PropertyValidatorContext context) { - if (context.PropertyValue == null) return true; + if (context.PropertyValue == null) + { + return true; + } return _qualityProfileService.Exists((int)context.PropertyValue); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Validation/UrlValidator.cs b/src/NzbDrone.Core/Validation/UrlValidator.cs index a52c14a90..844ab80f2 100644 --- a/src/NzbDrone.Core/Validation/UrlValidator.cs +++ b/src/NzbDrone.Core/Validation/UrlValidator.cs @@ -21,8 +21,12 @@ public UrlValidator() protected override bool IsValid(PropertyValidatorContext context) { - if (context.PropertyValue == null) return false; + if (context.PropertyValue == null) + { + return false; + } + return context.PropertyValue.ToString().IsValidUrl(); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Host.Test/ContainerFixture.cs b/src/NzbDrone.Host.Test/ContainerFixture.cs index 594897892..9078bf48f 100644 --- a/src/NzbDrone.Host.Test/ContainerFixture.cs +++ b/src/NzbDrone.Host.Test/ContainerFixture.cs @@ -14,8 +14,8 @@ using NzbDrone.Core.Lifecycle; using NzbDrone.Core.Messaging.Commands; using NzbDrone.Core.Messaging.Events; -using NzbDrone.SignalR; using NzbDrone.Host; +using NzbDrone.SignalR; using NzbDrone.Test.Common; namespace NzbDrone.App.Test @@ -97,4 +97,4 @@ public void should_return_same_instance_of_singletons_by_different_interfaces() first.Should().BeSameAs(second); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Host.Test/NzbDroneProcessServiceFixture.cs b/src/NzbDrone.Host.Test/NzbDroneProcessServiceFixture.cs index 3ce41f5df..4d51521dc 100644 --- a/src/NzbDrone.Host.Test/NzbDroneProcessServiceFixture.cs +++ b/src/NzbDrone.Host.Test/NzbDroneProcessServiceFixture.cs @@ -35,7 +35,7 @@ public void should_continue_if_only_instance() .Setup(c => c.FindProcessByName(It.Is<string>(f => f.Contains("NzbDrone")))) .Returns(new List<ProcessInfo> { - new ProcessInfo {Id = CURRENT_PROCESS_ID} + new ProcessInfo { Id = CURRENT_PROCESS_ID } }); Subject.PreventStartIfAlreadyRunning(); diff --git a/src/NzbDrone.Host.Test/RouterTest.cs b/src/NzbDrone.Host.Test/RouterTest.cs index 843061504..52793f31b 100644 --- a/src/NzbDrone.Host.Test/RouterTest.cs +++ b/src/NzbDrone.Host.Test/RouterTest.cs @@ -18,7 +18,6 @@ public void Setup() WindowsOnly(); } - [Test] public void Route_should_call_install_service_when_application_mode_is_install() { @@ -37,7 +36,6 @@ public void Route_should_call_install_service_when_application_mode_is_install() serviceProviderMock.Verify(c => c.Install(ServiceProvider.SERVICE_NAME), Times.Once()); } - [Test] public void Route_should_call_uninstall_service_when_application_mode_is_uninstall() { @@ -78,7 +76,6 @@ public void Route_should_call_service_start_when_run_in_service_mode() serviceProvider.Verify(c => c.Run(It.IsAny<ServiceBase>()), Times.Once()); } - [Test] public void show_error_on_install_if_service_already_exist() { @@ -90,7 +87,6 @@ public void show_error_on_install_if_service_already_exist() serviceMock.Setup(c => c.ServiceExist(ServiceProvider.SERVICE_NAME)).Returns(true); Subject.Route(ApplicationModes.InstallService); - } [Test] @@ -104,7 +100,6 @@ public void show_error_on_uninstall_if_service_doesnt_exist() serviceMock.Setup(c => c.ServiceExist(ServiceProvider.SERVICE_NAME)).Returns(false); Subject.Route(ApplicationModes.UninstallService); - } } } diff --git a/src/NzbDrone.Host/AccessControl/FirewallAdapter.cs b/src/NzbDrone.Host/AccessControl/FirewallAdapter.cs index 6bc836980..f030ed268 100644 --- a/src/NzbDrone.Host/AccessControl/FirewallAdapter.cs +++ b/src/NzbDrone.Host/AccessControl/FirewallAdapter.cs @@ -58,6 +58,7 @@ private bool IsNzbDronePortOpen(int port) { _logger.Warn(ex, "Failed to check for open port in firewall"); } + return false; } diff --git a/src/NzbDrone.Host/Bootstrap.cs b/src/NzbDrone.Host/Bootstrap.cs index c3e3e85f9..0dac43281 100644 --- a/src/NzbDrone.Host/Bootstrap.cs +++ b/src/NzbDrone.Host/Bootstrap.cs @@ -15,8 +15,8 @@ namespace NzbDrone.Host { public static class Bootstrap { - private static IContainer _container; private static readonly Logger Logger = NzbDroneLogger.GetLogger(typeof(Bootstrap)); + private static IContainer _container; public static void Start(StartupContext startupContext, IUserAlert userAlert, Action<IContainer> startCallback = null) { @@ -44,7 +44,6 @@ public static void Start(StartupContext startupContext, IUserAlert userAlert, Ac { startCallback(_container); } - else { SpinToExit(appMode); @@ -151,6 +150,7 @@ private static bool IsInUtilityMode(ApplicationModes applicationMode) { return true; } + default: { return false; diff --git a/src/NzbDrone.Host/BrowserService.cs b/src/NzbDrone.Host/BrowserService.cs index 7ccf23b59..3766699d2 100644 --- a/src/NzbDrone.Host/BrowserService.cs +++ b/src/NzbDrone.Host/BrowserService.cs @@ -47,4 +47,4 @@ public void LaunchWebUI() } } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Host/IUserAlert.cs b/src/NzbDrone.Host/IUserAlert.cs index 04db62985..3be8f7e63 100644 --- a/src/NzbDrone.Host/IUserAlert.cs +++ b/src/NzbDrone.Host/IUserAlert.cs @@ -4,4 +4,4 @@ public interface IUserAlert { void Alert(string message); } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Host/PlatformValidation.cs b/src/NzbDrone.Host/PlatformValidation.cs index ccd9ef145..affa0e991 100644 --- a/src/NzbDrone.Host/PlatformValidation.cs +++ b/src/NzbDrone.Host/PlatformValidation.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Diagnostics; using System.Reflection; using NLog; @@ -9,9 +9,8 @@ namespace NzbDrone.Host { public static class PlatformValidation { - private static readonly Logger Logger = NzbDroneLogger.GetLogger(typeof(PlatformValidation)); - private const string DOWNLOAD_LINK = "http://www.microsoft.com/en-us/download/details.aspx?id=42643"; + private static readonly Logger Logger = NzbDroneLogger.GetLogger(typeof(PlatformValidation)); public static bool IsValidate(IUserAlert userAlert) { @@ -39,7 +38,6 @@ public static bool IsValidate(IUserAlert userAlert) return true; } - private static bool IsAssemblyAvailable(string assemblyString) { try @@ -52,7 +50,6 @@ private static bool IsAssemblyAvailable(string assemblyString) Logger.Warn(e, "Couldn't load {0}", assemblyString); return false; } - } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Host/Router.cs b/src/NzbDrone.Host/Router.cs index fd7563617..09fd7fca5 100644 --- a/src/NzbDrone.Host/Router.cs +++ b/src/NzbDrone.Host/Router.cs @@ -58,6 +58,7 @@ public void Route(ApplicationModes applicationModes) _nzbDroneConsoleFactory.Start(); break; } + case ApplicationModes.InstallService: { _logger.Debug("Install Service selected"); @@ -75,8 +76,10 @@ public void Route(ApplicationModes applicationModes) // Ensures that there isn't an instance of Sonarr already running that the service account cannot stop. _processProvider.SpawnNewProcess("sc.exe", $"start {ServiceProvider.SERVICE_NAME}", null, true); } + break; } + case ApplicationModes.UninstallService: { _logger.Debug("Uninstall Service selected"); @@ -91,6 +94,7 @@ public void Route(ApplicationModes applicationModes) break; } + case ApplicationModes.RegisterUrl: { _logger.Debug("Regiser URL selected"); @@ -98,6 +102,7 @@ public void Route(ApplicationModes applicationModes) break; } + default: { _consoleService.PrintHelp(); diff --git a/src/NzbDrone.Host/SpinService.cs b/src/NzbDrone.Host/SpinService.cs index 04f3d4e98..aaa8b9ec5 100644 --- a/src/NzbDrone.Host/SpinService.cs +++ b/src/NzbDrone.Host/SpinService.cs @@ -65,7 +65,7 @@ public void Spin() path = Path.GetDirectoryName(path); } } - + _processProvider.SpawnNewProcess(path, restartArgs); } } diff --git a/src/NzbDrone.Host/TerminateApplicationException.cs b/src/NzbDrone.Host/TerminateApplicationException.cs index 734fb65d2..cbcc0ceb2 100644 --- a/src/NzbDrone.Host/TerminateApplicationException.cs +++ b/src/NzbDrone.Host/TerminateApplicationException.cs @@ -9,4 +9,4 @@ public TerminateApplicationException(string reason) { } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Integration.Test/ApiTests/CalendarFixture.cs b/src/NzbDrone.Integration.Test/ApiTests/CalendarFixture.cs index bc05c025d..47762b9aa 100644 --- a/src/NzbDrone.Integration.Test/ApiTests/CalendarFixture.cs +++ b/src/NzbDrone.Integration.Test/ApiTests/CalendarFixture.cs @@ -1,10 +1,10 @@ -using FluentAssertions; -using NUnit.Framework; -using Sonarr.Api.V3.Episodes; -using NzbDrone.Integration.Test.Client; -using System; +using System; using System.Collections.Generic; using System.Linq; +using FluentAssertions; +using NUnit.Framework; +using NzbDrone.Integration.Test.Client; +using Sonarr.Api.V3.Episodes; namespace NzbDrone.Integration.Test.ApiTests { diff --git a/src/NzbDrone.Integration.Test/ApiTests/DiskSpaceFixture.cs b/src/NzbDrone.Integration.Test/ApiTests/DiskSpaceFixture.cs index a16a2100f..468970ece 100644 --- a/src/NzbDrone.Integration.Test/ApiTests/DiskSpaceFixture.cs +++ b/src/NzbDrone.Integration.Test/ApiTests/DiskSpaceFixture.cs @@ -1,8 +1,8 @@ using System.Linq; using FluentAssertions; using NUnit.Framework; -using Sonarr.Api.V3.DiskSpace; using NzbDrone.Integration.Test.Client; +using Sonarr.Api.V3.DiskSpace; namespace NzbDrone.Integration.Test.ApiTests { diff --git a/src/NzbDrone.Integration.Test/ApiTests/DownloadClientFixture.cs b/src/NzbDrone.Integration.Test/ApiTests/DownloadClientFixture.cs index 302eb780a..e4f018ad7 100644 --- a/src/NzbDrone.Integration.Test/ApiTests/DownloadClientFixture.cs +++ b/src/NzbDrone.Integration.Test/ApiTests/DownloadClientFixture.cs @@ -7,8 +7,8 @@ namespace NzbDrone.Integration.Test.ApiTests [TestFixture] public class DownloadClientFixture : IntegrationTest { - - [Test, Order(0)] + [Test] + [Order(0)] public void add_downloadclient_without_name_should_return_badrequest() { EnsureNoDownloadClient(); @@ -22,7 +22,8 @@ public void add_downloadclient_without_name_should_return_badrequest() DownloadClients.InvalidPost(schema); } - [Test, Order(0)] + [Test] + [Order(0)] public void add_downloadclient_without_nzbfolder_should_return_badrequest() { EnsureNoDownloadClient(); @@ -36,7 +37,8 @@ public void add_downloadclient_without_nzbfolder_should_return_badrequest() DownloadClients.InvalidPost(schema); } - [Test, Order(0)] + [Test] + [Order(0)] public void add_downloadclient_without_watchfolder_should_return_badrequest() { EnsureNoDownloadClient(); @@ -50,7 +52,8 @@ public void add_downloadclient_without_watchfolder_should_return_badrequest() DownloadClients.InvalidPost(schema); } - [Test, Order(1)] + [Test] + [Order(1)] public void add_downloadclient() { EnsureNoDownloadClient(); @@ -67,7 +70,8 @@ public void add_downloadclient() result.Enable.Should().BeTrue(); } - [Test, Order(2)] + [Test] + [Order(2)] public void get_all_downloadclients() { EnsureDownloadClient(); @@ -77,7 +81,8 @@ public void get_all_downloadclients() clients.Should().NotBeNullOrEmpty(); } - [Test, Order(2)] + [Test] + [Order(2)] public void get_downloadclient_by_id() { var client = EnsureDownloadClient(); @@ -93,7 +98,8 @@ public void get_downloadclient_by_unknown_id_should_return_404() var result = DownloadClients.InvalidGet(1000000); } - [Test, Order(3)] + [Test] + [Order(3)] public void update_downloadclient() { EnsureNoDownloadClient(); @@ -105,7 +111,8 @@ public void update_downloadclient() result.Should().NotBeNull(); } - [Test, Order(4)] + [Test] + [Order(4)] public void delete_downloadclient() { var client = EnsureDownloadClient(); diff --git a/src/NzbDrone.Integration.Test/ApiTests/EpisodeFixture.cs b/src/NzbDrone.Integration.Test/ApiTests/EpisodeFixture.cs index c4d8c1780..2cb4e0a31 100644 --- a/src/NzbDrone.Integration.Test/ApiTests/EpisodeFixture.cs +++ b/src/NzbDrone.Integration.Test/ApiTests/EpisodeFixture.cs @@ -1,21 +1,21 @@ -using System.Threading; +using System.Linq; +using System.Threading; using FluentAssertions; using NUnit.Framework; -using Sonarr.Api.V3.Series; -using System.Linq; using NzbDrone.Test.Common; +using Sonarr.Api.V3.Series; namespace NzbDrone.Integration.Test.ApiTests { [TestFixture] public class EpisodeFixture : IntegrationTest { - private SeriesResource series; + private SeriesResource _series; [SetUp] public void Setup() { - series = GivenSeriesWithEpisodes(); + _series = GivenSeriesWithEpisodes(); } private SeriesResource GivenSeriesWithEpisodes() @@ -36,13 +36,13 @@ private SeriesResource GivenSeriesWithEpisodes() [Test] public void should_be_able_to_get_all_episodes_in_series() { - Episodes.GetEpisodesInSeries(series.Id).Count.Should().BeGreaterThan(0); + Episodes.GetEpisodesInSeries(_series.Id).Count.Should().BeGreaterThan(0); } [Test] public void should_be_able_to_get_a_single_episode() { - var episodes = Episodes.GetEpisodesInSeries(series.Id); + var episodes = Episodes.GetEpisodesInSeries(_series.Id); Episodes.Get(episodes.First().Id).Should().NotBeNull(); } @@ -50,18 +50,17 @@ public void should_be_able_to_get_a_single_episode() [Test] public void should_be_able_to_set_monitor_status() { - var episodes = Episodes.GetEpisodesInSeries(series.Id); + var episodes = Episodes.GetEpisodesInSeries(_series.Id); var updatedEpisode = episodes.First(); updatedEpisode.Monitored = false; Episodes.Put(updatedEpisode).Monitored.Should().BeFalse(); } - [TearDown] public void TearDown() { - Series.Delete(series.Id); + Series.Delete(_series.Id); Thread.Sleep(2000); } } diff --git a/src/NzbDrone.Integration.Test/ApiTests/FileSystemFixture.cs b/src/NzbDrone.Integration.Test/ApiTests/FileSystemFixture.cs index 4d4c49821..d54dfa286 100644 --- a/src/NzbDrone.Integration.Test/ApiTests/FileSystemFixture.cs +++ b/src/NzbDrone.Integration.Test/ApiTests/FileSystemFixture.cs @@ -1,13 +1,13 @@ -using FluentAssertions; -using NUnit.Framework; +using System.Collections.Generic; +using System.IO; using System.Linq; +using System.Net; +using System.Reflection; +using FluentAssertions; +using NUnit.Framework; +using NzbDrone.Common.Disk; using NzbDrone.Integration.Test.Client; using RestSharp; -using System.Net; -using NzbDrone.Common.Disk; -using System.Reflection; -using System.IO; -using System.Collections.Generic; namespace NzbDrone.Integration.Test.ApiTests { @@ -15,7 +15,7 @@ namespace NzbDrone.Integration.Test.ApiTests public class FileSystemFixture : IntegrationTest { public ClientBase FileSystem; - + private string _file; private string _folder; @@ -32,7 +32,7 @@ public void SetUp() _file = Assembly.GetExecutingAssembly().Location; _folder = Path.GetDirectoryName(_file) + Path.DirectorySeparatorChar; } - + [Test] public void get_filesystem_content_excluding_files() { diff --git a/src/NzbDrone.Integration.Test/ApiTests/HistoryFixture.cs b/src/NzbDrone.Integration.Test/ApiTests/HistoryFixture.cs index 2a6faf9d1..820ef5900 100644 --- a/src/NzbDrone.Integration.Test/ApiTests/HistoryFixture.cs +++ b/src/NzbDrone.Integration.Test/ApiTests/HistoryFixture.cs @@ -17,4 +17,4 @@ public void history_should_be_empty() history.Records.Should().BeEmpty(); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Integration.Test/ApiTests/IndexerFixture.cs b/src/NzbDrone.Integration.Test/ApiTests/IndexerFixture.cs index 2a17e37ec..9d56d68f0 100644 --- a/src/NzbDrone.Integration.Test/ApiTests/IndexerFixture.cs +++ b/src/NzbDrone.Integration.Test/ApiTests/IndexerFixture.cs @@ -2,8 +2,8 @@ using FluentAssertions; using Newtonsoft.Json.Linq; using NUnit.Framework; -using Sonarr.Api.V3.Indexers; using NzbDrone.Core.ThingiProvider; +using Sonarr.Api.V3.Indexers; using Sonarr.Http.ClientSchema; namespace NzbDrone.Integration.Test.ApiTests @@ -47,7 +47,7 @@ public void v2_categories_should_be_array() var schema = GetNewznabSchemav2(); var categoriesField = GetCategoriesField(schema); - + categoriesField.Value.Should().BeOfType<JArray>(); } diff --git a/src/NzbDrone.Integration.Test/ApiTests/NamingConfigFixture.cs b/src/NzbDrone.Integration.Test/ApiTests/NamingConfigFixture.cs index 3dcfa5c83..3d4578e0a 100644 --- a/src/NzbDrone.Integration.Test/ApiTests/NamingConfigFixture.cs +++ b/src/NzbDrone.Integration.Test/ApiTests/NamingConfigFixture.cs @@ -6,7 +6,6 @@ namespace NzbDrone.Integration.Test.ApiTests [TestFixture] public class NamingConfigFixture : IntegrationTest { - [Test] public void should_be_able_to_get() { @@ -124,4 +123,4 @@ public void should_get_bad_request_if_series_folder_format_does_not_contain_seri errors.Should().NotBeNull(); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Integration.Test/ApiTests/NotificationFixture.cs b/src/NzbDrone.Integration.Test/ApiTests/NotificationFixture.cs index 85ba510ff..28894e732 100644 --- a/src/NzbDrone.Integration.Test/ApiTests/NotificationFixture.cs +++ b/src/NzbDrone.Integration.Test/ApiTests/NotificationFixture.cs @@ -3,7 +3,6 @@ using FluentAssertions; using NUnit.Framework; - namespace NzbDrone.Integration.Test.ApiTests { [TestFixture] diff --git a/src/NzbDrone.Integration.Test/ApiTests/ReleaseFixture.cs b/src/NzbDrone.Integration.Test/ApiTests/ReleaseFixture.cs index fdcbe3dd6..9984be847 100644 --- a/src/NzbDrone.Integration.Test/ApiTests/ReleaseFixture.cs +++ b/src/NzbDrone.Integration.Test/ApiTests/ReleaseFixture.cs @@ -1,8 +1,8 @@ -using FluentAssertions; +using System.Linq; +using System.Net; +using FluentAssertions; using NUnit.Framework; using Sonarr.Api.V3.Indexers; -using System.Linq; -using System.Net; namespace NzbDrone.Integration.Test.ApiTests { @@ -49,6 +49,7 @@ private bool BeValidRelease(ReleaseResource releaseResource) releaseResource.Title.Should().NotBeNullOrWhiteSpace(); releaseResource.DownloadUrl.Should().NotBeNullOrWhiteSpace(); releaseResource.SeriesTitle.Should().NotBeNullOrWhiteSpace(); + //TODO: uncomment these after moving to restsharp for rss //releaseResource.NzbInfoUrl.Should().NotBeNullOrWhiteSpace(); //releaseResource.Size.Should().BeGreaterThan(0); diff --git a/src/NzbDrone.Integration.Test/ApiTests/RootFolderFixture.cs b/src/NzbDrone.Integration.Test/ApiTests/RootFolderFixture.cs index 5445073b8..ae9956b50 100644 --- a/src/NzbDrone.Integration.Test/ApiTests/RootFolderFixture.cs +++ b/src/NzbDrone.Integration.Test/ApiTests/RootFolderFixture.cs @@ -32,12 +32,10 @@ public void should_add_and_delete_root_folders() RootFolders.All().Should().OnlyContain(c => c.Id == postResponse.Id); - RootFolders.Delete(postResponse.Id); RootFolders.All().Should().BeEmpty(); - SignalRMessages.Should().Contain(c => c.Name == "rootfolder"); } @@ -53,4 +51,4 @@ public void invalid_path_should_return_bad_request() postResponse.Should().NotBeNull(); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Integration.Test/ApiTests/SeriesEditorFixture.cs b/src/NzbDrone.Integration.Test/ApiTests/SeriesEditorFixture.cs index 7854eac92..5e9c2ab91 100644 --- a/src/NzbDrone.Integration.Test/ApiTests/SeriesEditorFixture.cs +++ b/src/NzbDrone.Integration.Test/ApiTests/SeriesEditorFixture.cs @@ -1,6 +1,6 @@ -using FluentAssertions; +using System.Linq; +using FluentAssertions; using NUnit.Framework; -using System.Linq; using NzbDrone.Test.Common; namespace NzbDrone.Integration.Test.ApiTests @@ -42,4 +42,4 @@ public void should_be_able_to_update_multiple_series() result.TrueForAll(s => s.QualityProfileId == 2).Should().BeTrue(); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Integration.Test/ApiTests/SeriesFixture.cs b/src/NzbDrone.Integration.Test/ApiTests/SeriesFixture.cs index 9a67e3a11..02c8acb24 100644 --- a/src/NzbDrone.Integration.Test/ApiTests/SeriesFixture.cs +++ b/src/NzbDrone.Integration.Test/ApiTests/SeriesFixture.cs @@ -1,15 +1,16 @@ -using FluentAssertions; -using NUnit.Framework; -using System.Linq; -using System.IO; using System.Collections.Generic; +using System.IO; +using System.Linq; +using FluentAssertions; +using NUnit.Framework; namespace NzbDrone.Integration.Test.ApiTests { [TestFixture] public class SeriesFixture : IntegrationTest { - [Test, Order(0)] + [Test] + [Order(0)] public void add_series_with_tags_should_store_them() { EnsureNoSeries(266189, "The Blacklist"); @@ -29,7 +30,8 @@ public void add_series_with_tags_should_store_them() result.Tags.Should().Equal(tag.Id); } - [Test, Order(0)] + [Test] + [Order(0)] public void add_series_without_profileid_should_return_badrequest() { EnsureNoSeries(266189, "The Blacklist"); @@ -41,7 +43,8 @@ public void add_series_without_profileid_should_return_badrequest() Series.InvalidPost(series); } - [Test, Order(0)] + [Test] + [Order(0)] public void add_series_without_path_should_return_badrequest() { EnsureNoSeries(266189, "The Blacklist"); @@ -53,7 +56,8 @@ public void add_series_without_path_should_return_badrequest() Series.InvalidPost(series); } - [Test, Order(1)] + [Test] + [Order(1)] public void add_series() { EnsureNoSeries(266189, "The Blacklist"); @@ -73,8 +77,8 @@ public void add_series() result.Path.Should().Be(Path.Combine(SeriesRootFolder, series.Title)); } - - [Test, Order(2)] + [Test] + [Order(2)] public void get_all_series() { EnsureSeries(266189, "The Blacklist"); @@ -85,7 +89,8 @@ public void get_all_series() Series.All().Should().Contain(v => v.TvdbId == 266189); } - [Test, Order(2)] + [Test] + [Order(2)] public void get_series_by_id() { var series = EnsureSeries(266189, "The Blacklist"); @@ -101,7 +106,8 @@ public void get_series_by_unknown_id_should_return_404() var result = Series.InvalidGet(1000000); } - [Test, Order(2)] + [Test] + [Order(2)] public void update_series_profile_id() { var series = EnsureSeries(266189, "The Blacklist"); @@ -119,7 +125,8 @@ public void update_series_profile_id() Series.Get(series.Id).QualityProfileId.Should().Be(profileId); } - [Test, Order(3)] + [Test] + [Order(3)] public void update_series_monitored() { var series = EnsureSeries(266189, "The Blacklist", false); @@ -139,7 +146,8 @@ public void update_series_monitored() result.Seasons.First().Monitored.Should().BeTrue(); } - [Test, Order(3)] + [Test] + [Order(3)] public void update_series_tags() { var series = EnsureSeries(266189, "The Blacklist"); @@ -161,7 +169,8 @@ public void update_series_tags() } } - [Test, Order(4)] + [Test] + [Order(4)] public void delete_series() { var series = EnsureSeries(266189, "The Blacklist"); @@ -173,4 +182,4 @@ public void delete_series() Series.All().Should().NotContain(v => v.TvdbId == 266189); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Integration.Test/ApiTests/SeriesLookupFixture.cs b/src/NzbDrone.Integration.Test/ApiTests/SeriesLookupFixture.cs index f45169551..502376b0f 100644 --- a/src/NzbDrone.Integration.Test/ApiTests/SeriesLookupFixture.cs +++ b/src/NzbDrone.Integration.Test/ApiTests/SeriesLookupFixture.cs @@ -34,4 +34,4 @@ public void lookup_random_series_using_asterix() series.Should().NotBeEmpty(); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Integration.Test/ApiTests/WantedTests/CutoffUnmetFixture.cs b/src/NzbDrone.Integration.Test/ApiTests/WantedTests/CutoffUnmetFixture.cs index 2270faa35..1a75068e4 100644 --- a/src/NzbDrone.Integration.Test/ApiTests/WantedTests/CutoffUnmetFixture.cs +++ b/src/NzbDrone.Integration.Test/ApiTests/WantedTests/CutoffUnmetFixture.cs @@ -8,7 +8,8 @@ namespace NzbDrone.Integration.Test.ApiTests.WantedTests [TestFixture] public class CutoffUnmetFixture : IntegrationTest { - [Test, Order(1)] + [Test] + [Order(1)] public void cutoff_should_have_monitored_items() { EnsureProfileCutoff(1, Quality.HDTV720p, true); @@ -20,7 +21,8 @@ public void cutoff_should_have_monitored_items() result.Records.Should().NotBeEmpty(); } - [Test, Order(1)] + [Test] + [Order(1)] public void cutoff_should_not_have_unmonitored_items() { EnsureProfileCutoff(1, Quality.HDTV720p, true); @@ -32,7 +34,8 @@ public void cutoff_should_not_have_unmonitored_items() result.Records.Should().BeEmpty(); } - [Test, Order(1)] + [Test] + [Order(1)] public void cutoff_should_have_series() { EnsureProfileCutoff(1, Quality.HDTV720p, true); @@ -45,7 +48,8 @@ public void cutoff_should_have_series() result.Records.First().Series.Title.Should().Be("The Blacklist"); } - [Test, Order(2)] + [Test] + [Order(2)] public void cutoff_should_have_unmonitored_items() { EnsureProfileCutoff(1, Quality.HDTV720p, true); diff --git a/src/NzbDrone.Integration.Test/ApiTests/WantedTests/MissingFixture.cs b/src/NzbDrone.Integration.Test/ApiTests/WantedTests/MissingFixture.cs index 9a75b5357..a91b954f7 100644 --- a/src/NzbDrone.Integration.Test/ApiTests/WantedTests/MissingFixture.cs +++ b/src/NzbDrone.Integration.Test/ApiTests/WantedTests/MissingFixture.cs @@ -7,7 +7,8 @@ namespace NzbDrone.Integration.Test.ApiTests.WantedTests [TestFixture] public class MissingFixture : IntegrationTest { - [Test, Order(0)] + [Test] + [Order(0)] public void missing_should_be_empty() { EnsureNoSeries(266189, "The Blacklist"); @@ -17,7 +18,8 @@ public void missing_should_be_empty() result.Records.Should().BeEmpty(); } - [Test, Order(1)] + [Test] + [Order(1)] public void missing_should_have_monitored_items() { EnsureSeries(266189, "The Blacklist", true); @@ -27,7 +29,8 @@ public void missing_should_have_monitored_items() result.Records.Should().NotBeEmpty(); } - [Test, Order(1)] + [Test] + [Order(1)] public void missing_should_have_series() { EnsureSeries(266189, "The Blacklist", true); @@ -38,7 +41,8 @@ public void missing_should_have_series() result.Records.First().Series.Title.Should().Be("The Blacklist"); } - [Test, Order(1)] + [Test] + [Order(1)] public void missing_should_not_have_unmonitored_items() { EnsureSeries(266189, "The Blacklist", false); @@ -48,7 +52,8 @@ public void missing_should_not_have_unmonitored_items() result.Records.Should().BeEmpty(); } - [Test, Order(2)] + [Test] + [Order(2)] public void missing_should_have_unmonitored_items() { EnsureSeries(266189, "The Blacklist", false); diff --git a/src/NzbDrone.Integration.Test/Client/ClientBase.cs b/src/NzbDrone.Integration.Test/Client/ClientBase.cs index 030fbdb85..9a7313fde 100644 --- a/src/NzbDrone.Integration.Test/Client/ClientBase.cs +++ b/src/NzbDrone.Integration.Test/Client/ClientBase.cs @@ -3,10 +3,10 @@ using System.Net; using FluentAssertions; using NLog; -using Sonarr.Http.REST; using NzbDrone.Common.Serializer; using RestSharp; using Sonarr.Http; +using Sonarr.Http.REST; namespace NzbDrone.Integration.Test.Client { @@ -84,7 +84,6 @@ public class ClientBase<TResource> : ClientBase public ClientBase(IRestClient restClient, string apiKey, string resource = null) : base(restClient, apiKey, resource ?? new TResource().ResourceName) { - } public List<TResource> All(Dictionary<string, object> queryParams = null) diff --git a/src/NzbDrone.Integration.Test/Client/CommandClient.cs b/src/NzbDrone.Integration.Test/Client/CommandClient.cs index dd49231cb..c3bc6476f 100644 --- a/src/NzbDrone.Integration.Test/Client/CommandClient.cs +++ b/src/NzbDrone.Integration.Test/Client/CommandClient.cs @@ -5,8 +5,8 @@ using Newtonsoft.Json; using NUnit.Framework; using NzbDrone.Core.Messaging.Commands; -using Sonarr.Http.REST; using RestSharp; +using Sonarr.Http.REST; namespace NzbDrone.Integration.Test.Client { diff --git a/src/NzbDrone.Integration.Test/Client/DownloadClientClient.cs b/src/NzbDrone.Integration.Test/Client/DownloadClientClient.cs index 9ed93ceef..40a5afab7 100644 --- a/src/NzbDrone.Integration.Test/Client/DownloadClientClient.cs +++ b/src/NzbDrone.Integration.Test/Client/DownloadClientClient.cs @@ -1,6 +1,6 @@ using System.Collections.Generic; -using Sonarr.Api.V3.DownloadClient; using RestSharp; +using Sonarr.Api.V3.DownloadClient; namespace NzbDrone.Integration.Test.Client { @@ -17,4 +17,4 @@ public List<DownloadClientResource> Schema() return Get<List<DownloadClientResource>>(request); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Integration.Test/Client/EpisodeClient.cs b/src/NzbDrone.Integration.Test/Client/EpisodeClient.cs index a015b0758..da1e56bbb 100644 --- a/src/NzbDrone.Integration.Test/Client/EpisodeClient.cs +++ b/src/NzbDrone.Integration.Test/Client/EpisodeClient.cs @@ -1,6 +1,6 @@ using System.Collections.Generic; -using Sonarr.Api.V3.Episodes; using RestSharp; +using Sonarr.Api.V3.Episodes; namespace NzbDrone.Integration.Test.Client { diff --git a/src/NzbDrone.Integration.Test/Client/IndexerClient.cs b/src/NzbDrone.Integration.Test/Client/IndexerClient.cs index a627db763..60dab9ab0 100644 --- a/src/NzbDrone.Integration.Test/Client/IndexerClient.cs +++ b/src/NzbDrone.Integration.Test/Client/IndexerClient.cs @@ -1,6 +1,6 @@ using System.Collections.Generic; -using Sonarr.Api.V3.Indexers; using RestSharp; +using Sonarr.Api.V3.Indexers; namespace NzbDrone.Integration.Test.Client { @@ -17,4 +17,4 @@ public List<IndexerResource> Schema() return Get<List<IndexerResource>>(request); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Integration.Test/Client/LogsClient.cs b/src/NzbDrone.Integration.Test/Client/LogsClient.cs index 468cce5d4..f22961c86 100644 --- a/src/NzbDrone.Integration.Test/Client/LogsClient.cs +++ b/src/NzbDrone.Integration.Test/Client/LogsClient.cs @@ -34,6 +34,7 @@ public string[] GetLogFileLines(string filename) _logger.Error(ex, "Failed to get log lines"); throw; } + _logger.Info(ex, "Failed to get log lines, attempt {0}/{1}", attempt, attempts); Thread.Sleep(10); attempt++; @@ -41,4 +42,4 @@ public string[] GetLogFileLines(string filename) } } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Integration.Test/Client/NotificationClient.cs b/src/NzbDrone.Integration.Test/Client/NotificationClient.cs index f97a7b48a..d30c48c62 100644 --- a/src/NzbDrone.Integration.Test/Client/NotificationClient.cs +++ b/src/NzbDrone.Integration.Test/Client/NotificationClient.cs @@ -1,6 +1,6 @@ using System.Collections.Generic; -using Sonarr.Api.V3.Notifications; using RestSharp; +using Sonarr.Api.V3.Notifications; namespace NzbDrone.Integration.Test.Client { @@ -17,4 +17,4 @@ public List<NotificationResource> Schema() return Get<List<NotificationResource>>(request); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Integration.Test/Client/ReleaseClient.cs b/src/NzbDrone.Integration.Test/Client/ReleaseClient.cs index 2675953b6..2a055a226 100644 --- a/src/NzbDrone.Integration.Test/Client/ReleaseClient.cs +++ b/src/NzbDrone.Integration.Test/Client/ReleaseClient.cs @@ -1,5 +1,5 @@ -using Sonarr.Api.V3.Indexers; -using RestSharp; +using RestSharp; +using Sonarr.Api.V3.Indexers; namespace NzbDrone.Integration.Test.Client { diff --git a/src/NzbDrone.Integration.Test/Client/ReleasePushClient.cs b/src/NzbDrone.Integration.Test/Client/ReleasePushClient.cs index 5245a5d3f..ed347a416 100644 --- a/src/NzbDrone.Integration.Test/Client/ReleasePushClient.cs +++ b/src/NzbDrone.Integration.Test/Client/ReleasePushClient.cs @@ -1,5 +1,5 @@ -using Sonarr.Api.V3.Indexers; -using RestSharp; +using RestSharp; +using Sonarr.Api.V3.Indexers; namespace NzbDrone.Integration.Test.Client { diff --git a/src/NzbDrone.Integration.Test/Client/SeriesClient.cs b/src/NzbDrone.Integration.Test/Client/SeriesClient.cs index 53355253f..2d62905b6 100644 --- a/src/NzbDrone.Integration.Test/Client/SeriesClient.cs +++ b/src/NzbDrone.Integration.Test/Client/SeriesClient.cs @@ -1,7 +1,7 @@ using System.Collections.Generic; using System.Net; -using Sonarr.Api.V3.Series; using RestSharp; +using Sonarr.Api.V3.Series; namespace NzbDrone.Integration.Test.Client { @@ -31,7 +31,6 @@ public SeriesResource Get(string slug, HttpStatusCode statusCode = HttpStatusCod var request = BuildRequest(slug); return Get<SeriesResource>(request, statusCode); } - } public class SystemInfoClient : ClientBase<SeriesResource> diff --git a/src/NzbDrone.Integration.Test/CorsFixture.cs b/src/NzbDrone.Integration.Test/CorsFixture.cs index f4dedc839..252996dc1 100644 --- a/src/NzbDrone.Integration.Test/CorsFixture.cs +++ b/src/NzbDrone.Integration.Test/CorsFixture.cs @@ -1,7 +1,7 @@ using FluentAssertions; using NUnit.Framework; -using Sonarr.Http.Extensions; using RestSharp; +using Sonarr.Http.Extensions; namespace NzbDrone.Integration.Test { diff --git a/src/NzbDrone.Integration.Test/GenericApiFixture.cs b/src/NzbDrone.Integration.Test/GenericApiFixture.cs index 1063275c9..ba02a515c 100644 --- a/src/NzbDrone.Integration.Test/GenericApiFixture.cs +++ b/src/NzbDrone.Integration.Test/GenericApiFixture.cs @@ -16,7 +16,6 @@ public class GenericApiFixture : IntegrationTest [TestCase("")] public void should_get_json_with_accept_header(string header) { - var request = new RestRequest("system/status") { RequestFormat = DataFormat.None @@ -34,7 +33,6 @@ public void should_get_json_with_accept_header(string header) [TestCase("application/junk")] public void should_get_unacceptable_with_accept_header(string header) { - var request = new RestRequest("system/status") { RequestFormat = DataFormat.None diff --git a/src/NzbDrone.Integration.Test/IndexHtmlFixture.cs b/src/NzbDrone.Integration.Test/IndexHtmlFixture.cs index b931620ca..8bd1a26fc 100644 --- a/src/NzbDrone.Integration.Test/IndexHtmlFixture.cs +++ b/src/NzbDrone.Integration.Test/IndexHtmlFixture.cs @@ -13,6 +13,5 @@ public void should_get_index_html() var text = new WebClient().DownloadString(RootUrl); text.Should().NotBeNullOrWhiteSpace(); } - } } diff --git a/src/NzbDrone.Integration.Test/IntegrationTestBase.cs b/src/NzbDrone.Integration.Test/IntegrationTestBase.cs index e8007515e..2c4e2f06a 100644 --- a/src/NzbDrone.Integration.Test/IntegrationTestBase.cs +++ b/src/NzbDrone.Integration.Test/IntegrationTestBase.cs @@ -11,6 +11,15 @@ using NLog.Config; using NLog.Targets; using NUnit.Framework; +using NzbDrone.Common.EnvironmentInfo; +using NzbDrone.Common.Processes; +using NzbDrone.Common.Serializer; +using NzbDrone.Core.Qualities; +using NzbDrone.Core.Tv.Commands; +using NzbDrone.Integration.Test.Client; +using NzbDrone.SignalR; +using NzbDrone.Test.Common.Categories; +using RestSharp; using Sonarr.Api.V3.Blocklist; using Sonarr.Api.V3.Commands; using Sonarr.Api.V3.Config; @@ -21,17 +30,8 @@ using Sonarr.Api.V3.Profiles.Quality; using Sonarr.Api.V3.RootFolders; using Sonarr.Api.V3.Series; -using Sonarr.Api.V3.Tags; -using NzbDrone.Common.EnvironmentInfo; -using NzbDrone.Common.Serializer; -using NzbDrone.Core.Qualities; -using NzbDrone.Core.Tv.Commands; -using NzbDrone.Integration.Test.Client; -using NzbDrone.SignalR; -using NzbDrone.Test.Common.Categories; -using RestSharp; -using NzbDrone.Common.Processes; using Sonarr.Api.V3.System.Tasks; +using Sonarr.Api.V3.Tags; namespace NzbDrone.Integration.Test { @@ -39,7 +39,6 @@ namespace NzbDrone.Integration.Test public abstract class IntegrationTestBase { protected RestClient RestClient { get; private set; } - protected RestClient RestClientv3 { get; private set; } public ClientBase<BlocklistResource> Blocklist; public CommandClient Commands; @@ -310,7 +309,7 @@ public EpisodeFileResource EnsureEpisodeFile(SeriesResource series, int season, Directory.CreateDirectory(Path.GetDirectoryName(path)); File.WriteAllText(path, "Fake Episode"); - Commands.PostAndWait(new RefreshSeriesCommand( series.Id )); + Commands.PostAndWait(new RefreshSeriesCommand(series.Id)); Commands.WaitAll(); diff --git a/src/NzbDrone.Mono.Test/DiskProviderTests/DiskProviderFixture.cs b/src/NzbDrone.Mono.Test/DiskProviderTests/DiskProviderFixture.cs index 017de3bc7..2b7467087 100644 --- a/src/NzbDrone.Mono.Test/DiskProviderTests/DiskProviderFixture.cs +++ b/src/NzbDrone.Mono.Test/DiskProviderTests/DiskProviderFixture.cs @@ -39,6 +39,7 @@ public void MonoDiskProviderFixtureTearDown() { Syscall.chmod(_tempPath, FilePermissions.S_IRUSR | FilePermissions.S_IWUSR); } + _tempPath = null; } } @@ -70,7 +71,6 @@ protected void SetWritePermissionsInternal(string path, bool writable, bool setg mode &= ~(FilePermissions.S_IWUSR | FilePermissions.S_IWGRP | FilePermissions.S_IWOTH); } - if (setgid) { mode |= FilePermissions.S_ISGID; diff --git a/src/NzbDrone.Mono.Test/EnvironmentInfo/VersionAdapters/MacOsVersionAdapterFixture.cs b/src/NzbDrone.Mono.Test/EnvironmentInfo/VersionAdapters/MacOsVersionAdapterFixture.cs index 460df24bc..b650422cd 100644 --- a/src/NzbDrone.Mono.Test/EnvironmentInfo/VersionAdapters/MacOsVersionAdapterFixture.cs +++ b/src/NzbDrone.Mono.Test/EnvironmentInfo/VersionAdapters/MacOsVersionAdapterFixture.cs @@ -38,7 +38,6 @@ public void should_get_version_info(string versionString) versionName.FullName.Should().Be("macOS " + versionString); } - [TestCase] public void should_detect_server() { diff --git a/src/NzbDrone.Mono.Test/EnvironmentInfo/VersionAdapters/ReleaseFileVersionAdapterFixture.cs b/src/NzbDrone.Mono.Test/EnvironmentInfo/VersionAdapters/ReleaseFileVersionAdapterFixture.cs index e52ebafec..b257e5713 100644 --- a/src/NzbDrone.Mono.Test/EnvironmentInfo/VersionAdapters/ReleaseFileVersionAdapterFixture.cs +++ b/src/NzbDrone.Mono.Test/EnvironmentInfo/VersionAdapters/ReleaseFileVersionAdapterFixture.cs @@ -40,7 +40,6 @@ public void should_return_null_if_etc_doestn_exist() Subject.Read().Should().BeNull(); } - [Test] public void should_return_null_if_release_file_doestn_exist() { @@ -79,7 +78,6 @@ public void should_detect_version() version.Name.Should().Be("ubuntu"); version.Version.Should().Be("14.04"); version.FullName.Should().Be("Ubuntu 14.04.5 LTS"); - } } } diff --git a/src/NzbDrone.Mono/Disk/DiskProvider.cs b/src/NzbDrone.Mono/Disk/DiskProvider.cs index c461deea3..e18332124 100644 --- a/src/NzbDrone.Mono/Disk/DiskProvider.cs +++ b/src/NzbDrone.Mono/Disk/DiskProvider.cs @@ -55,7 +55,6 @@ public override IMount GetMount(string path) public override void InheritFolderPermissions(string filename) { - } public override void SetEveryonePermissions(string filename) @@ -434,6 +433,7 @@ public override bool TryCreateHardLink(string source, string destination) { _logger.Debug(ex, "Hardlink '{0}' to '{1}' failed.", source, destination); } + return false; } catch (Exception ex) diff --git a/src/NzbDrone.Mono/Disk/SymbolicLinkResolver.cs b/src/NzbDrone.Mono/Disk/SymbolicLinkResolver.cs index 09a932135..b4c712274 100644 --- a/src/NzbDrone.Mono/Disk/SymbolicLinkResolver.cs +++ b/src/NzbDrone.Mono/Disk/SymbolicLinkResolver.cs @@ -76,6 +76,7 @@ private static void GetPathComponents(string path, out string[] components, out dirs[target++] = dirs[i]; } } + components = dirs; lastIndex = target; } @@ -114,6 +115,7 @@ private bool TryFollowFirstSymbolicLink(ref string path) { realPath = string.Concat(realPath, UnixPath.DirectorySeparatorChar, string.Join(UnixPath.DirectorySeparatorChar.ToString(), dirs, i + 1, lastIndex - i - 1)); } + path = realPath; return pathValid; } diff --git a/src/NzbDrone.Mono/EnvironmentInfo/VersionAdapters/IssueFileVersionAdapter.cs b/src/NzbDrone.Mono/EnvironmentInfo/VersionAdapters/IssueFileVersionAdapter.cs index 321a8c12e..2965f5a1a 100644 --- a/src/NzbDrone.Mono/EnvironmentInfo/VersionAdapters/IssueFileVersionAdapter.cs +++ b/src/NzbDrone.Mono/EnvironmentInfo/VersionAdapters/IssueFileVersionAdapter.cs @@ -30,7 +30,6 @@ public OsVersionModel Read() var fileContent = _diskProvider.ReadAllText(issueFile); - // Ubuntu 14.04.5 LTS \n \l // Ubuntu 16.04.1 LTS \n \l diff --git a/src/NzbDrone.Mono/EnvironmentInfo/VersionAdapters/MacOsVersionAdapter.cs b/src/NzbDrone.Mono/EnvironmentInfo/VersionAdapters/MacOsVersionAdapter.cs index 3a7e77fd8..59f743da2 100644 --- a/src/NzbDrone.Mono/EnvironmentInfo/VersionAdapters/MacOsVersionAdapter.cs +++ b/src/NzbDrone.Mono/EnvironmentInfo/VersionAdapters/MacOsVersionAdapter.cs @@ -48,8 +48,6 @@ public OsVersionModel Read() var text = _diskProvider.ReadAllText(versionFile); var match = DarwinVersionRegex.Match(text); - - if (match.Success) { version = match.Groups["version"].Value; diff --git a/src/NzbDrone.Mono/EnvironmentInfo/VersionAdapters/ReleaseFileVersionAdapter.cs b/src/NzbDrone.Mono/EnvironmentInfo/VersionAdapters/ReleaseFileVersionAdapter.cs index 5e50ea3d5..78dcceec6 100644 --- a/src/NzbDrone.Mono/EnvironmentInfo/VersionAdapters/ReleaseFileVersionAdapter.cs +++ b/src/NzbDrone.Mono/EnvironmentInfo/VersionAdapters/ReleaseFileVersionAdapter.cs @@ -71,7 +71,6 @@ public OsVersionModel Read() } return new OsVersionModel(name, version, fullName); - } public bool Enabled => OsInfo.IsLinux; diff --git a/src/NzbDrone.SignalR/SignalRMessage.cs b/src/NzbDrone.SignalR/SignalRMessage.cs index 17a7d4187..548d988a9 100644 --- a/src/NzbDrone.SignalR/SignalRMessage.cs +++ b/src/NzbDrone.SignalR/SignalRMessage.cs @@ -11,4 +11,4 @@ public class SignalRMessage [JsonIgnore] public ModelAction Action { get; set; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Test.Common/AutoMoq/AutoMoqer.cs b/src/NzbDrone.Test.Common/AutoMoq/AutoMoqer.cs index 2f3c10e52..6b3a1a102 100644 --- a/src/NzbDrone.Test.Common/AutoMoq/AutoMoqer.cs +++ b/src/NzbDrone.Test.Common/AutoMoq/AutoMoqer.cs @@ -6,12 +6,12 @@ using System.Linq.Expressions; using System.Reflection; using System.Runtime.CompilerServices; -using Unity; using Moq; using Moq.Language.Flow; using NzbDrone.Common.Composition; using NzbDrone.Common.EnvironmentInfo; using NzbDrone.Test.Common.AutoMoq.Unity; +using Unity; using Unity.Resolution; [assembly: InternalsVisibleTo("AutoMoq.Tests")] @@ -35,7 +35,6 @@ public AutoMoqer(MockBehavior defaultBehavior) { DefaultBehavior = defaultBehavior; SetupAutoMoqer(new UnityContainer()); - } public AutoMoqer(IUnityContainer container) @@ -52,12 +51,14 @@ public virtual T Resolve<T>() return result; } - public virtual Mock<T> GetMock<T>() where T : class + public virtual Mock<T> GetMock<T>() + where T : class { return GetMock<T>(DefaultBehavior); } - public virtual Mock<T> GetMock<T>(MockBehavior behavior) where T : class + public virtual Mock<T> GetMock<T>(MockBehavior behavior) + where T : class { ResolveType = null; var type = GetTheMockType<T>(); @@ -79,9 +80,14 @@ public virtual Mock<T> GetMock<T>(MockBehavior behavior) where T : class public virtual void SetMock(Type type, Mock mock) { if (_registeredMocks.ContainsKey(type) == false) + { _registeredMocks.Add(type, mock); + } + if (mock != null) + { _container.RegisterInstance(type, mock.Object); + } } public virtual void SetConstant<T>(T instance) @@ -90,32 +96,38 @@ public virtual void SetConstant<T>(T instance) SetMock(instance.GetType(), null); } - public ISetup<T> Setup<T>(Expression<Action<T>> expression) where T : class + public ISetup<T> Setup<T>(Expression<Action<T>> expression) + where T : class { return GetMock<T>().Setup(expression); } - public ISetup<T, TResult> Setup<T, TResult>(Expression<Func<T, TResult>> expression) where T : class + public ISetup<T, TResult> Setup<T, TResult>(Expression<Func<T, TResult>> expression) + where T : class { return GetMock<T>().Setup(expression); } - public void Verify<T>(Expression<Action<T>> expression) where T : class + public void Verify<T>(Expression<Action<T>> expression) + where T : class { GetMock<T>().Verify(expression); } - public void Verify<T>(Expression<Action<T>> expression, string failMessage) where T : class + public void Verify<T>(Expression<Action<T>> expression, string failMessage) + where T : class { GetMock<T>().Verify(expression, failMessage); } - public void Verify<T>(Expression<Action<T>> expression, Times times) where T : class + public void Verify<T>(Expression<Action<T>> expression, Times times) + where T : class { GetMock<T>().Verify(expression, times); } - public void Verify<T>(Expression<Action<T>> expression, Times times, string failMessage) where T : class + public void Verify<T>(Expression<Action<T>> expression, Times times, string failMessage) + where T : class { GetMock<T>().Verify(expression, times, failMessage); } @@ -125,12 +137,12 @@ public void VerifyAllMocks() foreach (var registeredMock in _registeredMocks) { if (registeredMock.Value is Mock mock) + { mock.VerifyAll(); + } } } - #region private methods - private void SetupAutoMoqer(IUnityContainer container) { _container = container; @@ -149,12 +161,14 @@ private static void AddTheAutoMockingContainerExtensionToTheContainer(IUnityCont return; } - private Mock<T> TheRegisteredMockForThisType<T>(Type type) where T : class + private Mock<T> TheRegisteredMockForThisType<T>(Type type) + where T : class { return (Mock<T>)_registeredMocks.First(x => x.Key == type).Value; } - private void CreateANewMockAndRegisterIt<T>(Type type, MockBehavior behavior) where T : class + private void CreateANewMockAndRegisterIt<T>(Type type, MockBehavior behavior) + where T : class { var mock = new Mock<T>(behavior); _container.RegisterInstance(mock.Object); @@ -166,7 +180,8 @@ private bool GetMockHasNotBeenCalledForThisType(Type type) return _registeredMocks.ContainsKey(type) == false; } - private static Type GetTheMockType<T>() where T : class + private static Type GetTheMockType<T>() + where T : class { return typeof(T); } @@ -187,7 +202,5 @@ private void RegisterPlatformLibrary(IUnityContainer container) Assembly.Load(assemblyName); } - - #endregion } } diff --git a/src/NzbDrone.Test.Common/AutoMoq/Unity/AutoMockingBuilderStrategy.cs b/src/NzbDrone.Test.Common/AutoMoq/Unity/AutoMockingBuilderStrategy.cs index 5fbb18d32..6190ae70d 100644 --- a/src/NzbDrone.Test.Common/AutoMoq/Unity/AutoMockingBuilderStrategy.cs +++ b/src/NzbDrone.Test.Common/AutoMoq/Unity/AutoMockingBuilderStrategy.cs @@ -2,10 +2,10 @@ using System.Collections.Generic; using System.Linq; using System.Reflection; -using Unity; using Moq; -using Unity.Strategies; +using Unity; using Unity.Builder; +using Unity.Strategies; namespace NzbDrone.Test.Common.AutoMoq.Unity { @@ -36,8 +36,6 @@ public override void PreBuildUp(ref BuilderContext context) } } - #region private methods - private bool AMockObjectShouldBeCreatedForThisType(Type type) { var mocker = _container.Resolve<AutoMoqer>(); @@ -77,7 +75,5 @@ private static Type[] EmptyArgumentList() { return new[] { typeof(object[]) }; } - - #endregion } } diff --git a/src/NzbDrone.Test.Common/AutoMoq/Unity/AutoMockingContainerExtension.cs b/src/NzbDrone.Test.Common/AutoMoq/Unity/AutoMockingContainerExtension.cs index b764c929d..5f3b4fb64 100644 --- a/src/NzbDrone.Test.Common/AutoMoq/Unity/AutoMockingContainerExtension.cs +++ b/src/NzbDrone.Test.Common/AutoMoq/Unity/AutoMockingContainerExtension.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using Unity.Builder; using Unity.Extension; @@ -7,7 +7,7 @@ namespace NzbDrone.Test.Common.AutoMoq.Unity { public class AutoMockingContainerExtension : UnityContainerExtension { - private readonly IList<Type> registeredTypes = new List<Type>(); + private readonly IList<Type> _registeredTypes = new List<Type>(); protected override void Initialize() { @@ -15,25 +15,21 @@ protected override void Initialize() SetBuildingStrategyForBuildingUnregisteredTypes(); } - #region private methods - private void SetEventsOnContainerToTrackAllRegisteredTypes() { - Context.Registering += ((sender, e) => RegisterType(e.TypeFrom)); - Context.RegisteringInstance += ((sender, e) => RegisterType(e.RegisteredType)); + Context.Registering += (sender, e) => RegisterType(e.TypeFrom); + Context.RegisteringInstance += (sender, e) => RegisterType(e.RegisteredType); } private void RegisterType(Type typeToRegister) { - registeredTypes.Add(typeToRegister); + _registeredTypes.Add(typeToRegister); } private void SetBuildingStrategyForBuildingUnregisteredTypes() { - var strategy = new AutoMockingBuilderStrategy(registeredTypes, Container); + var strategy = new AutoMockingBuilderStrategy(_registeredTypes, Container); Context.Strategies.Add(strategy, UnityBuildStage.PreCreation); } - - #endregion } } diff --git a/src/NzbDrone.Test.Common/Categories/DiskAccessTestAttribute.cs b/src/NzbDrone.Test.Common/Categories/DiskAccessTestAttribute.cs index faccff30d..d62a0dce0 100644 --- a/src/NzbDrone.Test.Common/Categories/DiskAccessTestAttribute.cs +++ b/src/NzbDrone.Test.Common/Categories/DiskAccessTestAttribute.cs @@ -7,7 +7,6 @@ public class DiskAccessTestAttribute : CategoryAttribute public DiskAccessTestAttribute() : base("DiskAccessTest") { - } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Test.Common/Categories/IntegrationTestAttribute.cs b/src/NzbDrone.Test.Common/Categories/IntegrationTestAttribute.cs index 43d46f0fe..f26c5e84e 100644 --- a/src/NzbDrone.Test.Common/Categories/IntegrationTestAttribute.cs +++ b/src/NzbDrone.Test.Common/Categories/IntegrationTestAttribute.cs @@ -7,7 +7,6 @@ public class IntegrationTestAttribute : CategoryAttribute public IntegrationTestAttribute() : base("IntegrationTest") { - } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Test.Common/Categories/ManualTestAttribute.cs b/src/NzbDrone.Test.Common/Categories/ManualTestAttribute.cs index 37700203b..0dd8fdec3 100644 --- a/src/NzbDrone.Test.Common/Categories/ManualTestAttribute.cs +++ b/src/NzbDrone.Test.Common/Categories/ManualTestAttribute.cs @@ -7,7 +7,6 @@ public class ManualTestAttribute : CategoryAttribute public ManualTestAttribute() : base("ManualTest") { - } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Test.Common/ConcurrencyCounter.cs b/src/NzbDrone.Test.Common/ConcurrencyCounter.cs index 03586ad60..6ee4554db 100644 --- a/src/NzbDrone.Test.Common/ConcurrencyCounter.cs +++ b/src/NzbDrone.Test.Common/ConcurrencyCounter.cs @@ -6,9 +6,9 @@ namespace NzbDrone.Test.Common { public class ConcurrencyCounter { + private readonly object _mutex = new object(); + private readonly Dictionary<int, int> _threads = new Dictionary<int, int>(); private int _items; - readonly object _mutex = new object(); - readonly Dictionary<int, int> _threads = new Dictionary<int, int>(); public int MaxThreads => _threads.Count; @@ -30,7 +30,6 @@ public int Start() int threadId = Thread.CurrentThread.ManagedThreadId; lock (_mutex) { - _threads[threadId] = 1; } @@ -54,4 +53,4 @@ public void Stop(int id) } } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Test.Common/ExceptionVerification.cs b/src/NzbDrone.Test.Common/ExceptionVerification.cs index a60d1297b..4ead02b8f 100644 --- a/src/NzbDrone.Test.Common/ExceptionVerification.cs +++ b/src/NzbDrone.Test.Common/ExceptionVerification.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Threading; @@ -55,6 +55,7 @@ private static string GetLogsString(IEnumerable<LogEventInfo> logs) errors += Environment.NewLine + string.Format("[{0}] {1}: {2} {3}", log.Level, log.LoggerName, log.FormattedMessage, exception); } + return errors; } @@ -75,7 +76,9 @@ public static void WaitForErrors(int count, int msec) } if (!_waitEvent.Wait(msec)) + { break; + } } Expected(LogLevel.Error, count); @@ -142,9 +145,11 @@ private static void Expected(LogLevel level, int count) if (levelLogs.Count != count) { - var message = string.Format("{0} {1}(s) were expected but {2} were logged.\n\r{3}", - count, level, levelLogs.Count, GetLogsString(levelLogs)); + count, + level, + levelLogs.Count, + GetLogsString(levelLogs)); message = "\n\r****************************************************************************************\n\r" + message + @@ -166,4 +171,4 @@ private static void Ignore(LogLevel level) } } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Test.Common/MockerExtensions.cs b/src/NzbDrone.Test.Common/MockerExtensions.cs index 45f528e54..c4e18fd1c 100644 --- a/src/NzbDrone.Test.Common/MockerExtensions.cs +++ b/src/NzbDrone.Test.Common/MockerExtensions.cs @@ -12,4 +12,4 @@ public static TInterface Resolve<TInterface, TService>(this AutoMoqer mocker) return service; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Test.Common/NzbDroneRunner.cs b/src/NzbDrone.Test.Common/NzbDroneRunner.cs index a31bbb3f4..a9ab77136 100644 --- a/src/NzbDrone.Test.Common/NzbDroneRunner.cs +++ b/src/NzbDrone.Test.Common/NzbDroneRunner.cs @@ -126,7 +126,6 @@ public void KillAll() // May happen if the process closes while being closed } - TestBase.DeleteTempFolder(AppData); } diff --git a/src/NzbDrone.Test.Common/StringExtensions.cs b/src/NzbDrone.Test.Common/StringExtensions.cs index 3cdb3bf35..659be6170 100644 --- a/src/NzbDrone.Test.Common/StringExtensions.cs +++ b/src/NzbDrone.Test.Common/StringExtensions.cs @@ -14,10 +14,11 @@ public static string AsOsAgnostic(this string path) path = path.Replace(":", ""); path = Path.DirectorySeparatorChar + path; } + path = path.Replace("\\", Path.DirectorySeparatorChar.ToString()); } return path; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Test.Common/TestBase.cs b/src/NzbDrone.Test.Common/TestBase.cs index afdf97876..e13c0aff7 100644 --- a/src/NzbDrone.Test.Common/TestBase.cs +++ b/src/NzbDrone.Test.Common/TestBase.cs @@ -17,14 +17,12 @@ namespace NzbDrone.Test.Common public abstract class TestBase<TSubject> : TestBase where TSubject : class { - private TSubject _subject; [SetUp] public void CoreTestSetup() { _subject = null; - } protected TSubject Subject @@ -38,9 +36,7 @@ protected TSubject Subject return _subject; } - } - } public abstract class TestBase : LoggingTest @@ -65,7 +61,6 @@ protected AutoMoqer Mocker } } - protected int RandomNumber { get @@ -123,7 +118,6 @@ public void TestBaseTearDown() DeleteTempFolder(_tempFolder); } - public static string GetUID() { return ProcessProvider.GetCurrentProcessId() + "_" + DateTime.Now.Ticks + "_" + Interlocked.Increment(ref _nextUid); diff --git a/src/NzbDrone.Test.Common/TestException.cs b/src/NzbDrone.Test.Common/TestException.cs index 751b4c346..b51331474 100644 --- a/src/NzbDrone.Test.Common/TestException.cs +++ b/src/NzbDrone.Test.Common/TestException.cs @@ -5,4 +5,4 @@ namespace NzbDrone.Test.Common public class TestException : Exception { } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Test.Dummy/DummyApp.cs b/src/NzbDrone.Test.Dummy/DummyApp.cs index 3f6419d02..036eca70f 100644 --- a/src/NzbDrone.Test.Dummy/DummyApp.cs +++ b/src/NzbDrone.Test.Dummy/DummyApp.cs @@ -7,7 +7,7 @@ public class DummyApp { public const string DUMMY_PROCCESS_NAME = "Sonarr.Test.Dummy"; - static void Main(string[] args) + private static void Main(string[] args) { var process = Process.GetCurrentProcess(); diff --git a/src/NzbDrone.Update.Test/InstallUpdateServiceFixture.cs b/src/NzbDrone.Update.Test/InstallUpdateServiceFixture.cs index 6d9a95687..ee4d361c0 100644 --- a/src/NzbDrone.Update.Test/InstallUpdateServiceFixture.cs +++ b/src/NzbDrone.Update.Test/InstallUpdateServiceFixture.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.IO; using FluentAssertions; using NUnit.Framework; @@ -13,8 +13,8 @@ namespace NzbDrone.Update.Test [TestFixture] public class InstallUpdateServiceFixture : TestBase<InstallUpdateService> { - private string _targetFolder = @"C:\NzbDrone\".AsOsAgnostic(); private const int _processId = 12; + private string _targetFolder = @"C:\NzbDrone\".AsOsAgnostic(); [SetUp] public void Setup() diff --git a/src/NzbDrone.Update.Test/ProgramFixture.cs b/src/NzbDrone.Update.Test/ProgramFixture.cs index 36cef568a..20e39e13b 100644 --- a/src/NzbDrone.Update.Test/ProgramFixture.cs +++ b/src/NzbDrone.Update.Test/ProgramFixture.cs @@ -11,15 +11,12 @@ namespace NzbDrone.Update.Test [TestFixture] public class ProgramFixture : TestBase<UpdateApp> { - - [Test] public void should_throw_if_null_passed_in() { Assert.Throws<ArgumentOutOfRangeException>(() => Subject.Start(null)); } - [TestCase("d", "")] [TestCase("", "")] [TestCase("0", "")] @@ -34,18 +31,14 @@ public void should_throw_if_first_arg_isnt_an_int(string arg1, string arg2) [Test] public void should_call_update_with_correct_path() { - var ProcessPath = @"C:\Sonarr\Sonarr.exe".AsOsAgnostic(); + var processPath = @"C:\Sonarr\Sonarr.exe".AsOsAgnostic(); Mocker.GetMock<IProcessProvider>().Setup(c => c.GetProcessById(12)) - .Returns(new ProcessInfo() { StartPath = ProcessPath }); - - - Subject.Start(new[] { "12", "", ProcessPath }); + .Returns(new ProcessInfo() { StartPath = processPath }); + Subject.Start(new[] { "12", "", processPath }); Mocker.GetMock<IInstallUpdateService>().Verify(c => c.Start(@"C:\Sonarr".AsOsAgnostic(), 12), Times.Once()); } - - } } diff --git a/src/NzbDrone.Update.Test/UpdateProviderStartFixture.cs b/src/NzbDrone.Update.Test/UpdateProviderStartFixture.cs index 5258b59ac..7f2d401d6 100644 --- a/src/NzbDrone.Update.Test/UpdateProviderStartFixture.cs +++ b/src/NzbDrone.Update.Test/UpdateProviderStartFixture.cs @@ -58,10 +58,10 @@ public void should_stop_nzbdrone_service_if_installed_and_running() WithInstalledService(); WithServiceRunning(true); - + Mocker.Resolve<InstallUpdateService>().Start(TARGET_FOLDER); - + Mocker.GetMock<IServiceProvider>().Verify(c => c.Stop(ServiceProvider.SERVICE_NAME), Times.Once()); } @@ -71,20 +71,20 @@ public void should_not_stop_nzbdrone_service_if_installed_but_not_running() WithInstalledService(); WithServiceRunning(false); - + Mocker.Resolve<InstallUpdateService>().Start(TARGET_FOLDER); - + Mocker.GetMock<IServiceProvider>().Verify(c => c.Stop(ServiceProvider.SERVICE_NAME), Times.Never()); } [Test] public void should_not_stop_nzbdrone_service_if_service_isnt_installed() { - + Mocker.Resolve<InstallUpdateService>().Start(TARGET_FOLDER); - + Mocker.GetMock<IServiceProvider>().Verify(c => c.Stop(It.IsAny<string>()), Times.Never()); } @@ -97,7 +97,7 @@ public void should_kill_nzbdrone_process_if_running() .Setup(c => c.GetProcessByName(ProcessProvider.NzbDroneProcessName)) .Returns(proccesses); - + Mocker.Resolve<InstallUpdateService>().Start(TARGET_FOLDER); @@ -111,10 +111,10 @@ public void should_not_kill_nzbdrone_process_not_running() .Setup(c => c.GetProcessByName(ProcessProvider.NzbDroneProcessName)) .Returns(new List<ProcessInfo>()); - + Mocker.Resolve<InstallUpdateService>().Start(TARGET_FOLDER); - + Mocker.GetMock<IProcessProvider>().Verify(c => c.Kill(It.IsAny<int>()), Times.Never()); } @@ -146,10 +146,10 @@ public void should_restore_if_update_fails() .Setup(c => c.CopyDirectory(UPDATE_FOLDER, TARGET_FOLDER)) .Throws(new IOException()); - + Mocker.Resolve<InstallUpdateService>().Start(TARGET_FOLDER); - + Mocker.GetMock<IDiskProvider>() .Verify(c => c.CopyDirectory(BACKUP_FOLDER, TARGET_FOLDER), Times.Once()); ExceptionVerification.ExpectedFatals(1); @@ -161,10 +161,10 @@ public void should_restart_service_if_service_was_running() WithInstalledService(); WithServiceRunning(true); - + Mocker.Resolve<InstallUpdateService>().Start(TARGET_FOLDER); - + VerifyServiceRestart(); } @@ -174,10 +174,10 @@ public void should_restart_process_if_service_was_not_running() WithInstalledService(); WithServiceRunning(false); - + Mocker.Resolve<InstallUpdateService>().Start(TARGET_FOLDER); - + VerifyProcessRestart(); } @@ -191,10 +191,10 @@ public void should_restart_service_if_service_was_running_and_update_fails() .Setup(c => c.CopyDirectory(UPDATE_FOLDER, TARGET_FOLDER)) .Throws(new IOException()); - + Mocker.Resolve<InstallUpdateService>().Start(TARGET_FOLDER); - + VerifyServiceRestart(); ExceptionVerification.ExpectedFatals(1); } @@ -209,10 +209,10 @@ public void should_restart_process_if_service_was_not_running_and_update_fails() .Setup(c => c.CopyDirectory(UPDATE_FOLDER, TARGET_FOLDER)) .Throws(new IOException()); - + Mocker.Resolve<InstallUpdateService>().Start(TARGET_FOLDER); - + VerifyProcessRestart(); ExceptionVerification.ExpectedFatals(1); } diff --git a/src/NzbDrone.Update/UpdateApp.cs b/src/NzbDrone.Update/UpdateApp.cs index f72b6b148..9c835241e 100644 --- a/src/NzbDrone.Update/UpdateApp.cs +++ b/src/NzbDrone.Update/UpdateApp.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.IO; using System.Linq; using NLog; @@ -15,10 +15,11 @@ public class UpdateApp { private readonly IInstallUpdateService _installUpdateService; private readonly IProcessProvider _processProvider; - private static IContainer _container; private static readonly Logger Logger = NzbDroneLogger.GetLogger(typeof(UpdateApp)); + private static IContainer _container; + public UpdateApp(IInstallUpdateService installUpdateService, IProcessProvider processProvider) { _installUpdateService = installUpdateService; @@ -114,7 +115,6 @@ private string GetInstallationDirectory(UpdateStartupContext startupContext) return exeFileInfo.DirectoryName; } - else { Logger.Debug("Using executing application: {0}", startupContext.ExecutingApplication); diff --git a/src/NzbDrone.Update/UpdateContainerBuilder.cs b/src/NzbDrone.Update/UpdateContainerBuilder.cs index ae1fe4afc..8573f871d 100644 --- a/src/NzbDrone.Update/UpdateContainerBuilder.cs +++ b/src/NzbDrone.Update/UpdateContainerBuilder.cs @@ -10,7 +10,6 @@ public class UpdateContainerBuilder : ContainerBuilderBase private UpdateContainerBuilder(IStartupContext startupContext, List<string> assemblies) : base(startupContext, assemblies) { - } public static IContainer Build(IStartupContext startupContext) diff --git a/src/NzbDrone.Update/UpdateEngine/DetectApplicationType.cs b/src/NzbDrone.Update/UpdateEngine/DetectApplicationType.cs index 781435606..9aac7edb2 100644 --- a/src/NzbDrone.Update/UpdateEngine/DetectApplicationType.cs +++ b/src/NzbDrone.Update/UpdateEngine/DetectApplicationType.cs @@ -42,4 +42,4 @@ public AppType GetAppType() return AppType.Normal; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Update/UpdateEngine/InstallUpdateService.cs b/src/NzbDrone.Update/UpdateEngine/InstallUpdateService.cs index 260db29f0..c3287f3fe 100644 --- a/src/NzbDrone.Update/UpdateEngine/InstallUpdateService.cs +++ b/src/NzbDrone.Update/UpdateEngine/InstallUpdateService.cs @@ -57,10 +57,14 @@ private void Verify(string targetFolder, int processId) _logger.Info("Verifying requirements before update..."); if (string.IsNullOrWhiteSpace(targetFolder)) + { throw new ArgumentException("Target folder can not be null or empty"); + } if (!_diskProvider.FolderExists(targetFolder)) + { throw new DirectoryNotFoundException("Target folder doesn't exist " + targetFolder); + } if (processId < 1) { @@ -74,7 +78,9 @@ private void Verify(string targetFolder, int processId) _logger.Info("Verifying Update Folder"); if (!_diskProvider.FolderExists(_appFolderInfo.GetUpdatePackageFolder())) + { throw new DirectoryNotFoundException("Update folder doesn't exist " + _appFolderInfo.GetUpdatePackageFolder()); + } } public void Start(string installationFolder, int processId) @@ -161,7 +167,6 @@ public void Start(string installationFolder, int processId) } } } - } } } diff --git a/src/NzbDrone.Update/UpdateEngine/StartNzbDrone.cs b/src/NzbDrone.Update/UpdateEngine/StartNzbDrone.cs index d4eae8d8a..36cd51efb 100644 --- a/src/NzbDrone.Update/UpdateEngine/StartNzbDrone.cs +++ b/src/NzbDrone.Update/UpdateEngine/StartNzbDrone.cs @@ -37,7 +37,6 @@ public void Start(AppType appType, string installationFolder) try { StartService(); - } catch (InvalidOperationException e) { diff --git a/src/NzbDrone.Update/UpdateEngine/TerminateNzbDrone.cs b/src/NzbDrone.Update/UpdateEngine/TerminateNzbDrone.cs index ce2d90812..2c9319caf 100644 --- a/src/NzbDrone.Update/UpdateEngine/TerminateNzbDrone.cs +++ b/src/NzbDrone.Update/UpdateEngine/TerminateNzbDrone.cs @@ -61,4 +61,4 @@ public void Terminate(int processId) } } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Windows/Disk/DiskProvider.cs b/src/NzbDrone.Windows/Disk/DiskProvider.cs index 14aa624fb..d8b9dc448 100644 --- a/src/NzbDrone.Windows/Disk/DiskProvider.cs +++ b/src/NzbDrone.Windows/Disk/DiskProvider.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.IO; using System.Linq; using System.Runtime.InteropServices; @@ -17,14 +17,14 @@ public class DiskProvider : DiskProviderBase [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)] [return: MarshalAs(UnmanagedType.Bool)] - static extern bool GetDiskFreeSpaceEx(string lpDirectoryName, + private static extern bool GetDiskFreeSpaceEx(string lpDirectoryName, out ulong lpFreeBytesAvailable, out ulong lpTotalNumberOfBytes, out ulong lpTotalNumberOfFreeBytes); [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)] [return: MarshalAs(UnmanagedType.Bool)] - static extern bool CreateHardLink(string lpFileName, string lpExistingFileName, IntPtr lpSecurityAttributes); + private static extern bool CreateHardLink(string lpFileName, string lpExistingFileName, IntPtr lpSecurityAttributes); public override long? GetAvailableSpace(string path) { @@ -33,7 +33,9 @@ static extern bool GetDiskFreeSpaceEx(string lpDirectoryName, var root = GetPathRoot(path); if (!FolderExists(root)) + { throw new DirectoryNotFoundException(root); + } return DriveFreeSpaceEx(root); } @@ -68,9 +70,11 @@ public override void SetEveryonePermissions(string filename) return; } - var accessRule = new FileSystemAccessRule(sid, rights, + var accessRule = new FileSystemAccessRule(sid, + rights, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, - PropagationFlags.InheritOnly, controlType); + PropagationFlags.InheritOnly, + controlType); bool modified; directorySecurity.ModifyAccessRule(AccessControlModification.Add, accessRule, out modified); @@ -85,22 +89,18 @@ public override void SetEveryonePermissions(string filename) Logger.Warn(e, "Couldn't set permission for {0}. account:{1} rights:{2} accessControlType:{3}", filename, accountSid, rights, controlType); throw; } - } public override void SetFilePermissions(string path, string mask, string group) { - } public override void SetPermissions(string path, string mask, string group) { - } public override void CopyPermissions(string sourcePath, string targetPath) { - } public override long? GetTotalSize(string path) @@ -110,7 +110,9 @@ public override void CopyPermissions(string sourcePath, string targetPath) var root = GetPathRoot(path); if (!FolderExists(root)) + { throw new DirectoryNotFoundException(root); + } return DriveTotalSizeEx(root); } @@ -157,7 +159,6 @@ private static long DriveTotalSizeEx(string folderName) return 0; } - public override bool TryCreateHardLink(string source, string destination) { try diff --git a/src/NzbDrone.Windows/EnvironmentInfo/WindowsVersionInfo.cs b/src/NzbDrone.Windows/EnvironmentInfo/WindowsVersionInfo.cs index d71c9a7f0..6d9699f87 100644 --- a/src/NzbDrone.Windows/EnvironmentInfo/WindowsVersionInfo.cs +++ b/src/NzbDrone.Windows/EnvironmentInfo/WindowsVersionInfo.cs @@ -46,4 +46,4 @@ private bool IsServer() return false; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone/MessageBoxUserAlert.cs b/src/NzbDrone/MessageBoxUserAlert.cs index 1b5686864..b95eec3de 100644 --- a/src/NzbDrone/MessageBoxUserAlert.cs +++ b/src/NzbDrone/MessageBoxUserAlert.cs @@ -10,4 +10,4 @@ public void Alert(string message) MessageBox.Show(text: message, buttons: MessageBoxButtons.OK, icon: MessageBoxIcon.Warning, caption: "NzbDrone"); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone/SysTray/SysTrayApp.cs b/src/NzbDrone/SysTray/SysTrayApp.cs index 32fb66d1a..38979724f 100644 --- a/src/NzbDrone/SysTray/SysTrayApp.cs +++ b/src/NzbDrone/SysTray/SysTrayApp.cs @@ -78,7 +78,6 @@ protected override void Dispose(bool isDisposing) { Invoke(new MethodInvoker(() => Dispose(isDisposing))); } - else { base.Dispose(isDisposing); @@ -99,7 +98,6 @@ private void LaunchBrowser(object sender, EventArgs e) } catch (Exception) { - } } @@ -129,7 +127,6 @@ private void DisposeTrayIcon() } catch (Exception) { - } } } diff --git a/src/ServiceHelpers/ServiceInstall/Program.cs b/src/ServiceHelpers/ServiceInstall/Program.cs index 02938247b..d178414a5 100644 --- a/src/ServiceHelpers/ServiceInstall/Program.cs +++ b/src/ServiceHelpers/ServiceInstall/Program.cs @@ -1,8 +1,8 @@ -namespace ServiceInstall +namespace ServiceInstall { public static class Program { - static void Main() + private static void Main() { ServiceHelper.Run(@"/i"); } diff --git a/src/ServiceHelpers/ServiceInstall/ServiceHelper.cs b/src/ServiceHelpers/ServiceInstall/ServiceHelper.cs index 5fb7e35b6..1162f764c 100644 --- a/src/ServiceHelpers/ServiceInstall/ServiceHelper.cs +++ b/src/ServiceHelpers/ServiceInstall/ServiceHelper.cs @@ -41,8 +41,8 @@ public static void Run(string arg) }; var process = new Process { StartInfo = startInfo }; - process.OutputDataReceived += (OnDataReceived); - process.ErrorDataReceived += (OnDataReceived); + process.OutputDataReceived += OnDataReceived; + process.ErrorDataReceived += OnDataReceived; process.Start(); diff --git a/src/ServiceHelpers/ServiceUninstall/Program.cs b/src/ServiceHelpers/ServiceUninstall/Program.cs index c8bc4f181..f57066bb7 100644 --- a/src/ServiceHelpers/ServiceUninstall/Program.cs +++ b/src/ServiceHelpers/ServiceUninstall/Program.cs @@ -2,7 +2,7 @@ { public static class Program { - static void Main() + private static void Main() { ServiceHelper.Run(@"/u"); } diff --git a/src/ServiceHelpers/ServiceUninstall/ServiceHelper.cs b/src/ServiceHelpers/ServiceUninstall/ServiceHelper.cs index 3bf6b6594..a1b97ccad 100644 --- a/src/ServiceHelpers/ServiceUninstall/ServiceHelper.cs +++ b/src/ServiceHelpers/ServiceUninstall/ServiceHelper.cs @@ -41,8 +41,8 @@ public static void Run(string arg) }; var process = new Process { StartInfo = startInfo }; - process.OutputDataReceived += (OnDataReceived); - process.ErrorDataReceived += (OnDataReceived); + process.OutputDataReceived += OnDataReceived; + process.ErrorDataReceived += OnDataReceived; process.Start(); diff --git a/src/Sonarr.Api.V3/Blocklist/BlocklistResource.cs b/src/Sonarr.Api.V3/Blocklist/BlocklistResource.cs index b6cb9f77d..485be42a1 100644 --- a/src/Sonarr.Api.V3/Blocklist/BlocklistResource.cs +++ b/src/Sonarr.Api.V3/Blocklist/BlocklistResource.cs @@ -27,7 +27,10 @@ public static class BlocklistResourceMapper { public static BlocklistResource MapToResource(this NzbDrone.Core.Blocklisting.Blocklist model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new BlocklistResource { diff --git a/src/Sonarr.Api.V3/Calendar/CalendarFeedModule.cs b/src/Sonarr.Api.V3/Calendar/CalendarFeedModule.cs index dc764a594..5f68c3981 100644 --- a/src/Sonarr.Api.V3/Calendar/CalendarFeedModule.cs +++ b/src/Sonarr.Api.V3/Calendar/CalendarFeedModule.cs @@ -31,10 +31,11 @@ public CalendarFeedModule(IEpisodeService episodeService, ITagService tagService private object GetCalendarFeed() { var pastDays = 7; - var futureDays = 28; + var futureDays = 28; var start = DateTime.Today.AddDays(-pastDays); var end = DateTime.Today.AddDays(futureDays); var unmonitored = Request.GetBooleanQueryParameter("unmonitored"); + // There was a typo, recognize both the correct 'premieresOnly' and mistyped 'premiersOnly' boolean for background compat. var premieresOnly = Request.GetBooleanQueryParameter("premieresOnly") || Request.GetBooleanQueryParameter("premiersOnly"); var asAllDay = Request.GetBooleanQueryParameter("asAllDay"); diff --git a/src/Sonarr.Api.V3/Calendar/CalendarModule.cs b/src/Sonarr.Api.V3/Calendar/CalendarModule.cs index 6440eba44..09017ba60 100644 --- a/src/Sonarr.Api.V3/Calendar/CalendarModule.cs +++ b/src/Sonarr.Api.V3/Calendar/CalendarModule.cs @@ -33,8 +33,15 @@ private List<EpisodeResource> GetCalendar() var queryStart = Request.Query.Start; var queryEnd = Request.Query.End; - if (queryStart.HasValue) start = DateTime.Parse(queryStart.Value); - if (queryEnd.HasValue) end = DateTime.Parse(queryEnd.Value); + if (queryStart.HasValue) + { + start = DateTime.Parse(queryStart.Value); + } + + if (queryEnd.HasValue) + { + end = DateTime.Parse(queryEnd.Value); + } var resources = MapToResource(_episodeService.EpisodesBetweenDates(start, end, includeUnmonitored), includeSeries, includeEpisodeFile, includeEpisodeImages); diff --git a/src/Sonarr.Api.V3/Commands/CommandModule.cs b/src/Sonarr.Api.V3/Commands/CommandModule.cs index fd4964296..3c960d816 100644 --- a/src/Sonarr.Api.V3/Commands/CommandModule.cs +++ b/src/Sonarr.Api.V3/Commands/CommandModule.cs @@ -50,7 +50,7 @@ private CommandResource GetCommand(int id) private int StartCommand(CommandResource commandResource) { var commandType = - _serviceFactory.GetImplementations(typeof (Command)) + _serviceFactory.GetImplementations(typeof(Command)) .Single(c => c.Name.Replace("Command", "") .Equals(commandResource.Name, StringComparison.InvariantCultureIgnoreCase)); diff --git a/src/Sonarr.Api.V3/Commands/CommandResource.cs b/src/Sonarr.Api.V3/Commands/CommandResource.cs index cef9722f0..aa919a620 100644 --- a/src/Sonarr.Api.V3/Commands/CommandResource.cs +++ b/src/Sonarr.Api.V3/Commands/CommandResource.cs @@ -33,37 +33,51 @@ public DateTime? StateChangeTime { get { - - if (Started.HasValue) return Started.Value; + if (Started.HasValue) + { + return Started.Value; + } return Ended; } - set { } + set + { + } } public bool SendUpdatesToClient { get { - if (Body != null) return Body.SendUpdatesToClient; + if (Body != null) + { + return Body.SendUpdatesToClient; + } return false; } - set { } + set + { + } } public bool UpdateScheduledTask { get { - if (Body != null) return Body.UpdateScheduledTask; + if (Body != null) + { + return Body.UpdateScheduledTask; + } return false; } - set { } + set + { + } } public DateTime? LastExecutionTime { get; set; } @@ -73,7 +87,10 @@ public static class CommandResourceMapper { public static CommandResource ToResource(this CommandModel model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new CommandResource { diff --git a/src/Sonarr.Api.V3/Config/DownloadClientConfigModule.cs b/src/Sonarr.Api.V3/Config/DownloadClientConfigModule.cs index 223f25cab..242e3971a 100644 --- a/src/Sonarr.Api.V3/Config/DownloadClientConfigModule.cs +++ b/src/Sonarr.Api.V3/Config/DownloadClientConfigModule.cs @@ -14,4 +14,4 @@ protected override DownloadClientConfigResource ToResource(IConfigService model) return DownloadClientConfigResourceMapper.ToResource(model); } } -} \ No newline at end of file +} diff --git a/src/Sonarr.Api.V3/Config/HostConfigResource.cs b/src/Sonarr.Api.V3/Config/HostConfigResource.cs index 30c6284f4..4d0c1b3e3 100644 --- a/src/Sonarr.Api.V3/Config/HostConfigResource.cs +++ b/src/Sonarr.Api.V3/Config/HostConfigResource.cs @@ -57,6 +57,7 @@ public static HostConfigResource ToResource(this IConfigFileProvider model, ICon LaunchBrowser = model.LaunchBrowser, AuthenticationMethod = model.AuthenticationMethod, AnalyticsEnabled = model.AnalyticsEnabled, + //Username //Password LogLevel = model.LogLevel, diff --git a/src/Sonarr.Api.V3/Config/IndexerConfigModule.cs b/src/Sonarr.Api.V3/Config/IndexerConfigModule.cs index 438fa477a..7251c9d78 100644 --- a/src/Sonarr.Api.V3/Config/IndexerConfigModule.cs +++ b/src/Sonarr.Api.V3/Config/IndexerConfigModule.cs @@ -6,7 +6,6 @@ namespace Sonarr.Api.V3.Config { public class IndexerConfigModule : SonarrConfigModule<IndexerConfigResource> { - public IndexerConfigModule(IConfigService configService) : base(configService) { @@ -25,4 +24,4 @@ protected override IndexerConfigResource ToResource(IConfigService model) return IndexerConfigResourceMapper.ToResource(model); } } -} \ No newline at end of file +} diff --git a/src/Sonarr.Api.V3/Config/NamingConfigModule.cs b/src/Sonarr.Api.V3/Config/NamingConfigModule.cs index b5bf12179..2863b829b 100644 --- a/src/Sonarr.Api.V3/Config/NamingConfigModule.cs +++ b/src/Sonarr.Api.V3/Config/NamingConfigModule.cs @@ -77,7 +77,7 @@ private object GetExamples(NamingConfigResource config) var nameSpec = config.ToModel(); var sampleResource = new NamingExampleResource(); - + var singleEpisodeSampleResult = _filenameSampleService.GetStandardSample(nameSpec); var multiEpisodeSampleResult = _filenameSampleService.GetMultiEpisodeSample(nameSpec); var dailyEpisodeSampleResult = _filenameSampleService.GetDailySample(nameSpec); diff --git a/src/Sonarr.Api.V3/Config/NamingConfigResource.cs b/src/Sonarr.Api.V3/Config/NamingConfigResource.cs index 4a78ffe7b..8b95058a7 100644 --- a/src/Sonarr.Api.V3/Config/NamingConfigResource.cs +++ b/src/Sonarr.Api.V3/Config/NamingConfigResource.cs @@ -20,4 +20,4 @@ public class NamingConfigResource : RestResource public string Separator { get; set; } public string NumberStyle { get; set; } } -} \ No newline at end of file +} diff --git a/src/Sonarr.Api.V3/Config/NamingExampleResource.cs b/src/Sonarr.Api.V3/Config/NamingExampleResource.cs index 02f7c472e..587dbad3d 100644 --- a/src/Sonarr.Api.V3/Config/NamingExampleResource.cs +++ b/src/Sonarr.Api.V3/Config/NamingExampleResource.cs @@ -31,6 +31,7 @@ public static NamingConfigResource ToResource(this NamingConfig model) SeriesFolderFormat = model.SeriesFolderFormat, SeasonFolderFormat = model.SeasonFolderFormat, SpecialsFolderFormat = model.SpecialsFolderFormat + //IncludeSeriesTitle //IncludeEpisodeTitle //IncludeQuality @@ -68,4 +69,4 @@ public static NamingConfig ToModel(this NamingConfigResource resource) }; } } -} \ No newline at end of file +} diff --git a/src/Sonarr.Api.V3/Config/SonarrConfigModule.cs b/src/Sonarr.Api.V3/Config/SonarrConfigModule.cs index 81db42608..ae7a000dc 100644 --- a/src/Sonarr.Api.V3/Config/SonarrConfigModule.cs +++ b/src/Sonarr.Api.V3/Config/SonarrConfigModule.cs @@ -6,7 +6,8 @@ namespace Sonarr.Api.V3.Config { - public abstract class SonarrConfigModule<TResource> : SonarrRestModule<TResource> where TResource : RestResource, new() + public abstract class SonarrConfigModule<TResource> : SonarrRestModule<TResource> + where TResource : RestResource, new() { private readonly IConfigService _configService; @@ -15,8 +16,8 @@ protected SonarrConfigModule(IConfigService configService) { } - protected SonarrConfigModule(string resource, IConfigService configService) : - base("config/" + resource.Trim('/')) + protected SonarrConfigModule(string resource, IConfigService configService) + : base("config/" + resource.Trim('/')) { _configService = configService; diff --git a/src/Sonarr.Api.V3/Config/UiConfigModule.cs b/src/Sonarr.Api.V3/Config/UiConfigModule.cs index 8a3408c57..86306f22a 100644 --- a/src/Sonarr.Api.V3/Config/UiConfigModule.cs +++ b/src/Sonarr.Api.V3/Config/UiConfigModule.cs @@ -7,7 +7,6 @@ public class UiConfigModule : SonarrConfigModule<UiConfigResource> public UiConfigModule(IConfigService configService) : base(configService) { - } protected override UiConfigResource ToResource(IConfigService model) @@ -15,4 +14,4 @@ protected override UiConfigResource ToResource(IConfigService model) return UiConfigResourceMapper.ToResource(model); } } -} \ No newline at end of file +} diff --git a/src/Sonarr.Api.V3/CustomFilters/CustomFilterResource.cs b/src/Sonarr.Api.V3/CustomFilters/CustomFilterResource.cs index b1079591f..aa71a34d8 100644 --- a/src/Sonarr.Api.V3/CustomFilters/CustomFilterResource.cs +++ b/src/Sonarr.Api.V3/CustomFilters/CustomFilterResource.cs @@ -17,7 +17,10 @@ public static class CustomFilterResourceMapper { public static CustomFilterResource ToResource(this CustomFilter model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new CustomFilterResource { @@ -30,7 +33,10 @@ public static CustomFilterResource ToResource(this CustomFilter model) public static CustomFilter ToModel(this CustomFilterResource resource) { - if (resource == null) return null; + if (resource == null) + { + return null; + } return new CustomFilter { diff --git a/src/Sonarr.Api.V3/DiskSpace/DiskSpaceResource.cs b/src/Sonarr.Api.V3/DiskSpace/DiskSpaceResource.cs index 18750eebd..9a5ceec4d 100644 --- a/src/Sonarr.Api.V3/DiskSpace/DiskSpaceResource.cs +++ b/src/Sonarr.Api.V3/DiskSpace/DiskSpaceResource.cs @@ -14,7 +14,10 @@ public static class DiskSpaceResourceMapper { public static DiskSpaceResource MapToResource(this NzbDrone.Core.DiskSpace.DiskSpace model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new DiskSpaceResource { diff --git a/src/Sonarr.Api.V3/DownloadClient/DownloadClientModule.cs b/src/Sonarr.Api.V3/DownloadClient/DownloadClientModule.cs index be45700d5..4575a2bd4 100644 --- a/src/Sonarr.Api.V3/DownloadClient/DownloadClientModule.cs +++ b/src/Sonarr.Api.V3/DownloadClient/DownloadClientModule.cs @@ -11,4 +11,4 @@ public DownloadClientModule(IDownloadClientFactory downloadClientFactory) { } } -} \ No newline at end of file +} diff --git a/src/Sonarr.Api.V3/DownloadClient/DownloadClientResource.cs b/src/Sonarr.Api.V3/DownloadClient/DownloadClientResource.cs index 713496537..31e200f0b 100644 --- a/src/Sonarr.Api.V3/DownloadClient/DownloadClientResource.cs +++ b/src/Sonarr.Api.V3/DownloadClient/DownloadClientResource.cs @@ -16,7 +16,10 @@ public class DownloadClientResourceMapper : ProviderResourceMapper<DownloadClien { public override DownloadClientResource ToResource(DownloadClientDefinition definition) { - if (definition == null) return null; + if (definition == null) + { + return null; + } var resource = base.ToResource(definition); @@ -31,7 +34,10 @@ public override DownloadClientResource ToResource(DownloadClientDefinition defin public override DownloadClientDefinition ToModel(DownloadClientResource resource) { - if (resource == null) return null; + if (resource == null) + { + return null; + } var definition = base.ToModel(resource); @@ -44,4 +50,4 @@ public override DownloadClientDefinition ToModel(DownloadClientResource resource return definition; } } -} \ No newline at end of file +} diff --git a/src/Sonarr.Api.V3/EpisodeFiles/EpisodeFileModule.cs b/src/Sonarr.Api.V3/EpisodeFiles/EpisodeFileModule.cs index 6feb5102b..2111c0d8f 100644 --- a/src/Sonarr.Api.V3/EpisodeFiles/EpisodeFileModule.cs +++ b/src/Sonarr.Api.V3/EpisodeFiles/EpisodeFileModule.cs @@ -73,7 +73,6 @@ private List<EpisodeFileResource> GetEpisodeFiles() return _mediaFileService.GetFilesBySeries(seriesId).ConvertAll(f => f.ToResource(series, _upgradableSpecification)); } - else { string episodeFileIdsValue = episodeFileIdsQuery.Value.ToString(); @@ -86,7 +85,7 @@ private List<EpisodeFileResource> GetEpisodeFiles() return episodeFiles.GroupBy(e => e.SeriesId) .SelectMany(f => f.ToList() - .ConvertAll( e => e.ToResource(_seriesService.GetSeries(f.Key), _upgradableSpecification))) + .ConvertAll(e => e.ToResource(_seriesService.GetSeries(f.Key), _upgradableSpecification))) .ToList(); } } diff --git a/src/Sonarr.Api.V3/EpisodeFiles/EpisodeFileResource.cs b/src/Sonarr.Api.V3/EpisodeFiles/EpisodeFileResource.cs index 0dbe2f66d..944c24dcd 100644 --- a/src/Sonarr.Api.V3/EpisodeFiles/EpisodeFileResource.cs +++ b/src/Sonarr.Api.V3/EpisodeFiles/EpisodeFileResource.cs @@ -31,7 +31,10 @@ public static class EpisodeFileResourceMapper { private static EpisodeFileResource ToResource(this EpisodeFile model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new EpisodeFileResource { @@ -40,6 +43,7 @@ private static EpisodeFileResource ToResource(this EpisodeFile model) SeriesId = model.SeriesId, SeasonNumber = model.SeasonNumber, RelativePath = model.RelativePath, + //Path Size = model.Size, DateAdded = model.DateAdded, @@ -48,14 +52,17 @@ private static EpisodeFileResource ToResource(this EpisodeFile model) Language = model.Language, Quality = model.Quality, MediaInfo = model.MediaInfo.ToResource(model.SceneName) + //QualityCutoffNotMet }; - } public static EpisodeFileResource ToResource(this EpisodeFile model, NzbDrone.Core.Tv.Series series, IUpgradableSpecification upgradableSpecification) { - if (model == null) return null; + if (model == null) + { + return null; + } return new EpisodeFileResource { diff --git a/src/Sonarr.Api.V3/EpisodeFiles/MediaInfoResource.cs b/src/Sonarr.Api.V3/EpisodeFiles/MediaInfoResource.cs index f114453da..ae85ae5ef 100644 --- a/src/Sonarr.Api.V3/EpisodeFiles/MediaInfoResource.cs +++ b/src/Sonarr.Api.V3/EpisodeFiles/MediaInfoResource.cs @@ -53,7 +53,6 @@ public static MediaInfoResource ToResource(this MediaInfoModel model, string sce }; } - private static string FormatRuntime(TimeSpan runTime) { var formattedRuntime = ""; diff --git a/src/Sonarr.Api.V3/Episodes/EpisodeModule.cs b/src/Sonarr.Api.V3/Episodes/EpisodeModule.cs index 919d6981f..53bf48925 100644 --- a/src/Sonarr.Api.V3/Episodes/EpisodeModule.cs +++ b/src/Sonarr.Api.V3/Episodes/EpisodeModule.cs @@ -58,7 +58,6 @@ private List<EpisodeResource> GetEpisodes() int episodeFileId = Convert.ToInt32(episodeFileIdQuery.Value); return MapToResource(_episodeService.GetEpisodesByFileId(episodeFileId), false, false, includeImages); - } throw new BadRequestException("seriesId or episodeIds must be provided"); diff --git a/src/Sonarr.Api.V3/Episodes/EpisodeModuleWithSignalR.cs b/src/Sonarr.Api.V3/Episodes/EpisodeModuleWithSignalR.cs index 6ff27de59..b51c609b7 100644 --- a/src/Sonarr.Api.V3/Episodes/EpisodeModuleWithSignalR.cs +++ b/src/Sonarr.Api.V3/Episodes/EpisodeModuleWithSignalR.cs @@ -56,7 +56,7 @@ protected EpisodeResource GetEpisode(int id) var resource = MapToResource(episode, true, true, true); return resource; } - + protected override EpisodeResource GetResourceByIdForBroadcast(int id) { var episode = _episodeService.GetEpisode(id); diff --git a/src/Sonarr.Api.V3/Episodes/EpisodeResource.cs b/src/Sonarr.Api.V3/Episodes/EpisodeResource.cs index 4551658cd..93c3ebb9c 100644 --- a/src/Sonarr.Api.V3/Episodes/EpisodeResource.cs +++ b/src/Sonarr.Api.V3/Episodes/EpisodeResource.cs @@ -46,7 +46,10 @@ public static class EpisodeResourceMapper { public static EpisodeResource ToResource(this Episode model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new EpisodeResource { @@ -61,6 +64,7 @@ public static EpisodeResource ToResource(this Episode model) AirDate = model.AirDate, AirDateUtc = model.AirDateUtc, Overview = model.Overview, + //EpisodeFile HasFile = model.HasFile, @@ -71,13 +75,17 @@ public static EpisodeResource ToResource(this Episode model) SceneSeasonNumber = model.SceneSeasonNumber, UnverifiedSceneNumbering = model.UnverifiedSceneNumbering, SeriesTitle = model.SeriesTitle, + //Series = model.Series.MapToResource(), }; } public static List<EpisodeResource> ToResource(this IEnumerable<Episode> models) { - if (models == null) return null; + if (models == null) + { + return null; + } return models.Select(ToResource).ToList(); } diff --git a/src/Sonarr.Api.V3/Episodes/RenameEpisodeModule.cs b/src/Sonarr.Api.V3/Episodes/RenameEpisodeModule.cs index d714369d7..d0ed7da23 100644 --- a/src/Sonarr.Api.V3/Episodes/RenameEpisodeModule.cs +++ b/src/Sonarr.Api.V3/Episodes/RenameEpisodeModule.cs @@ -25,7 +25,6 @@ private List<RenameEpisodeResource> GetEpisodes() { seriesId = (int)Request.Query.SeriesId; } - else { throw new BadRequestException("seriesId is missing"); diff --git a/src/Sonarr.Api.V3/Episodes/RenameEpisodeResource.cs b/src/Sonarr.Api.V3/Episodes/RenameEpisodeResource.cs index 3f6ef14e0..fe45cff96 100644 --- a/src/Sonarr.Api.V3/Episodes/RenameEpisodeResource.cs +++ b/src/Sonarr.Api.V3/Episodes/RenameEpisodeResource.cs @@ -18,7 +18,10 @@ public static class RenameEpisodeResourceMapper { public static RenameEpisodeResource ToResource(this NzbDrone.Core.MediaFiles.RenameEpisodeFilePreview model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new RenameEpisodeResource { diff --git a/src/Sonarr.Api.V3/FileSystem/FileSystemModule.cs b/src/Sonarr.Api.V3/FileSystem/FileSystemModule.cs index 4c20dd86f..29303568b 100644 --- a/src/Sonarr.Api.V3/FileSystem/FileSystemModule.cs +++ b/src/Sonarr.Api.V3/FileSystem/FileSystemModule.cs @@ -61,7 +61,8 @@ private object GetMediaFiles() return new string[0]; } - return _diskScanService.GetVideoFiles(path).Select(f => new { + return _diskScanService.GetVideoFiles(path).Select(f => new + { Path = f, RelativePath = path.GetRelativePath(f), Name = Path.GetFileName(f) diff --git a/src/Sonarr.Api.V3/Health/HealthModule.cs b/src/Sonarr.Api.V3/Health/HealthModule.cs index bc5cece82..841e31d57 100644 --- a/src/Sonarr.Api.V3/Health/HealthModule.cs +++ b/src/Sonarr.Api.V3/Health/HealthModule.cs @@ -29,4 +29,4 @@ public void Handle(HealthCheckCompleteEvent message) BroadcastResourceChange(ModelAction.Sync); } } -} \ No newline at end of file +} diff --git a/src/Sonarr.Api.V3/Health/HealthResource.cs b/src/Sonarr.Api.V3/Health/HealthResource.cs index 702c2cc10..9e5102109 100644 --- a/src/Sonarr.Api.V3/Health/HealthResource.cs +++ b/src/Sonarr.Api.V3/Health/HealthResource.cs @@ -18,7 +18,10 @@ public static class HealthResourceMapper { public static HealthResource ToResource(this HealthCheck model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new HealthResource { diff --git a/src/Sonarr.Api.V3/History/HistoryModule.cs b/src/Sonarr.Api.V3/History/HistoryModule.cs index f20806d23..c4c22c17f 100644 --- a/src/Sonarr.Api.V3/History/HistoryModule.cs +++ b/src/Sonarr.Api.V3/History/HistoryModule.cs @@ -32,7 +32,6 @@ public HistoryModule(IHistoryService historyService, Get("/series", x => GetSeriesHistory()); Post("/failed", x => MarkAsFailed()); Post(@"/failed/(?<id>[\d]{1,10})", x => MarkAsFailed((int)x.Id)); - } protected HistoryResource MapToResource(EpisodeHistory model, bool includeSeries, bool includeEpisode) @@ -79,7 +78,7 @@ private PagingResource<HistoryResource> GetHistory(PagingResource<HistoryResourc var episodeId = Convert.ToInt32(episodeIdFilter.Value); pagingSpec.FilterExpressions.Add(h => h.EpisodeId == episodeId); } - + if (downloadIdFilter != null) { var downloadId = downloadIdFilter.Value; @@ -93,7 +92,7 @@ private List<HistoryResource> GetHistorySince() { var queryDate = Request.Query.Date; var queryEventType = Request.Query.EventType; - + if (!queryDate.HasValue) { throw new BadRequestException("date is missing"); diff --git a/src/Sonarr.Api.V3/History/HistoryResource.cs b/src/Sonarr.Api.V3/History/HistoryResource.cs index 467ab4b20..c412c209c 100644 --- a/src/Sonarr.Api.V3/History/HistoryResource.cs +++ b/src/Sonarr.Api.V3/History/HistoryResource.cs @@ -33,7 +33,10 @@ public static class HistoryResourceMapper { public static HistoryResource ToResource(this EpisodeHistory model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new HistoryResource { @@ -44,6 +47,7 @@ public static HistoryResource ToResource(this EpisodeHistory model) SourceTitle = model.SourceTitle, Language = model.Language, Quality = model.Quality, + //QualityCutoffNotMet Date = model.Date, DownloadId = model.DownloadId, @@ -51,6 +55,7 @@ public static HistoryResource ToResource(this EpisodeHistory model) EventType = model.EventType, Data = model.Data + //Episode //Series }; diff --git a/src/Sonarr.Api.V3/ImportLists/ImportListExclusionModule.cs b/src/Sonarr.Api.V3/ImportLists/ImportListExclusionModule.cs index 0e6b9d84b..e88e9d83c 100644 --- a/src/Sonarr.Api.V3/ImportLists/ImportListExclusionModule.cs +++ b/src/Sonarr.Api.V3/ImportLists/ImportListExclusionModule.cs @@ -1,8 +1,8 @@ using System.Collections.Generic; -using NzbDrone.Core.ImportLists.Exclusions; -using Sonarr.Http; using FluentValidation; +using NzbDrone.Core.ImportLists.Exclusions; using NzbDrone.Core.Validation; +using Sonarr.Http; namespace Sonarr.Api.V3.ImportLists { diff --git a/src/Sonarr.Api.V3/ImportLists/ImportListExclusionResource.cs b/src/Sonarr.Api.V3/ImportLists/ImportListExclusionResource.cs index 42287d07e..b39cd6167 100644 --- a/src/Sonarr.Api.V3/ImportLists/ImportListExclusionResource.cs +++ b/src/Sonarr.Api.V3/ImportLists/ImportListExclusionResource.cs @@ -15,7 +15,10 @@ public static class ImportListExclusionResourceMapper { public static ImportListExclusionResource ToResource(this ImportListExclusion model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new ImportListExclusionResource { @@ -27,7 +30,10 @@ public static ImportListExclusionResource ToResource(this ImportListExclusion mo public static ImportListExclusion ToModel(this ImportListExclusionResource resource) { - if (resource == null) return null; + if (resource == null) + { + return null; + } return new ImportListExclusion { diff --git a/src/Sonarr.Api.V3/ImportLists/ImportListModule.cs b/src/Sonarr.Api.V3/ImportLists/ImportListModule.cs index aab081598..e3f06128b 100644 --- a/src/Sonarr.Api.V3/ImportLists/ImportListModule.cs +++ b/src/Sonarr.Api.V3/ImportLists/ImportListModule.cs @@ -10,8 +10,7 @@ public class ImportListModule : ProviderModuleBase<ImportListResource, IImportLi public ImportListModule(ImportListFactory importListFactory, ProfileExistsValidator profileExistsValidator, - LanguageProfileExistsValidator languageProfileExistsValidator - ) + LanguageProfileExistsValidator languageProfileExistsValidator) : base(importListFactory, "importlist", ResourceMapper) { Http.Validation.RuleBuilderExtensions.ValidId(SharedValidator.RuleFor(s => s.QualityProfileId)); diff --git a/src/Sonarr.Api.V3/ImportLists/ImportListResource.cs b/src/Sonarr.Api.V3/ImportLists/ImportListResource.cs index 6f708b3e1..bfb65275e 100644 --- a/src/Sonarr.Api.V3/ImportLists/ImportListResource.cs +++ b/src/Sonarr.Api.V3/ImportLists/ImportListResource.cs @@ -26,7 +26,7 @@ public override ImportListResource ToResource(ImportListDefinition definition) } var resource = base.ToResource(definition); - + resource.EnableAutomaticAdd = definition.EnableAutomaticAdd; resource.ShouldMonitor = definition.ShouldMonitor; resource.RootFolderPath = definition.RootFolderPath; @@ -35,7 +35,7 @@ public override ImportListResource ToResource(ImportListDefinition definition) resource.SeriesType = definition.SeriesType; resource.SeasonFolder = definition.SeasonFolder; resource.ListType = definition.ListType; - resource.ListOrder = (int) definition.ListType; + resource.ListOrder = (int)definition.ListType; return resource; } @@ -48,7 +48,7 @@ public override ImportListDefinition ToModel(ImportListResource resource) } var definition = base.ToModel(resource); - + definition.EnableAutomaticAdd = resource.EnableAutomaticAdd; definition.ShouldMonitor = resource.ShouldMonitor; definition.RootFolderPath = resource.RootFolderPath; diff --git a/src/Sonarr.Api.V3/Indexers/IndexerModule.cs b/src/Sonarr.Api.V3/Indexers/IndexerModule.cs index ec32cfecc..54ed1a778 100644 --- a/src/Sonarr.Api.V3/Indexers/IndexerModule.cs +++ b/src/Sonarr.Api.V3/Indexers/IndexerModule.cs @@ -11,4 +11,4 @@ public IndexerModule(IndexerFactory indexerFactory) { } } -} \ No newline at end of file +} diff --git a/src/Sonarr.Api.V3/Indexers/IndexerResource.cs b/src/Sonarr.Api.V3/Indexers/IndexerResource.cs index 04abbc73e..decb25806 100644 --- a/src/Sonarr.Api.V3/Indexers/IndexerResource.cs +++ b/src/Sonarr.Api.V3/Indexers/IndexerResource.cs @@ -19,7 +19,10 @@ public class IndexerResourceMapper : ProviderResourceMapper<IndexerResource, Ind { public override IndexerResource ToResource(IndexerDefinition definition) { - if (definition == null) return null; + if (definition == null) + { + return null; + } var resource = base.ToResource(definition); @@ -38,7 +41,10 @@ public override IndexerResource ToResource(IndexerDefinition definition) public override IndexerDefinition ToModel(IndexerResource resource) { - if (resource == null) return null; + if (resource == null) + { + return null; + } var definition = base.ToModel(resource); diff --git a/src/Sonarr.Api.V3/Indexers/ReleaseModule.cs b/src/Sonarr.Api.V3/Indexers/ReleaseModule.cs index 6d4b90ec3..abce3b4a7 100644 --- a/src/Sonarr.Api.V3/Indexers/ReleaseModule.cs +++ b/src/Sonarr.Api.V3/Indexers/ReleaseModule.cs @@ -45,8 +45,8 @@ public ReleaseModule(IFetchAndParseRss rssFetcherAndParser, ICacheManager cacheManager, ILanguageProfileService languageProfileService, IQualityProfileService qualityProfileService, - Logger logger) : - base(languageProfileService, qualityProfileService) + Logger logger) + : base(languageProfileService, qualityProfileService) { _rssFetcherAndParser = rssFetcherAndParser; _releaseSearchService = releaseSearchService; @@ -115,7 +115,7 @@ private object DownloadRelease(ReleaseResource release) { var episode = _episodeService.GetEpisode(release.EpisodeId.Value); - episodes = new List<Episode>{episode}; + episodes = new List<Episode> { episode }; } remoteEpisode.Episodes = episodes; diff --git a/src/Sonarr.Api.V3/Indexers/ReleaseModuleBase.cs b/src/Sonarr.Api.V3/Indexers/ReleaseModuleBase.cs index 605861557..7c1eb1907 100644 --- a/src/Sonarr.Api.V3/Indexers/ReleaseModuleBase.cs +++ b/src/Sonarr.Api.V3/Indexers/ReleaseModuleBase.cs @@ -8,14 +8,14 @@ namespace Sonarr.Api.V3.Indexers { public abstract class ReleaseModuleBase : SonarrRestModule<ReleaseResource> { - private readonly LanguageProfile LANGUAGE_PROFILE; - private readonly QualityProfile QUALITY_PROFILE; + private readonly LanguageProfile _languageProfile; + private readonly QualityProfile _qualityProfile; public ReleaseModuleBase(ILanguageProfileService languageProfileService, IQualityProfileService qualityProfileService) { - LANGUAGE_PROFILE = languageProfileService.GetDefaultProfile(string.Empty); - QUALITY_PROFILE = qualityProfileService.GetDefaultProfile(string.Empty); + _languageProfile = languageProfileService.GetDefaultProfile(string.Empty); + _qualityProfile = qualityProfileService.GetDefaultProfile(string.Empty); } protected virtual List<ReleaseResource> MapDecisions(IEnumerable<DownloadDecision> decisions) @@ -38,8 +38,8 @@ protected virtual ReleaseResource MapDecision(DownloadDecision decision, int ini release.ReleaseWeight = initialWeight; - release.QualityWeight = QUALITY_PROFILE.GetIndex(release.Quality.Quality).Index * 100; - release.LanguageWeight = LANGUAGE_PROFILE.Languages.FindIndex(v => v.Language == release.Language) * 100; + release.QualityWeight = _qualityProfile.GetIndex(release.Quality.Quality).Index * 100; + release.LanguageWeight = _languageProfile.Languages.FindIndex(v => v.Language == release.Language) * 100; release.QualityWeight += release.Quality.Revision.Real * 10; release.QualityWeight += release.Quality.Revision.Version; diff --git a/src/Sonarr.Api.V3/Indexers/ReleasePushModule.cs b/src/Sonarr.Api.V3/Indexers/ReleasePushModule.cs index 40adf837c..f832c7412 100644 --- a/src/Sonarr.Api.V3/Indexers/ReleasePushModule.cs +++ b/src/Sonarr.Api.V3/Indexers/ReleasePushModule.cs @@ -1,4 +1,4 @@ -using System.Collections.Generic; +using System.Collections.Generic; using System.Linq; using FluentValidation; using FluentValidation.Results; @@ -26,8 +26,8 @@ public ReleasePushModule(IMakeDownloadDecision downloadDecisionMaker, IIndexerFactory indexerFactory, ILanguageProfileService languageProfileService, IQualityProfileService qualityProfileService, - Logger logger) : - base(languageProfileService, qualityProfileService) + Logger logger) + : base(languageProfileService, qualityProfileService) { _downloadDecisionMaker = downloadDecisionMaker; _downloadDecisionProcessor = downloadDecisionProcessor; @@ -59,10 +59,10 @@ private object ProcessRelease(ReleaseResource release) if (firstDecision?.RemoteEpisode.ParsedEpisodeInfo == null) { - throw new ValidationException(new List<ValidationFailure>{ new ValidationFailure("Title", "Unable to parse", release.Title) }); + throw new ValidationException(new List<ValidationFailure> { new ValidationFailure("Title", "Unable to parse", release.Title) }); } - return MapDecisions(new [] { firstDecision }); + return MapDecisions(new[] { firstDecision }); } private void ResolveIndexer(ReleaseInfo release) diff --git a/src/Sonarr.Api.V3/Indexers/ReleaseResource.cs b/src/Sonarr.Api.V3/Indexers/ReleaseResource.cs index 8b2e21e19..ecd276b5d 100644 --- a/src/Sonarr.Api.V3/Indexers/ReleaseResource.cs +++ b/src/Sonarr.Api.V3/Indexers/ReleaseResource.cs @@ -69,10 +69,12 @@ public class ReleaseResource : RestResource // Sent when queuing an unknown release [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + // [JsonIgnore] public int? SeriesId { get; set; } [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + // [JsonIgnore] public int? EpisodeId { get; set; } } @@ -91,6 +93,7 @@ public static ReleaseResource ToResource(this DownloadDecision model) { Guid = releaseInfo.Guid, Quality = parsedEpisodeInfo.Quality, + //QualityWeight Age = releaseInfo.Age, AgeHours = releaseInfo.AgeHours, @@ -123,6 +126,7 @@ public static ReleaseResource ToResource(this DownloadDecision model) InfoUrl = releaseInfo.InfoUrl, EpisodeRequested = remoteEpisode.EpisodeRequested, DownloadAllowed = remoteEpisode.DownloadAllowed, + //ReleaseWeight PreferredWordScore = remoteEpisode.PreferredWordScore, SceneMapping = remoteEpisode.SceneMapping.ToResource(), @@ -138,7 +142,6 @@ public static ReleaseResource ToResource(this DownloadDecision model) IsPossibleSpecialEpisode = parsedEpisodeInfo.IsPossibleSpecialEpisode, Special = parsedEpisodeInfo.Special, }; - } public static ReleaseInfo ToModel(this ReleaseResource resource) diff --git a/src/Sonarr.Api.V3/Logs/LogFileModule.cs b/src/Sonarr.Api.V3/Logs/LogFileModule.cs index 549d1b595..83441c792 100644 --- a/src/Sonarr.Api.V3/Logs/LogFileModule.cs +++ b/src/Sonarr.Api.V3/Logs/LogFileModule.cs @@ -38,6 +38,5 @@ protected override string DownloadUrlRoot return "logfile"; } } - } -} \ No newline at end of file +} diff --git a/src/Sonarr.Api.V3/Logs/LogFileModuleBase.cs b/src/Sonarr.Api.V3/Logs/LogFileModuleBase.cs index 06abcd840..95ae0dd23 100644 --- a/src/Sonarr.Api.V3/Logs/LogFileModuleBase.cs +++ b/src/Sonarr.Api.V3/Logs/LogFileModuleBase.cs @@ -38,7 +38,7 @@ private List<LogFileResource> GetLogFilesResponse() { var file = files[i]; var filename = Path.GetFileName(file); - + result.Add(new LogFileResource { Id = i + 1, @@ -57,10 +57,12 @@ private object GetLogFileResponse(string filename) var filePath = GetLogFilePath(filename); if (!_diskProvider.FileExists(filePath)) + { return new NotFoundResponse(); + } var data = _diskProvider.ReadAllText(filePath); - + return new TextResponse(data); } @@ -69,4 +71,4 @@ private object GetLogFileResponse(string filename) protected abstract string DownloadUrlRoot { get; } } -} \ No newline at end of file +} diff --git a/src/Sonarr.Api.V3/Logs/LogResource.cs b/src/Sonarr.Api.V3/Logs/LogResource.cs index 86d835dfc..cf54af99d 100644 --- a/src/Sonarr.Api.V3/Logs/LogResource.cs +++ b/src/Sonarr.Api.V3/Logs/LogResource.cs @@ -19,7 +19,10 @@ public static class LogResourceMapper { public static LogResource ToResource(this Log model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new LogResource { diff --git a/src/Sonarr.Api.V3/Logs/UpdateLogFileModule.cs b/src/Sonarr.Api.V3/Logs/UpdateLogFileModule.cs index 0b39844bc..a9537f85b 100644 --- a/src/Sonarr.Api.V3/Logs/UpdateLogFileModule.cs +++ b/src/Sonarr.Api.V3/Logs/UpdateLogFileModule.cs @@ -25,7 +25,10 @@ public UpdateLogFileModule(IAppFolderInfo appFolderInfo, protected override IEnumerable<string> GetLogFiles() { - if (!_diskProvider.FolderExists(_appFolderInfo.GetUpdateLogFolder())) return Enumerable.Empty<string>(); + if (!_diskProvider.FolderExists(_appFolderInfo.GetUpdateLogFolder())) + { + return Enumerable.Empty<string>(); + } return _diskProvider.GetFiles(_appFolderInfo.GetUpdateLogFolder(), SearchOption.TopDirectoryOnly) .Where(f => Regex.IsMatch(Path.GetFileName(f), LOGFILE_ROUTE.TrimStart('/'), RegexOptions.IgnoreCase)) @@ -45,4 +48,4 @@ protected override string DownloadUrlRoot } } } -} \ No newline at end of file +} diff --git a/src/Sonarr.Api.V3/ManualImport/ManualImportModule.cs b/src/Sonarr.Api.V3/ManualImport/ManualImportModule.cs index 0c754be1c..cd23cfab8 100644 --- a/src/Sonarr.Api.V3/ManualImport/ManualImportModule.cs +++ b/src/Sonarr.Api.V3/ManualImport/ManualImportModule.cs @@ -82,7 +82,7 @@ private ManualImportResource AddQualityWeight(ManualImportResource item) item.QualityWeight += item.Quality.Revision.Real * 10; item.QualityWeight += item.Quality.Revision.Version; } - + return item; } } diff --git a/src/Sonarr.Api.V3/ManualImport/ManualImportResource.cs b/src/Sonarr.Api.V3/ManualImport/ManualImportResource.cs index d11c0e0a4..2c170430a 100644 --- a/src/Sonarr.Api.V3/ManualImport/ManualImportResource.cs +++ b/src/Sonarr.Api.V3/ManualImport/ManualImportResource.cs @@ -34,7 +34,10 @@ public static class ManualImportResourceMapper { public static ManualImportResource ToResource(this ManualImportItem model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new ManualImportResource { @@ -51,6 +54,7 @@ public static ManualImportResource ToResource(this ManualImportItem model) ReleaseGroup = model.ReleaseGroup, Quality = model.Quality, Language = model.Language, + //QualityWeight DownloadId = model.DownloadId, Rejections = model.Rejections diff --git a/src/Sonarr.Api.V3/MediaCovers/MediaCoverModule.cs b/src/Sonarr.Api.V3/MediaCovers/MediaCoverModule.cs index eff113f21..efe4848ea 100644 --- a/src/Sonarr.Api.V3/MediaCovers/MediaCoverModule.cs +++ b/src/Sonarr.Api.V3/MediaCovers/MediaCoverModule.cs @@ -1,4 +1,4 @@ -using System.IO; +using System.IO; using System.Text.RegularExpressions; using Nancy; using Nancy.Responses; @@ -10,14 +10,15 @@ namespace Sonarr.Api.V3.MediaCovers { public class MediaCoverModule : SonarrV3Module { - private static readonly Regex RegexResizedImage = new Regex(@"-\d+\.jpg$", RegexOptions.Compiled | RegexOptions.IgnoreCase); - private const string MEDIA_COVER_ROUTE = @"/(?<seriesId>\d+)/(?<filename>(.+)\.(jpg|png|gif))"; + private static readonly Regex RegexResizedImage = new Regex(@"-\d+\.jpg$", RegexOptions.Compiled | RegexOptions.IgnoreCase); + private readonly IAppFolderInfo _appFolderInfo; private readonly IDiskProvider _diskProvider; - public MediaCoverModule(IAppFolderInfo appFolderInfo, IDiskProvider diskProvider) : base("MediaCover") + public MediaCoverModule(IAppFolderInfo appFolderInfo, IDiskProvider diskProvider) + : base("MediaCover") { _appFolderInfo = appFolderInfo; _diskProvider = diskProvider; @@ -38,6 +39,7 @@ private object GetMediaCover(int seriesId, string filename) { return new NotFoundResponse(); } + filePath = basefilePath; } diff --git a/src/Sonarr.Api.V3/Metadata/MetadataModule.cs b/src/Sonarr.Api.V3/Metadata/MetadataModule.cs index 9cc8e8988..a2ec54177 100644 --- a/src/Sonarr.Api.V3/Metadata/MetadataModule.cs +++ b/src/Sonarr.Api.V3/Metadata/MetadataModule.cs @@ -11,4 +11,4 @@ public MetadataModule(IMetadataFactory metadataFactory) { } } -} \ No newline at end of file +} diff --git a/src/Sonarr.Api.V3/Metadata/MetadataResource.cs b/src/Sonarr.Api.V3/Metadata/MetadataResource.cs index 4a1faa20c..eaaec0eb0 100644 --- a/src/Sonarr.Api.V3/Metadata/MetadataResource.cs +++ b/src/Sonarr.Api.V3/Metadata/MetadataResource.cs @@ -11,7 +11,10 @@ public class MetadataResourceMapper : ProviderResourceMapper<MetadataResource, M { public override MetadataResource ToResource(MetadataDefinition definition) { - if (definition == null) return null; + if (definition == null) + { + return null; + } var resource = base.ToResource(definition); @@ -22,7 +25,10 @@ public override MetadataResource ToResource(MetadataDefinition definition) public override MetadataDefinition ToModel(MetadataResource resource) { - if (resource == null) return null; + if (resource == null) + { + return null; + } var definition = base.ToModel(resource); @@ -31,4 +37,4 @@ public override MetadataDefinition ToModel(MetadataResource resource) return definition; } } -} \ No newline at end of file +} diff --git a/src/Sonarr.Api.V3/Notifications/NotificationModule.cs b/src/Sonarr.Api.V3/Notifications/NotificationModule.cs index f2dde4aca..e6ed91b0c 100644 --- a/src/Sonarr.Api.V3/Notifications/NotificationModule.cs +++ b/src/Sonarr.Api.V3/Notifications/NotificationModule.cs @@ -11,4 +11,4 @@ public NotificationModule(NotificationFactory notificationFactory) { } } -} \ No newline at end of file +} diff --git a/src/Sonarr.Api.V3/Notifications/NotificationResource.cs b/src/Sonarr.Api.V3/Notifications/NotificationResource.cs index 5e47ee68b..fae38ac7a 100644 --- a/src/Sonarr.Api.V3/Notifications/NotificationResource.cs +++ b/src/Sonarr.Api.V3/Notifications/NotificationResource.cs @@ -31,7 +31,10 @@ public class NotificationResourceMapper : ProviderResourceMapper<NotificationRes { public override NotificationResource ToResource(NotificationDefinition definition) { - if (definition == null) return default(NotificationResource); + if (definition == null) + { + return default(NotificationResource); + } var resource = base.ToResource(definition); @@ -60,7 +63,10 @@ public override NotificationResource ToResource(NotificationDefinition definitio public override NotificationDefinition ToModel(NotificationResource resource) { - if (resource == null) return default(NotificationDefinition); + if (resource == null) + { + return default(NotificationDefinition); + } var definition = base.ToModel(resource); @@ -87,4 +93,4 @@ public override NotificationDefinition ToModel(NotificationResource resource) return definition; } } -} \ No newline at end of file +} diff --git a/src/Sonarr.Api.V3/Parse/ParseModule.cs b/src/Sonarr.Api.V3/Parse/ParseModule.cs index e6e65be78..b036bf759 100644 --- a/src/Sonarr.Api.V3/Parse/ParseModule.cs +++ b/src/Sonarr.Api.V3/Parse/ParseModule.cs @@ -60,4 +60,4 @@ private ParseResource Parse() } } } -} \ No newline at end of file +} diff --git a/src/Sonarr.Api.V3/Parse/ParseResource.cs b/src/Sonarr.Api.V3/Parse/ParseResource.cs index 8dc8b9cc7..131b75442 100644 --- a/src/Sonarr.Api.V3/Parse/ParseResource.cs +++ b/src/Sonarr.Api.V3/Parse/ParseResource.cs @@ -13,4 +13,4 @@ public class ParseResource : RestResource public SeriesResource Series { get; set; } public List<EpisodeResource> Episodes { get; set; } } -} \ No newline at end of file +} diff --git a/src/Sonarr.Api.V3/Profiles/Delay/DelayProfileModule.cs b/src/Sonarr.Api.V3/Profiles/Delay/DelayProfileModule.cs index bb6499e7e..007d46220 100644 --- a/src/Sonarr.Api.V3/Profiles/Delay/DelayProfileModule.cs +++ b/src/Sonarr.Api.V3/Profiles/Delay/DelayProfileModule.cs @@ -83,4 +83,4 @@ private object Reorder(int id) return _delayProfileService.Reorder(id, afterId).ToResource(); } } -} \ No newline at end of file +} diff --git a/src/Sonarr.Api.V3/Profiles/Delay/DelayProfileResource.cs b/src/Sonarr.Api.V3/Profiles/Delay/DelayProfileResource.cs index fb83debe5..f2e2f38a2 100644 --- a/src/Sonarr.Api.V3/Profiles/Delay/DelayProfileResource.cs +++ b/src/Sonarr.Api.V3/Profiles/Delay/DelayProfileResource.cs @@ -22,7 +22,10 @@ public static class DelayProfileResourceMapper { public static DelayProfileResource ToResource(this DelayProfile model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new DelayProfileResource { @@ -41,7 +44,10 @@ public static DelayProfileResource ToResource(this DelayProfile model) public static DelayProfile ToModel(this DelayProfileResource resource) { - if (resource == null) return null; + if (resource == null) + { + return null; + } return new DelayProfile { diff --git a/src/Sonarr.Api.V3/Profiles/Language/LanguageProfileModule.cs b/src/Sonarr.Api.V3/Profiles/Language/LanguageProfileModule.cs index b424e724e..fd25e342c 100644 --- a/src/Sonarr.Api.V3/Profiles/Language/LanguageProfileModule.cs +++ b/src/Sonarr.Api.V3/Profiles/Language/LanguageProfileModule.cs @@ -54,4 +54,4 @@ private List<LanguageProfileResource> GetAll() return profiles; } } -} \ No newline at end of file +} diff --git a/src/Sonarr.Api.V3/Profiles/Language/LanguageProfileResource.cs b/src/Sonarr.Api.V3/Profiles/Language/LanguageProfileResource.cs index cc4293172..a32882eaf 100644 --- a/src/Sonarr.Api.V3/Profiles/Language/LanguageProfileResource.cs +++ b/src/Sonarr.Api.V3/Profiles/Language/LanguageProfileResource.cs @@ -23,7 +23,10 @@ public static class LanguageProfileResourceMapper { public static LanguageProfileResource ToResource(this LanguageProfile model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new LanguageProfileResource { @@ -37,7 +40,10 @@ public static LanguageProfileResource ToResource(this LanguageProfile model) public static LanguageProfileItemResource ToResource(this LanguageProfileItem model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new LanguageProfileItemResource { @@ -48,7 +54,10 @@ public static LanguageProfileItemResource ToResource(this LanguageProfileItem mo public static LanguageProfile ToModel(this LanguageProfileResource resource) { - if (resource == null) return null; + if (resource == null) + { + return null; + } return new LanguageProfile { @@ -62,7 +71,10 @@ public static LanguageProfile ToModel(this LanguageProfileResource resource) public static LanguageProfileItem ToModel(this LanguageProfileItemResource resource) { - if (resource == null) return null; + if (resource == null) + { + return null; + } return new LanguageProfileItem { diff --git a/src/Sonarr.Api.V3/Profiles/Language/LanguageValidator.cs b/src/Sonarr.Api.V3/Profiles/Language/LanguageValidator.cs index ab84b472b..a74724057 100644 --- a/src/Sonarr.Api.V3/Profiles/Language/LanguageValidator.cs +++ b/src/Sonarr.Api.V3/Profiles/Language/LanguageValidator.cs @@ -15,7 +15,6 @@ public static IRuleBuilderOptions<T, IList<LanguageProfileItemResource>> MustHav } } - public class LanguageValidator<T> : PropertyValidator { public LanguageValidator() diff --git a/src/Sonarr.Api.V3/Profiles/Quality/QualityCutoffValidator.cs b/src/Sonarr.Api.V3/Profiles/Quality/QualityCutoffValidator.cs index 86a531315..67bde6196 100644 --- a/src/Sonarr.Api.V3/Profiles/Quality/QualityCutoffValidator.cs +++ b/src/Sonarr.Api.V3/Profiles/Quality/QualityCutoffValidator.cs @@ -18,7 +18,6 @@ public class ValidCutoffValidator<T> : PropertyValidator public ValidCutoffValidator() : base("Cutoff must be an allowed quality or group") { - } protected override bool IsValid(PropertyValidatorContext context) @@ -29,9 +28,15 @@ protected override bool IsValid(PropertyValidatorContext context) var cutoffItem = items.SingleOrDefault(i => (i.Quality == null && i.Id == cutoff) || i.Quality?.Id == cutoff); - if (cutoffItem == null) return false; + if (cutoffItem == null) + { + return false; + } - if (!cutoffItem.Allowed) return false; + if (!cutoffItem.Allowed) + { + return false; + } return true; } diff --git a/src/Sonarr.Api.V3/Profiles/Quality/QualityItemsValidator.cs b/src/Sonarr.Api.V3/Profiles/Quality/QualityItemsValidator.cs index 940435b3a..3de76a16a 100644 --- a/src/Sonarr.Api.V3/Profiles/Quality/QualityItemsValidator.cs +++ b/src/Sonarr.Api.V3/Profiles/Quality/QualityItemsValidator.cs @@ -26,7 +26,6 @@ public class AllowedValidator<T> : PropertyValidator public AllowedValidator() : base("Must contain at least one allowed quality") { - } protected override bool IsValid(PropertyValidatorContext context) @@ -52,7 +51,6 @@ public class GroupItemValidator<T> : PropertyValidator public GroupItemValidator() : base("Groups must contain multiple qualities") { - } protected override bool IsValid(PropertyValidatorContext context) @@ -73,7 +71,6 @@ public class QualityNameValidator<T> : PropertyValidator public QualityNameValidator() : base("Individual qualities should not be named") { - } protected override bool IsValid(PropertyValidatorContext context) @@ -94,7 +91,6 @@ public class ItemGroupNameValidator<T> : PropertyValidator public ItemGroupNameValidator() : base("Groups must have a name") { - } protected override bool IsValid(PropertyValidatorContext context) @@ -115,7 +111,6 @@ public class ItemGroupIdValidator<T> : PropertyValidator public ItemGroupIdValidator() : base("Groups must have an ID") { - } protected override bool IsValid(PropertyValidatorContext context) @@ -136,7 +131,6 @@ public class UniqueIdValidator<T> : PropertyValidator public UniqueIdValidator() : base("Groups must have a unique ID") { - } protected override bool IsValid(PropertyValidatorContext context) @@ -157,7 +151,6 @@ public class UniqueQualityIdValidator<T> : PropertyValidator public UniqueQualityIdValidator() : base("Qualities can only be used once") { - } protected override bool IsValid(PropertyValidatorContext context) @@ -179,7 +172,6 @@ protected override bool IsValid(PropertyValidatorContext context) qualityIds.Add(quality.Quality.Id); } } - else { if (qualityIds.Contains(item.Quality.Id)) diff --git a/src/Sonarr.Api.V3/Profiles/Quality/QualityProfileModule.cs b/src/Sonarr.Api.V3/Profiles/Quality/QualityProfileModule.cs index 618438292..4617c5d1a 100644 --- a/src/Sonarr.Api.V3/Profiles/Quality/QualityProfileModule.cs +++ b/src/Sonarr.Api.V3/Profiles/Quality/QualityProfileModule.cs @@ -52,4 +52,4 @@ private List<QualityProfileResource> GetAll() return _qualityProfileService.All().ToResource(); } } -} \ No newline at end of file +} diff --git a/src/Sonarr.Api.V3/Profiles/Quality/QualityProfileResource.cs b/src/Sonarr.Api.V3/Profiles/Quality/QualityProfileResource.cs index 581bc23c2..d9323c657 100644 --- a/src/Sonarr.Api.V3/Profiles/Quality/QualityProfileResource.cs +++ b/src/Sonarr.Api.V3/Profiles/Quality/QualityProfileResource.cs @@ -30,7 +30,10 @@ public static class ProfileResourceMapper { public static QualityProfileResource ToResource(this QualityProfile model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new QualityProfileResource { @@ -44,7 +47,10 @@ public static QualityProfileResource ToResource(this QualityProfile model) public static QualityProfileQualityItemResource ToResource(this QualityProfileQualityItem model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new QualityProfileQualityItemResource { @@ -58,7 +64,10 @@ public static QualityProfileQualityItemResource ToResource(this QualityProfileQu public static QualityProfile ToModel(this QualityProfileResource resource) { - if (resource == null) return null; + if (resource == null) + { + return null; + } return new QualityProfile { @@ -72,7 +81,10 @@ public static QualityProfile ToModel(this QualityProfileResource resource) public static QualityProfileQualityItem ToModel(this QualityProfileQualityItemResource resource) { - if (resource == null) return null; + if (resource == null) + { + return null; + } return new QualityProfileQualityItem { diff --git a/src/Sonarr.Api.V3/Profiles/Release/ReleaseProfileModule.cs b/src/Sonarr.Api.V3/Profiles/Release/ReleaseProfileModule.cs index 1248e697f..d4af789b9 100644 --- a/src/Sonarr.Api.V3/Profiles/Release/ReleaseProfileModule.cs +++ b/src/Sonarr.Api.V3/Profiles/Release/ReleaseProfileModule.cs @@ -13,7 +13,6 @@ public class ReleaseProfileModule : SonarrRestModule<ReleaseProfileResource> private readonly IReleaseProfileService _releaseProfileService; private readonly IIndexerFactory _indexerFactory; - public ReleaseProfileModule(IReleaseProfileService releaseProfileService, IIndexerFactory indexerFactory) { _releaseProfileService = releaseProfileService; diff --git a/src/Sonarr.Api.V3/Profiles/Release/ReleaseProfileResource.cs b/src/Sonarr.Api.V3/Profiles/Release/ReleaseProfileResource.cs index 1029dfbd7..795378ef9 100644 --- a/src/Sonarr.Api.V3/Profiles/Release/ReleaseProfileResource.cs +++ b/src/Sonarr.Api.V3/Profiles/Release/ReleaseProfileResource.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Linq; -using Newtonsoft.Json; using Newtonsoft.Json.Linq; using NzbDrone.Core.Profiles.Releases; using Sonarr.Http.REST; @@ -12,6 +11,7 @@ public class ReleaseProfileResource : RestResource { public string Name { get; set; } public bool Enabled { get; set; } + // Is List<string>, string or JArray, we accept 'string' with POST for backward compatibility public object Required { get; set; } public object Ignored { get; set; } @@ -31,7 +31,10 @@ public static class RestrictionResourceMapper { public static ReleaseProfileResource ToResource(this ReleaseProfile model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new ReleaseProfileResource { @@ -49,7 +52,10 @@ public static ReleaseProfileResource ToResource(this ReleaseProfile model) public static ReleaseProfile ToModel(this ReleaseProfileResource resource) { - if (resource == null) return null; + if (resource == null) + { + return null; + } return new ReleaseProfile { @@ -72,7 +78,7 @@ public static List<ReleaseProfileResource> ToResource(this IEnumerable<ReleasePr public static List<string> MapRequired(this ReleaseProfileResource profile) => ParseArray(profile.Required, "required"); public static List<string> MapIgnored(this ReleaseProfileResource profile) => ParseArray(profile.Ignored, "ignored"); - + private static List<string> ParseArray(object resource, string title) { if (resource == null) diff --git a/src/Sonarr.Api.V3/ProviderModuleBase.cs b/src/Sonarr.Api.V3/ProviderModuleBase.cs index e57bbe80d..3b1eec76c 100644 --- a/src/Sonarr.Api.V3/ProviderModuleBase.cs +++ b/src/Sonarr.Api.V3/ProviderModuleBase.cs @@ -37,7 +37,7 @@ protected ProviderModuleBase(IProviderFactory<TProvider, TProviderDefinition> pr DeleteResource = DeleteProvider; SharedValidator.RuleFor(c => c.Name).NotEmpty(); - SharedValidator.RuleFor(c => c.Name).Must((v,c) => !_providerFactory.All().Any(p => p.Name == c && p.Id != v.Id)).WithMessage("Should be unique"); + SharedValidator.RuleFor(c => c.Name).Must((v, c) => !_providerFactory.All().Any(p => p.Name == c && p.Id != v.Id)).WithMessage("Should be unique"); SharedValidator.RuleFor(c => c.Implementation).NotEmpty(); SharedValidator.RuleFor(c => c.ConfigContract).NotEmpty(); diff --git a/src/Sonarr.Api.V3/ProviderResource.cs b/src/Sonarr.Api.V3/ProviderResource.cs index aac54e2a3..d7f9672b0 100644 --- a/src/Sonarr.Api.V3/ProviderResource.cs +++ b/src/Sonarr.Api.V3/ProviderResource.cs @@ -25,7 +25,6 @@ public class ProviderResourceMapper<TProviderResource, TProviderDefinition> where TProviderDefinition : ProviderDefinition, new() { public virtual TProviderResource ToResource(TProviderDefinition definition) - { return new TProviderResource { @@ -45,7 +44,10 @@ public virtual TProviderResource ToResource(TProviderDefinition definition) public virtual TProviderDefinition ToModel(TProviderResource resource) { - if (resource == null) return default(TProviderDefinition); + if (resource == null) + { + return default(TProviderDefinition); + } var definition = new TProviderDefinition { @@ -65,4 +67,4 @@ public virtual TProviderDefinition ToModel(TProviderResource resource) return definition; } } -} \ No newline at end of file +} diff --git a/src/Sonarr.Api.V3/Qualities/QualityDefinitionModule.cs b/src/Sonarr.Api.V3/Qualities/QualityDefinitionModule.cs index f83e226aa..e6cec4c1b 100644 --- a/src/Sonarr.Api.V3/Qualities/QualityDefinitionModule.cs +++ b/src/Sonarr.Api.V3/Qualities/QualityDefinitionModule.cs @@ -51,8 +51,8 @@ private object UpdateMany() _qualityDefinitionService.UpdateMany(qualityDefinitions); return ResponseWithCode(_qualityDefinitionService.All() - .ToResource() - , HttpStatusCode.Accepted); + .ToResource(), + HttpStatusCode.Accepted); } public void Handle(CommandExecutedEvent message) @@ -63,4 +63,4 @@ public void Handle(CommandExecutedEvent message) } } } -} \ No newline at end of file +} diff --git a/src/Sonarr.Api.V3/Qualities/QualityDefinitionResource.cs b/src/Sonarr.Api.V3/Qualities/QualityDefinitionResource.cs index 85c5310a6..01c618917 100644 --- a/src/Sonarr.Api.V3/Qualities/QualityDefinitionResource.cs +++ b/src/Sonarr.Api.V3/Qualities/QualityDefinitionResource.cs @@ -21,7 +21,10 @@ public static class QualityDefinitionResourceMapper { public static QualityDefinitionResource ToResource(this QualityDefinition model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new QualityDefinitionResource { @@ -36,7 +39,10 @@ public static QualityDefinitionResource ToResource(this QualityDefinition model) public static QualityDefinition ToModel(this QualityDefinitionResource resource) { - if (resource == null) return null; + if (resource == null) + { + return null; + } return new QualityDefinition { @@ -59,4 +65,4 @@ public static List<QualityDefinition> ToModel(this IEnumerable<QualityDefinition return resources.Select(ToModel).ToList(); } } -} \ No newline at end of file +} diff --git a/src/Sonarr.Api.V3/Queue/QueueActionModule.cs b/src/Sonarr.Api.V3/Queue/QueueActionModule.cs index 5048c6e8f..ed6ed6e8a 100644 --- a/src/Sonarr.Api.V3/Queue/QueueActionModule.cs +++ b/src/Sonarr.Api.V3/Queue/QueueActionModule.cs @@ -163,7 +163,7 @@ private TrackedDownload Remove(int id, bool removeFromClient, bool blocklist) { _failedDownloadService.MarkAsFailed(trackedDownload.DownloadItem.DownloadId); } - + if (!removeFromClient && !blocklist) { if (!_ignoredDownloadService.IgnoreDownload(trackedDownload)) diff --git a/src/Sonarr.Api.V3/Queue/QueueModule.cs b/src/Sonarr.Api.V3/Queue/QueueModule.cs index e2c9839c4..a20b2d6c7 100644 --- a/src/Sonarr.Api.V3/Queue/QueueModule.cs +++ b/src/Sonarr.Api.V3/Queue/QueueModule.cs @@ -22,8 +22,8 @@ public class QueueModule : SonarrRestModuleWithSignalR<QueueResource, NzbDrone.C private readonly IQueueService _queueService; private readonly IPendingReleaseService _pendingReleaseService; - private readonly LanguageComparer LANGUAGE_COMPARER; - private readonly QualityModelComparer QUALITY_COMPARER; + private readonly LanguageComparer _languageComparer; + private readonly QualityModelComparer _qualityComparer; public QueueModule(IBroadcastSignalRMessage broadcastSignalRMessage, IQueueService queueService, @@ -36,8 +36,8 @@ public QueueModule(IBroadcastSignalRMessage broadcastSignalRMessage, _pendingReleaseService = pendingReleaseService; GetResourcePaged = GetQueue; - LANGUAGE_COMPARER = new LanguageComparer(languageProfileService.GetDefaultProfile(string.Empty)); - QUALITY_COMPARER = new QualityModelComparer(qualityProfileService.GetDefaultProfile(string.Empty)); + _languageComparer = new LanguageComparer(languageProfileService.GetDefaultProfile(string.Empty)); + _qualityComparer = new QualityModelComparer(qualityProfileService.GetDefaultProfile(string.Empty)); } private PagingResource<QueueResource> GetQueue(PagingResource<QueueResource> pagingResource) @@ -68,14 +68,12 @@ private PagingResource<QueueResource> GetQueue(PagingResource<QueueResource> pag : fullQueue.OrderByDescending(q => q.Episode?.SeasonNumber) .ThenByDescending(q => q.Episode?.EpisodeNumber); } - else if (pagingSpec.SortKey == "timeleft") { ordered = ascending ? fullQueue.OrderBy(q => q.Timeleft, new TimeleftComparer()) : fullQueue.OrderByDescending(q => q.Timeleft, new TimeleftComparer()); } - else if (pagingSpec.SortKey == "estimatedCompletionTime") { ordered = ascending @@ -83,48 +81,42 @@ private PagingResource<QueueResource> GetQueue(PagingResource<QueueResource> pag : fullQueue.OrderByDescending(q => q.EstimatedCompletionTime, new EstimatedCompletionTimeComparer()); } - else if (pagingSpec.SortKey == "protocol") { ordered = ascending ? fullQueue.OrderBy(q => q.Protocol) : fullQueue.OrderByDescending(q => q.Protocol); } - else if (pagingSpec.SortKey == "indexer") { ordered = ascending ? fullQueue.OrderBy(q => q.Indexer, StringComparer.InvariantCultureIgnoreCase) : fullQueue.OrderByDescending(q => q.Indexer, StringComparer.InvariantCultureIgnoreCase); } - else if (pagingSpec.SortKey == "downloadClient") { ordered = ascending ? fullQueue.OrderBy(q => q.DownloadClient, StringComparer.InvariantCultureIgnoreCase) : fullQueue.OrderByDescending(q => q.DownloadClient, StringComparer.InvariantCultureIgnoreCase); } - else if (pagingSpec.SortKey == "language") { ordered = ascending - ? fullQueue.OrderBy(q => q.Language, LANGUAGE_COMPARER) - : fullQueue.OrderByDescending(q => q.Language, LANGUAGE_COMPARER); + ? fullQueue.OrderBy(q => q.Language, _languageComparer) + : fullQueue.OrderByDescending(q => q.Language, _languageComparer); } - else if (pagingSpec.SortKey == "quality") { ordered = ascending - ? fullQueue.OrderBy(q => q.Quality, QUALITY_COMPARER) - : fullQueue.OrderByDescending(q => q.Quality, QUALITY_COMPARER); + ? fullQueue.OrderBy(q => q.Quality, _qualityComparer) + : fullQueue.OrderByDescending(q => q.Quality, _qualityComparer); } - else { ordered = ascending ? fullQueue.OrderBy(orderByFunc) : fullQueue.OrderByDescending(orderByFunc); } - ordered = ordered.ThenByDescending(q => q.Size == 0 ? 0 : 100 - q.Sizeleft / q.Size * 100); + ordered = ordered.ThenByDescending(q => q.Size == 0 ? 0 : 100 - (q.Sizeleft / q.Size * 100)); pagingSpec.Records = ordered.Skip((pagingSpec.Page - 1) * pagingSpec.PageSize).Take(pagingSpec.PageSize).ToList(); pagingSpec.TotalRecords = fullQueue.Count; @@ -138,7 +130,7 @@ private PagingResource<QueueResource> GetQueue(PagingResource<QueueResource> pag return pagingSpec; } - private Func<NzbDrone.Core.Queue.Queue, Object> GetOrderByFunc(PagingSpec<NzbDrone.Core.Queue.Queue> pagingSpec) + private Func<NzbDrone.Core.Queue.Queue, object> GetOrderByFunc(PagingSpec<NzbDrone.Core.Queue.Queue> pagingSpec) { switch (pagingSpec.SortKey) { @@ -160,7 +152,7 @@ private PagingResource<QueueResource> GetQueue(PagingResource<QueueResource> pag return q => q.Quality; case "progress": // Avoid exploding if a download's size is 0 - return q => 100 - q.Sizeleft / Math.Max(q.Size * 100, 1); + return q => 100 - (q.Sizeleft / Math.Max(q.Size * 100, 1)); default: return q => q.Timeleft; } diff --git a/src/Sonarr.Api.V3/Queue/QueueResource.cs b/src/Sonarr.Api.V3/Queue/QueueResource.cs index 29cd64fd2..e7879fa88 100644 --- a/src/Sonarr.Api.V3/Queue/QueueResource.cs +++ b/src/Sonarr.Api.V3/Queue/QueueResource.cs @@ -41,7 +41,10 @@ public static class QueueResourceMapper { public static QueueResource ToResource(this NzbDrone.Core.Queue.Queue model, bool includeSeries, bool includeEpisode) { - if (model == null) return null; + if (model == null) + { + return null; + } return new QueueResource { diff --git a/src/Sonarr.Api.V3/Queue/QueueStatusModule.cs b/src/Sonarr.Api.V3/Queue/QueueStatusModule.cs index b86826554..df599b18b 100644 --- a/src/Sonarr.Api.V3/Queue/QueueStatusModule.cs +++ b/src/Sonarr.Api.V3/Queue/QueueStatusModule.cs @@ -18,7 +18,6 @@ public class QueueStatusModule : SonarrRestModuleWithSignalR<QueueStatusResource private readonly IPendingReleaseService _pendingReleaseService; private readonly Debouncer _broadcastDebounce; - public QueueStatusModule(IBroadcastSignalRMessage broadcastSignalRMessage, IQueueService queueService, IPendingReleaseService pendingReleaseService) : base(broadcastSignalRMessage, "queue/status") { @@ -27,7 +26,6 @@ public QueueStatusModule(IBroadcastSignalRMessage broadcastSignalRMessage, IQueu _broadcastDebounce = new Debouncer(BroadcastChange, TimeSpan.FromSeconds(5)); - Get("/", x => GetQueueStatusResponse()); } diff --git a/src/Sonarr.Api.V3/RemotePathMappings/RemotePathMappingModule.cs b/src/Sonarr.Api.V3/RemotePathMappings/RemotePathMappingModule.cs index 1e6bb7f6e..953283b9a 100644 --- a/src/Sonarr.Api.V3/RemotePathMappings/RemotePathMappingModule.cs +++ b/src/Sonarr.Api.V3/RemotePathMappings/RemotePathMappingModule.cs @@ -65,4 +65,4 @@ private void UpdateMapping(RemotePathMappingResource resource) _remotePathMappingService.Update(mapping); } } -} \ No newline at end of file +} diff --git a/src/Sonarr.Api.V3/RemotePathMappings/RemotePathMappingResource.cs b/src/Sonarr.Api.V3/RemotePathMappings/RemotePathMappingResource.cs index c371329d6..fbac795e7 100644 --- a/src/Sonarr.Api.V3/RemotePathMappings/RemotePathMappingResource.cs +++ b/src/Sonarr.Api.V3/RemotePathMappings/RemotePathMappingResource.cs @@ -16,7 +16,10 @@ public static class RemotePathMappingResourceMapper { public static RemotePathMappingResource ToResource(this RemotePathMapping model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new RemotePathMappingResource { @@ -30,7 +33,10 @@ public static RemotePathMappingResource ToResource(this RemotePathMapping model) public static RemotePathMapping ToModel(this RemotePathMappingResource resource) { - if (resource == null) return null; + if (resource == null) + { + return null; + } return new RemotePathMapping { diff --git a/src/Sonarr.Api.V3/RootFolders/RootFolderModule.cs b/src/Sonarr.Api.V3/RootFolders/RootFolderModule.cs index 78ca10a81..54dff8599 100644 --- a/src/Sonarr.Api.V3/RootFolders/RootFolderModule.cs +++ b/src/Sonarr.Api.V3/RootFolders/RootFolderModule.cs @@ -20,8 +20,7 @@ public RootFolderModule(IRootFolderService rootFolderService, MappedNetworkDriveValidator mappedNetworkDriveValidator, StartupFolderValidator startupFolderValidator, SystemFolderValidator systemFolderValidator, - FolderWritableValidator folderWritableValidator - ) + FolderWritableValidator folderWritableValidator) : base(signalRBroadcaster) { _rootFolderService = rootFolderService; diff --git a/src/Sonarr.Api.V3/RootFolders/RootFolderResource.cs b/src/Sonarr.Api.V3/RootFolders/RootFolderResource.cs index babae02cb..e4a9068c8 100644 --- a/src/Sonarr.Api.V3/RootFolders/RootFolderResource.cs +++ b/src/Sonarr.Api.V3/RootFolders/RootFolderResource.cs @@ -19,7 +19,10 @@ public static class RootFolderResourceMapper { public static RootFolderResource ToResource(this RootFolder model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new RootFolderResource { @@ -34,13 +37,17 @@ public static RootFolderResource ToResource(this RootFolder model) public static RootFolder ToModel(this RootFolderResource resource) { - if (resource == null) return null; + if (resource == null) + { + return null; + } return new RootFolder { Id = resource.Id, Path = resource.Path + //Accessible //FreeSpace //UnmappedFolders @@ -52,4 +59,4 @@ public static List<RootFolderResource> ToResource(this IEnumerable<RootFolder> m return models.Select(ToResource).ToList(); } } -} \ No newline at end of file +} diff --git a/src/Sonarr.Api.V3/Series/SeasonResource.cs b/src/Sonarr.Api.V3/Series/SeasonResource.cs index 6030a5618..4826fd8ba 100644 --- a/src/Sonarr.Api.V3/Series/SeasonResource.cs +++ b/src/Sonarr.Api.V3/Series/SeasonResource.cs @@ -17,7 +17,10 @@ public static class SeasonResourceMapper { public static SeasonResource ToResource(this Season model, bool includeImages = false) { - if (model == null) return null; + if (model == null) + { + return null; + } return new SeasonResource { @@ -29,7 +32,10 @@ public static SeasonResource ToResource(this Season model, bool includeImages = public static Season ToModel(this SeasonResource resource) { - if (resource == null) return null; + if (resource == null) + { + return null; + } return new Season { diff --git a/src/Sonarr.Api.V3/Series/SeasonStatisticsResource.cs b/src/Sonarr.Api.V3/Series/SeasonStatisticsResource.cs index e482cd12a..02b8eddf4 100644 --- a/src/Sonarr.Api.V3/Series/SeasonStatisticsResource.cs +++ b/src/Sonarr.Api.V3/Series/SeasonStatisticsResource.cs @@ -18,7 +18,10 @@ public decimal PercentOfEpisodes { get { - if (EpisodeCount == 0) return 0; + if (EpisodeCount == 0) + { + return 0; + } return (decimal)EpisodeFileCount / (decimal)EpisodeCount * 100; } @@ -29,7 +32,10 @@ public static class SeasonStatisticsResourceMapper { public static SeasonStatisticsResource ToResource(this SeasonStatistics model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new SeasonStatisticsResource { diff --git a/src/Sonarr.Api.V3/Series/SeriesEditorModule.cs b/src/Sonarr.Api.V3/Series/SeriesEditorModule.cs index c50f50774..318907ac9 100644 --- a/src/Sonarr.Api.V3/Series/SeriesEditorModule.cs +++ b/src/Sonarr.Api.V3/Series/SeriesEditorModule.cs @@ -48,7 +48,7 @@ private object SaveAll() if (resource.SeriesType.HasValue) { - series.SeriesType = resource.SeriesType.Value; + series.SeriesType = resource.SeriesType.Value; } if (resource.SeasonFolder.HasValue) @@ -96,8 +96,8 @@ private object SaveAll() } return ResponseWithCode(_seriesService.UpdateSeries(seriesToUpdate, !resource.MoveFiles) - .ToResource() - , HttpStatusCode.Accepted); + .ToResource(), + HttpStatusCode.Accepted); } private object DeleteSeries() diff --git a/src/Sonarr.Api.V3/Series/SeriesFolderAsRootFolderValidator.cs b/src/Sonarr.Api.V3/Series/SeriesFolderAsRootFolderValidator.cs index 7d433e756..45d110a87 100644 --- a/src/Sonarr.Api.V3/Series/SeriesFolderAsRootFolderValidator.cs +++ b/src/Sonarr.Api.V3/Series/SeriesFolderAsRootFolderValidator.cs @@ -18,21 +18,33 @@ public SeriesFolderAsRootFolderValidator(IBuildFileNames fileNameBuilder) protected override bool IsValid(PropertyValidatorContext context) { - if (context.PropertyValue == null) return true; + if (context.PropertyValue == null) + { + return true; + } var seriesResource = context.Instance as SeriesResource; - if (seriesResource == null) return true; + if (seriesResource == null) + { + return true; + } var rootFolderPath = context.PropertyValue.ToString(); - if (rootFolderPath.IsNullOrWhiteSpace()) return true; + if (rootFolderPath.IsNullOrWhiteSpace()) + { + return true; + } var rootFolder = new DirectoryInfo(rootFolderPath).Name; var series = seriesResource.ToModel(); var seriesFolder = _fileNameBuilder.GetSeriesFolder(series); - if (seriesFolder == rootFolder) return false; + if (seriesFolder == rootFolder) + { + return false; + } var distance = seriesFolder.LevenshteinDistance(rootFolder); diff --git a/src/Sonarr.Api.V3/Series/SeriesImportModule.cs b/src/Sonarr.Api.V3/Series/SeriesImportModule.cs index 2fcc7835e..f46b6a24e 100644 --- a/src/Sonarr.Api.V3/Series/SeriesImportModule.cs +++ b/src/Sonarr.Api.V3/Series/SeriesImportModule.cs @@ -17,7 +17,6 @@ public SeriesImportModule(IAddSeriesService addSeriesService) Post("/", x => Import()); } - private object Import() { var resource = Request.Body.FromJson<List<SeriesResource>>(); diff --git a/src/Sonarr.Api.V3/Series/SeriesModule.cs b/src/Sonarr.Api.V3/Series/SeriesModule.cs index 1e0fea38b..9433f973f 100644 --- a/src/Sonarr.Api.V3/Series/SeriesModule.cs +++ b/src/Sonarr.Api.V3/Series/SeriesModule.cs @@ -22,15 +22,14 @@ namespace Sonarr.Api.V3.Series { - public class SeriesModule : SonarrRestModuleWithSignalR<SeriesResource, NzbDrone.Core.Tv.Series>, - IHandle<EpisodeImportedEvent>, + public class SeriesModule : SonarrRestModuleWithSignalR<SeriesResource, NzbDrone.Core.Tv.Series>, + IHandle<EpisodeImportedEvent>, IHandle<EpisodeFileDeletedEvent>, - IHandle<SeriesUpdatedEvent>, - IHandle<SeriesEditedEvent>, + IHandle<SeriesUpdatedEvent>, + IHandle<SeriesEditedEvent>, IHandle<SeriesDeletedEvent>, IHandle<SeriesRenamedEvent>, IHandle<MediaCoversUpdatedEvent> - { private readonly ISeriesService _seriesService; private readonly IAddSeriesService _addSeriesService; @@ -56,8 +55,7 @@ public SeriesModule(IBroadcastSignalRMessage signalRBroadcaster, SystemFolderValidator systemFolderValidator, ProfileExistsValidator profileExistsValidator, LanguageProfileExistsValidator languageProfileExistsValidator, - SeriesFolderAsRootFolderValidator seriesFolderAsRootFolderValidator - ) + SeriesFolderAsRootFolderValidator seriesFolderAsRootFolderValidator) : base(signalRBroadcaster) { _seriesService = seriesService; @@ -176,7 +174,10 @@ private void DeleteSeries(int id) private SeriesResource GetSeriesResource(NzbDrone.Core.Tv.Series series, bool includeSeasonImages) { - if (series == null) return null; + if (series == null) + { + return null; + } var resource = series.ToResource(includeSeasonImages); MapCoversToLocal(resource); @@ -205,7 +206,10 @@ private void LinkSeriesStatistics(List<SeriesResource> resources, List<SeriesSta foreach (var series in resources) { var stats = seriesStatistics.SingleOrDefault(ss => ss.SeriesId == series.Id); - if (stats == null) continue; + if (stats == null) + { + continue; + } LinkSeriesStatistics(series, stats); } @@ -238,7 +242,10 @@ private void PopulateAlternateTitles(SeriesResource resource) { var mappings = _sceneMappingService.FindByTvdbId(resource.TvdbId); - if (mappings == null) return; + if (mappings == null) + { + return; + } resource.AlternateTitles = mappings.ConvertAll(AlternateTitleResourceMapper.ToResource); } @@ -255,7 +262,10 @@ public void Handle(EpisodeImportedEvent message) public void Handle(EpisodeFileDeletedEvent message) { - if (message.Reason == DeleteMediaFileReason.Upgrade) return; + if (message.Reason == DeleteMediaFileReason.Upgrade) + { + return; + } BroadcastResourceChange(ModelAction.Updated, message.EpisodeFile.SeriesId); } diff --git a/src/Sonarr.Api.V3/Series/SeriesResource.cs b/src/Sonarr.Api.V3/Series/SeriesResource.cs index d1a93271c..918a7f276 100644 --- a/src/Sonarr.Api.V3/Series/SeriesResource.cs +++ b/src/Sonarr.Api.V3/Series/SeriesResource.cs @@ -72,13 +72,17 @@ public static class SeriesResourceMapper { public static SeriesResource ToResource(this NzbDrone.Core.Tv.Series model, bool includeSeasonImages = false) { - if (model == null) return null; + if (model == null) + { + return null; + } return new SeriesResource { Id = model.Id, Title = model.Title, + //AlternateTitles SortTitle = model.SortTitle, @@ -88,6 +92,7 @@ public static SeriesResource ToResource(this NzbDrone.Core.Tv.Series model, bool //SizeOnDisk Status = model.Status, Overview = model.Overview, + //NextAiring //PreviousAiring Network = model.Network, @@ -129,13 +134,17 @@ public static SeriesResource ToResource(this NzbDrone.Core.Tv.Series model, bool public static NzbDrone.Core.Tv.Series ToModel(this SeriesResource resource) { - if (resource == null) return null; + if (resource == null) + { + return null; + } return new NzbDrone.Core.Tv.Series { Id = resource.Id, Title = resource.Title, + //AlternateTitles SortTitle = resource.SortTitle, @@ -145,6 +154,7 @@ public static NzbDrone.Core.Tv.Series ToModel(this SeriesResource resource) //SizeOnDisk Status = resource.Status, Overview = resource.Overview, + //NextAiring //PreviousAiring Network = resource.Network, diff --git a/src/Sonarr.Api.V3/Series/SeriesStatisticsResource.cs b/src/Sonarr.Api.V3/Series/SeriesStatisticsResource.cs index dcdecbdf2..6a9dfa99e 100644 --- a/src/Sonarr.Api.V3/Series/SeriesStatisticsResource.cs +++ b/src/Sonarr.Api.V3/Series/SeriesStatisticsResource.cs @@ -17,20 +17,24 @@ public decimal PercentOfEpisodes { get { - if (EpisodeCount == 0) return 0; + if (EpisodeCount == 0) + { + return 0; + } return (decimal)EpisodeFileCount / (decimal)EpisodeCount * 100; } } - - } public static class SeriesStatisticsResourceMapper { public static SeriesStatisticsResource ToResource(this SeriesStatistics model, List<SeasonResource> seasons) { - if (model == null) return null; + if (model == null) + { + return null; + } return new SeriesStatisticsResource { diff --git a/src/Sonarr.Api.V3/System/SystemModule.cs b/src/Sonarr.Api.V3/System/SystemModule.cs index 80442129c..085493ed4 100644 --- a/src/Sonarr.Api.V3/System/SystemModule.cs +++ b/src/Sonarr.Api.V3/System/SystemModule.cs @@ -79,7 +79,7 @@ private object GetStatus() PackageAuthor = _deploymentInfoProvider.PackageAuthor, PackageUpdateMechanism = _deploymentInfoProvider.PackageUpdateMechanism, PackageUpdateMechanismMessage = _deploymentInfoProvider.PackageUpdateMechanismMessage - }; + }; } private object GetRoutes() diff --git a/src/Sonarr.Api.V3/Tags/TagDetailsResource.cs b/src/Sonarr.Api.V3/Tags/TagDetailsResource.cs index 2cc7059af..ea6a7b18b 100644 --- a/src/Sonarr.Api.V3/Tags/TagDetailsResource.cs +++ b/src/Sonarr.Api.V3/Tags/TagDetailsResource.cs @@ -20,7 +20,10 @@ public static class TagDetailsResourceMapper { public static TagDetailsResource ToResource(this TagDetails model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new TagDetailsResource { diff --git a/src/Sonarr.Api.V3/Tags/TagResource.cs b/src/Sonarr.Api.V3/Tags/TagResource.cs index 3c8a00244..f1ffce8c0 100644 --- a/src/Sonarr.Api.V3/Tags/TagResource.cs +++ b/src/Sonarr.Api.V3/Tags/TagResource.cs @@ -14,7 +14,10 @@ public static class TagResourceMapper { public static TagResource ToResource(this Tag model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new TagResource { @@ -25,7 +28,10 @@ public static TagResource ToResource(this Tag model) public static Tag ToModel(this TagResource resource) { - if (resource == null) return null; + if (resource == null) + { + return null; + } return new Tag { diff --git a/src/Sonarr.Api.V3/Update/UpdateModule.cs b/src/Sonarr.Api.V3/Update/UpdateModule.cs index 6c5ec785a..b83c120f1 100644 --- a/src/Sonarr.Api.V3/Update/UpdateModule.cs +++ b/src/Sonarr.Api.V3/Update/UpdateModule.cs @@ -59,4 +59,4 @@ private List<UpdateResource> GetRecentUpdates() return resources; } } -} \ No newline at end of file +} diff --git a/src/Sonarr.Api.V3/Update/UpdateResource.cs b/src/Sonarr.Api.V3/Update/UpdateResource.cs index d23d0dc1c..40c2dd426 100644 --- a/src/Sonarr.Api.V3/Update/UpdateResource.cs +++ b/src/Sonarr.Api.V3/Update/UpdateResource.cs @@ -28,7 +28,10 @@ public static class UpdateResourceMapper { public static UpdateResource ToResource(this UpdatePackage model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new UpdateResource { @@ -38,6 +41,7 @@ public static UpdateResource ToResource(this UpdatePackage model) ReleaseDate = model.ReleaseDate, FileName = model.FileName, Url = model.Url, + //Installed //Installable //Latest diff --git a/src/Sonarr.Http/Authentication/AuthenticationService.cs b/src/Sonarr.Http/Authentication/AuthenticationService.cs index 7f0a167be..8d6003155 100644 --- a/src/Sonarr.Http/Authentication/AuthenticationService.cs +++ b/src/Sonarr.Http/Authentication/AuthenticationService.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Linq; using System.Net; using System.Security.Claims; @@ -27,15 +27,15 @@ public interface IAuthenticationService : IUserValidator, IUserMapper public class AuthenticationService : IAuthenticationService { - private static readonly Logger _authLogger = LogManager.GetLogger("Auth"); private const string AnonymousUser = "Anonymous"; + private static readonly Logger _authLogger = LogManager.GetLogger("Auth"); private readonly IUserService _userService; private static string API_KEY; private static AuthenticationType AUTH_METHOD; [ThreadStatic] - private static NancyContext _context; + private static NancyContext _context; public AuthenticationService(IConfigFileProvider configFileProvider, IUserService userService) { @@ -187,14 +187,20 @@ public bool IsAuthenticated(NancyContext context) private bool ValidUser(NancyContext context) { - if (context.CurrentUser != null) return true; + if (context.CurrentUser != null) + { + return true; + } return false; } private bool ValidApiKey(string apiKey) { - if (API_KEY.Equals(apiKey)) return true; + if (API_KEY.Equals(apiKey)) + { + return true; + } return false; } diff --git a/src/Sonarr.Http/Authentication/EnableAuthInNancy.cs b/src/Sonarr.Http/Authentication/EnableAuthInNancy.cs index 834ef1802..a4e60911f 100644 --- a/src/Sonarr.Http/Authentication/EnableAuthInNancy.cs +++ b/src/Sonarr.Http/Authentication/EnableAuthInNancy.cs @@ -18,7 +18,7 @@ public class EnableAuthInNancy : IRegisterNancyPipeline private readonly IAuthenticationService _authenticationService; private readonly IConfigService _configService; private readonly IConfigFileProvider _configFileProvider; - private FormsAuthenticationConfiguration FormsAuthConfig; + private FormsAuthenticationConfiguration _formsAuthConfig; public EnableAuthInNancy(IAuthenticationService authenticationService, IConfigService configService, @@ -38,7 +38,6 @@ public void Register(IPipelines pipelines) RegisterFormsAuth(pipelines); pipelines.AfterRequest.AddItemToEndOfPipeline((Action<NancyContext>)SlidingAuthenticationForFormsAuth); } - else if (_configFileProvider.AuthenticationMethod == AuthenticationType.Basic) { pipelines.EnableBasicAuthentication(new BasicAuthenticationConfiguration(_authenticationService, "Sonarr")); @@ -56,7 +55,6 @@ private Response CaptureContext(NancyContext context) return null; } - private Response RequiresAuthentication(NancyContext context) { Response response = null; @@ -76,10 +74,9 @@ private void RegisterFormsAuth(IPipelines pipelines) var cryptographyConfiguration = new CryptographyConfiguration( new AesEncryptionProvider(new PassphraseKeyGenerator(_configService.RijndaelPassphrase, Encoding.ASCII.GetBytes(_configService.RijndaelSalt))), - new DefaultHmacProvider(new PassphraseKeyGenerator(_configService.HmacPassphrase, Encoding.ASCII.GetBytes(_configService.HmacSalt))) - ); + new DefaultHmacProvider(new PassphraseKeyGenerator(_configService.HmacPassphrase, Encoding.ASCII.GetBytes(_configService.HmacSalt)))); - FormsAuthConfig = new FormsAuthenticationConfiguration + _formsAuthConfig = new FormsAuthenticationConfiguration { RedirectUrl = _configFileProvider.UrlBase + "/login", UserMapper = _authenticationService, @@ -87,7 +84,7 @@ private void RegisterFormsAuth(IPipelines pipelines) CryptographyConfiguration = cryptographyConfiguration }; - FormsAuthentication.Enable(pipelines, FormsAuthConfig); + FormsAuthentication.Enable(pipelines, _formsAuthConfig); } private void RemoveLoginHooksForApiCalls(NancyContext context) @@ -117,7 +114,7 @@ private void SlidingAuthenticationForFormsAuth(NancyContext context) { var formsAuthCookieValue = context.Request.Cookies[formsAuthCookieName]; - if (FormsAuthentication.DecryptAndValidateAuthenticationCookie(formsAuthCookieValue, FormsAuthConfig).IsNotNullOrWhiteSpace()) + if (FormsAuthentication.DecryptAndValidateAuthenticationCookie(formsAuthCookieValue, _formsAuthConfig).IsNotNullOrWhiteSpace()) { var formsAuthCookie = new SonarrNancyCookie(formsAuthCookieName, formsAuthCookieValue, true, false, DateTime.UtcNow.AddDays(7)) { diff --git a/src/Sonarr.Http/Authentication/SonarrNancyCookie.cs b/src/Sonarr.Http/Authentication/SonarrNancyCookie.cs index 6378ecf09..b160e69a2 100644 --- a/src/Sonarr.Http/Authentication/SonarrNancyCookie.cs +++ b/src/Sonarr.Http/Authentication/SonarrNancyCookie.cs @@ -5,23 +5,28 @@ namespace Sonarr.Http.Authentication { public class SonarrNancyCookie : NancyCookie { - public SonarrNancyCookie(string name, string value) : base(name, value) + public SonarrNancyCookie(string name, string value) + : base(name, value) { } - public SonarrNancyCookie(string name, string value, DateTime expires) : base(name, value, expires) + public SonarrNancyCookie(string name, string value, DateTime expires) + : base(name, value, expires) { } - public SonarrNancyCookie(string name, string value, bool httpOnly) : base(name, value, httpOnly) + public SonarrNancyCookie(string name, string value, bool httpOnly) + : base(name, value, httpOnly) { } - public SonarrNancyCookie(string name, string value, bool httpOnly, bool secure) : base(name, value, httpOnly, secure) + public SonarrNancyCookie(string name, string value, bool httpOnly, bool secure) + : base(name, value, httpOnly, secure) { } - public SonarrNancyCookie(string name, string value, bool httpOnly, bool secure, DateTime? expires) : base(name, value, httpOnly, secure, expires) + public SonarrNancyCookie(string name, string value, bool httpOnly, bool secure, DateTime? expires) + : base(name, value, httpOnly, secure, expires) { } diff --git a/src/Sonarr.Http/ClientSchema/SchemaBuilder.cs b/src/Sonarr.Http/ClientSchema/SchemaBuilder.cs index 739fe78a5..23e7be775 100644 --- a/src/Sonarr.Http/ClientSchema/SchemaBuilder.cs +++ b/src/Sonarr.Http/ClientSchema/SchemaBuilder.cs @@ -53,7 +53,6 @@ public static object ReadFromSchema(List<Field> fields, Type targetType) } return target; - } public static T ReadFromSchema<T>(List<Field> fields) @@ -61,7 +60,6 @@ public static T ReadFromSchema<T>(List<Field> fields) return (T)ReadFromSchema(fields, typeof(T)); } - // Ideally this function should begin a System.Linq.Expression expression tree since it's faster. // But it's probably not needed till performance issues pop up. public static FieldMapping[] GetFieldMappings(Type type) @@ -81,6 +79,7 @@ public static FieldMapping[] GetFieldMappings(Type type) _mappings[type] = result; } + return result; } } @@ -189,32 +188,26 @@ private static Func<object, object> GetValueConverter(Type propertyType) { return fieldValue => fieldValue?.ToString().ParseInt32() ?? 0; } - else if (propertyType == typeof(long)) { return fieldValue => fieldValue?.ToString().ParseInt64() ?? 0; } - else if (propertyType == typeof(double)) { return fieldValue => fieldValue?.ToString().ParseDouble() ?? 0.0; } - else if (propertyType == typeof(int?)) { return fieldValue => fieldValue?.ToString().ParseInt32(); } - - else if (propertyType == typeof(Int64?)) + else if (propertyType == typeof(long?)) { return fieldValue => fieldValue?.ToString().ParseInt64(); } - else if (propertyType == typeof(double?)) { return fieldValue => fieldValue?.ToString().ParseDouble(); } - else if (propertyType == typeof(IEnumerable<int>)) { return fieldValue => @@ -233,7 +226,6 @@ private static Func<object, object> GetValueConverter(Type propertyType) } }; } - else if (propertyType == typeof(IEnumerable<string>)) { return fieldValue => @@ -252,7 +244,6 @@ private static Func<object, object> GetValueConverter(Type propertyType) } }; } - else { return fieldValue => fieldValue; @@ -261,7 +252,7 @@ private static Func<object, object> GetValueConverter(Type propertyType) private static string GetCamelCaseName(string name) { - return Char.ToLowerInvariant(name[0]) + name.Substring(1); + return char.ToLowerInvariant(name[0]) + name.Substring(1); } } } diff --git a/src/Sonarr.Http/ErrorManagement/ErrorModel.cs b/src/Sonarr.Http/ErrorManagement/ErrorModel.cs index 3d6c22dff..22eddb873 100644 --- a/src/Sonarr.Http/ErrorManagement/ErrorModel.cs +++ b/src/Sonarr.Http/ErrorManagement/ErrorModel.cs @@ -18,4 +18,4 @@ public ErrorModel() { } } -} \ No newline at end of file +} diff --git a/src/Sonarr.Http/ErrorManagement/SonarrErrorPipeline.cs b/src/Sonarr.Http/ErrorManagement/SonarrErrorPipeline.cs index c4b7b20c5..65edb1833 100644 --- a/src/Sonarr.Http/ErrorManagement/SonarrErrorPipeline.cs +++ b/src/Sonarr.Http/ErrorManagement/SonarrErrorPipeline.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Data.SQLite; using FluentValidation; using Nancy; @@ -29,7 +29,7 @@ public Response HandleException(NancyContext context, Exception exception) _logger.Warn(apiException, "API Error"); return apiException.ToErrorResponse(context); } - + if (exception is ValidationException validationException) { _logger.Warn("Invalid request {0}", validationException.Message); @@ -69,10 +69,12 @@ public Response HandleException(NancyContext context, Exception exception) if (context.Request.Method == "PUT" || context.Request.Method == "POST") { if (sqLiteException.Message.Contains("constraint failed")) + { return new ErrorModel { Message = exception.Message, }.AsResponse(context, HttpStatusCode.Conflict); + } } _logger.Error(sqLiteException, "[{0} {1}]", context.Request.Method, context.Request.Path); diff --git a/src/Sonarr.Http/Exceptions/InvalidApiKeyException.cs b/src/Sonarr.Http/Exceptions/InvalidApiKeyException.cs index d319ed731..c8d6e1ab3 100644 --- a/src/Sonarr.Http/Exceptions/InvalidApiKeyException.cs +++ b/src/Sonarr.Http/Exceptions/InvalidApiKeyException.cs @@ -8,7 +8,8 @@ public InvalidApiKeyException() { } - public InvalidApiKeyException(string message) : base(message) + public InvalidApiKeyException(string message) + : base(message) { } } diff --git a/src/Sonarr.Http/Extensions/Pipelines/CacheHeaderPipeline.cs b/src/Sonarr.Http/Extensions/Pipelines/CacheHeaderPipeline.cs index b08d5d6e5..70a627fe0 100644 --- a/src/Sonarr.Http/Extensions/Pipelines/CacheHeaderPipeline.cs +++ b/src/Sonarr.Http/Extensions/Pipelines/CacheHeaderPipeline.cs @@ -18,12 +18,15 @@ public CacheHeaderPipeline(ICacheableSpecification cacheableSpecification) public void Register(IPipelines pipelines) { - pipelines.AfterRequest.AddItemToStartOfPipeline((Action<NancyContext>) Handle); + pipelines.AfterRequest.AddItemToStartOfPipeline((Action<NancyContext>)Handle); } private void Handle(NancyContext context) { - if (context.Request.Method == "OPTIONS") return; + if (context.Request.Method == "OPTIONS") + { + return; + } if (_cacheableSpecification.IsCacheable(context)) { diff --git a/src/Sonarr.Http/Extensions/Pipelines/GZipPipeline.cs b/src/Sonarr.Http/Extensions/Pipelines/GZipPipeline.cs index 839177ffb..68c6dc39d 100644 --- a/src/Sonarr.Http/Extensions/Pipelines/GZipPipeline.cs +++ b/src/Sonarr.Http/Extensions/Pipelines/GZipPipeline.cs @@ -52,7 +52,6 @@ private void CompressResponse(NancyContext context) response.Contents = responseStream => _writeGZipStream(contents, responseStream); } } - catch (Exception ex) { _logger.Error(ex, "Unable to gzip response"); diff --git a/src/Sonarr.Http/Extensions/Pipelines/IRegisterNancyPipeline.cs b/src/Sonarr.Http/Extensions/Pipelines/IRegisterNancyPipeline.cs index 81dc848dd..7853075a5 100644 --- a/src/Sonarr.Http/Extensions/Pipelines/IRegisterNancyPipeline.cs +++ b/src/Sonarr.Http/Extensions/Pipelines/IRegisterNancyPipeline.cs @@ -8,4 +8,4 @@ public interface IRegisterNancyPipeline void Register(IPipelines pipelines); } -} \ No newline at end of file +} diff --git a/src/Sonarr.Http/Extensions/Pipelines/IfModifiedPipeline.cs b/src/Sonarr.Http/Extensions/Pipelines/IfModifiedPipeline.cs index 788876d76..7c7e8ed80 100644 --- a/src/Sonarr.Http/Extensions/Pipelines/IfModifiedPipeline.cs +++ b/src/Sonarr.Http/Extensions/Pipelines/IfModifiedPipeline.cs @@ -18,7 +18,7 @@ public IfModifiedPipeline(ICacheableSpecification cacheableSpecification) public void Register(IPipelines pipelines) { - pipelines.BeforeRequest.AddItemToStartOfPipeline((Func<NancyContext, Response>) Handle); + pipelines.BeforeRequest.AddItemToStartOfPipeline((Func<NancyContext, Response>)Handle); } private Response Handle(NancyContext context) @@ -33,4 +33,4 @@ private Response Handle(NancyContext context) return null; } } -} \ No newline at end of file +} diff --git a/src/Sonarr.Http/Extensions/Pipelines/RequestLoggingPipeline.cs b/src/Sonarr.Http/Extensions/Pipelines/RequestLoggingPipeline.cs index a1639c4fd..1f51de296 100644 --- a/src/Sonarr.Http/Extensions/Pipelines/RequestLoggingPipeline.cs +++ b/src/Sonarr.Http/Extensions/Pipelines/RequestLoggingPipeline.cs @@ -100,4 +100,4 @@ private static string GetOrigin(NancyContext context) } } } -} \ No newline at end of file +} diff --git a/src/Sonarr.Http/Extensions/Pipelines/SetCookieHeaderPipeline.cs b/src/Sonarr.Http/Extensions/Pipelines/SetCookieHeaderPipeline.cs index a23bdef17..e78f18d35 100644 --- a/src/Sonarr.Http/Extensions/Pipelines/SetCookieHeaderPipeline.cs +++ b/src/Sonarr.Http/Extensions/Pipelines/SetCookieHeaderPipeline.cs @@ -11,7 +11,7 @@ public class SetCookieHeaderPipeline : IRegisterNancyPipeline public void Register(IPipelines pipelines) { - pipelines.AfterRequest.AddItemToEndOfPipeline((Action<NancyContext>) Handle); + pipelines.AfterRequest.AddItemToEndOfPipeline((Action<NancyContext>)Handle); } private void Handle(NancyContext context) @@ -27,4 +27,4 @@ private void Handle(NancyContext context) } } } -} \ No newline at end of file +} diff --git a/src/Sonarr.Http/Extensions/Pipelines/SonarrVersionPipeline.cs b/src/Sonarr.Http/Extensions/Pipelines/SonarrVersionPipeline.cs index aefd6ceb4..600c11a43 100644 --- a/src/Sonarr.Http/Extensions/Pipelines/SonarrVersionPipeline.cs +++ b/src/Sonarr.Http/Extensions/Pipelines/SonarrVersionPipeline.cs @@ -11,7 +11,7 @@ public class SonarrVersionPipeline : IRegisterNancyPipeline public void Register(IPipelines pipelines) { - pipelines.AfterRequest.AddItemToStartOfPipeline((Action<NancyContext>) Handle); + pipelines.AfterRequest.AddItemToStartOfPipeline((Action<NancyContext>)Handle); } private void Handle(NancyContext context) @@ -22,4 +22,4 @@ private void Handle(NancyContext context) } } } -} \ No newline at end of file +} diff --git a/src/Sonarr.Http/Extensions/Pipelines/UrlBasePipeline.cs b/src/Sonarr.Http/Extensions/Pipelines/UrlBasePipeline.cs index a12451f4e..73623cd43 100644 --- a/src/Sonarr.Http/Extensions/Pipelines/UrlBasePipeline.cs +++ b/src/Sonarr.Http/Extensions/Pipelines/UrlBasePipeline.cs @@ -22,7 +22,7 @@ public void Register(IPipelines pipelines) { if (_urlBase.IsNotNullOrWhiteSpace()) { - pipelines.BeforeRequest.AddItemToStartOfPipeline((Func<NancyContext, Response>) Handle); + pipelines.BeforeRequest.AddItemToStartOfPipeline((Func<NancyContext, Response>)Handle); } } diff --git a/src/Sonarr.Http/Extensions/RequestExtensions.cs b/src/Sonarr.Http/Extensions/RequestExtensions.cs index 7be0a7534..cdddbda3f 100644 --- a/src/Sonarr.Http/Extensions/RequestExtensions.cs +++ b/src/Sonarr.Http/Extensions/RequestExtensions.cs @@ -30,9 +30,9 @@ public static bool IsSignalRRequest(this Request request) public static bool IsLocalRequest(this Request request) { - return (request.UserHostAddress.Equals("localhost") || + return request.UserHostAddress.Equals("localhost") || request.UserHostAddress.Equals("127.0.0.1") || - request.UserHostAddress.Equals("::1")); + request.UserHostAddress.Equals("::1"); } public static bool IsLoginRequest(this Request request) diff --git a/src/Sonarr.Http/Frontend/Mappers/HtmlMapperBase.cs b/src/Sonarr.Http/Frontend/Mappers/HtmlMapperBase.cs index 7863c1ca2..378a1185c 100644 --- a/src/Sonarr.Http/Frontend/Mappers/HtmlMapperBase.cs +++ b/src/Sonarr.Http/Frontend/Mappers/HtmlMapperBase.cs @@ -62,7 +62,6 @@ protected string GetHtmlText() { url = match.Groups["path"].Value; } - else { url = cacheBreakProvider.AddCacheBreakerToPath(match.Groups["path"].Value); diff --git a/src/Sonarr.Http/Frontend/StaticResourceModule.cs b/src/Sonarr.Http/Frontend/StaticResourceModule.cs index 66720f0b6..4069e168a 100644 --- a/src/Sonarr.Http/Frontend/StaticResourceModule.cs +++ b/src/Sonarr.Http/Frontend/StaticResourceModule.cs @@ -13,7 +13,6 @@ public class StaticResourceModule : NancyModule private readonly IEnumerable<IMapHttpRequestsToDisk> _requestMappers; private readonly Logger _logger; - public StaticResourceModule(IEnumerable<IMapHttpRequestsToDisk> requestMappers, Logger logger) { _requestMappers = requestMappers; diff --git a/src/Sonarr.Http/PagingResource.cs b/src/Sonarr.Http/PagingResource.cs index 2a49402de..d1c0a6eb7 100644 --- a/src/Sonarr.Http/PagingResource.cs +++ b/src/Sonarr.Http/PagingResource.cs @@ -30,7 +30,7 @@ public static PagingSpec<TModel> MapToPagingSpec<TResource, TModel>(this PagingR { pagingSpec.SortKey = defaultSortKey; - if(pagingResource.SortDirection == SortDirection.Default) + if (pagingResource.SortDirection == SortDirection.Default) { pagingSpec.SortDirection = defaultSortDirection; } diff --git a/src/Sonarr.Http/REST/BadRequestException.cs b/src/Sonarr.Http/REST/BadRequestException.cs index 37b94f5c1..4129ec588 100644 --- a/src/Sonarr.Http/REST/BadRequestException.cs +++ b/src/Sonarr.Http/REST/BadRequestException.cs @@ -10,4 +10,4 @@ public BadRequestException(object content = null) { } } -} \ No newline at end of file +} diff --git a/src/Sonarr.Http/REST/NotFoundException.cs b/src/Sonarr.Http/REST/NotFoundException.cs index 8b6109a5f..25e862420 100644 --- a/src/Sonarr.Http/REST/NotFoundException.cs +++ b/src/Sonarr.Http/REST/NotFoundException.cs @@ -10,4 +10,4 @@ public NotFoundException(object content = null) { } } -} \ No newline at end of file +} diff --git a/src/Sonarr.Http/REST/ResourceValidator.cs b/src/Sonarr.Http/REST/ResourceValidator.cs index 4e4662ee8..a33d2ef3c 100644 --- a/src/Sonarr.Http/REST/ResourceValidator.cs +++ b/src/Sonarr.Http/REST/ResourceValidator.cs @@ -23,7 +23,6 @@ public IRuleBuilderInitial<TResource, TProperty> RuleForField<TProperty>(Express private static object GetValue(object container, Func<TResource, IEnumerable<Field>> fieldListAccessor, string fieldName) { - var resource = fieldListAccessor((TResource)container).SingleOrDefault(c => c.Name == fieldName); if (resource == null) @@ -34,4 +33,4 @@ private static object GetValue(object container, Func<TResource, IEnumerable<Fie return resource.Value; } } -} \ No newline at end of file +} diff --git a/src/Sonarr.Http/REST/RestModule.cs b/src/Sonarr.Http/REST/RestModule.cs index 9a6b693f4..60209a2ba 100644 --- a/src/Sonarr.Http/REST/RestModule.cs +++ b/src/Sonarr.Http/REST/RestModule.cs @@ -17,7 +17,7 @@ public abstract class RestModule<TResource> : NancyModule private const string ROOT_ROUTE = "/"; private const string ID_ROUTE = @"/(?<id>[\d]{1,10})"; - private HashSet<string> EXCLUDED_KEYS = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase) + private HashSet<string> _excludedKeys = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase) { "page", "pageSize", @@ -57,10 +57,12 @@ protected RestModule(string modulePath) SharedValidator = new ResourceValidator<TResource>(); } - private void ValidateModule() { - if (GetResourceById != null) return; + if (GetResourceById != null) + { + return; + } if (CreateResource != null || UpdateResource != null) { @@ -70,7 +72,11 @@ private void ValidateModule() protected Action<int> DeleteResource { - private get { return _deleteResource; } + private get + { + return _deleteResource; + } + set { _deleteResource = value; @@ -86,7 +92,11 @@ protected Action<int> DeleteResource protected Func<int, TResource> GetResourceById { - get { return _getResourceById; } + get + { + return _getResourceById; + } + set { _getResourceById = value; @@ -114,11 +124,14 @@ protected Func<int, TResource> GetResourceById protected Func<List<TResource>> GetResourceAll { - private get { return _getResourceAll; } + private get + { + return _getResourceAll; + } + set { _getResourceAll = value; - Get(ROOT_ROUTE, options => { var resource = GetResourceAll(); @@ -129,11 +142,14 @@ protected Func<List<TResource>> GetResourceAll protected Func<PagingResource<TResource>, PagingResource<TResource>> GetResourcePaged { - private get { return _getResourcePaged; } + private get + { + return _getResourcePaged; + } + set { _getResourcePaged = value; - Get(ROOT_ROUTE, options => { var resource = GetResourcePaged(ReadPagingResourceFromRequest()); @@ -144,11 +160,14 @@ protected Func<PagingResource<TResource>, PagingResource<TResource>> GetResource protected Func<TResource> GetResourceSingle { - private get { return _getResourceSingle; } + private get + { + return _getResourceSingle; + } + set { _getResourceSingle = value; - Get(ROOT_ROUTE, options => { var resource = GetResourceSingle(); @@ -159,7 +178,11 @@ protected Func<TResource> GetResourceSingle protected Func<TResource, int> CreateResource { - private get { return _createResource; } + private get + { + return _createResource; + } + set { _createResource = value; @@ -173,7 +196,11 @@ protected Func<TResource, int> CreateResource protected Action<TResource> UpdateResource { - private get { return _updateResource; } + private get + { + return _updateResource; + } + set { _updateResource = value; @@ -183,7 +210,6 @@ protected Action<TResource> UpdateResource UpdateResource(resource); return ResponseWithCode(GetResourceById(resource.Id), HttpStatusCode.Accepted); }); - Put(ID_ROUTE, options => { var resource = ReadResourceFromRequest(); @@ -245,12 +271,17 @@ private PagingResource<TResource> ReadPagingResourceFromRequest() { int pageSize; int.TryParse(Request.Query.PageSize.ToString(), out pageSize); - if (pageSize == 0) pageSize = 10; + if (pageSize == 0) + { + pageSize = 10; + } int page; int.TryParse(Request.Query.Page.ToString(), out page); - if (page == 0) page = 1; - + if (page == 0) + { + page = 1; + } var pagingResource = new PagingResource<TResource> { @@ -302,7 +333,7 @@ private PagingResource<TResource> ReadPagingResourceFromRequest() foreach (var key in Request.Query) { - if (EXCLUDED_KEYS.Contains(key)) + if (_excludedKeys.Contains(key)) { continue; } diff --git a/src/Sonarr.Http/REST/RestResource.cs b/src/Sonarr.Http/REST/RestResource.cs index d6347882a..9eada5853 100644 --- a/src/Sonarr.Http/REST/RestResource.cs +++ b/src/Sonarr.Http/REST/RestResource.cs @@ -10,4 +10,4 @@ public abstract class RestResource [JsonIgnore] public virtual string ResourceName => GetType().Name.ToLowerInvariant().Replace("resource", ""); } -} \ No newline at end of file +} diff --git a/src/Sonarr.Http/ResourceChangeMessage.cs b/src/Sonarr.Http/ResourceChangeMessage.cs index f0c54f881..fb65b5998 100644 --- a/src/Sonarr.Http/ResourceChangeMessage.cs +++ b/src/Sonarr.Http/ResourceChangeMessage.cs @@ -4,7 +4,8 @@ namespace Sonarr.Http { - public class ResourceChangeMessage<TResource> where TResource : RestResource + public class ResourceChangeMessage<TResource> + where TResource : RestResource { public TResource Resource { get; private set; } public ModelAction Action { get; private set; } @@ -25,5 +26,4 @@ public ResourceChangeMessage(TResource resource, ModelAction action) Action = action; } } - -} \ No newline at end of file +} diff --git a/src/Sonarr.Http/SonarrBootstrapper.cs b/src/Sonarr.Http/SonarrBootstrapper.cs index f6c241cf6..539254cbf 100644 --- a/src/Sonarr.Http/SonarrBootstrapper.cs +++ b/src/Sonarr.Http/SonarrBootstrapper.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Linq; using Nancy; using Nancy.Bootstrapper; @@ -57,7 +57,8 @@ protected override Func<ITypeCatalog, NancyInternalConfiguration> InternalConfig get { // We don't support Xml Serialization atm - return NancyInternalConfiguration.WithOverrides(x => { + return NancyInternalConfiguration.WithOverrides(x => + { x.ResponseProcessors.Remove(typeof(ViewProcessor)); x.ResponseProcessors.Remove(typeof(XmlProcessor)); }); diff --git a/src/Sonarr.Http/SonarrRestModule.cs b/src/Sonarr.Http/SonarrRestModule.cs index 3924c6f2a..523db1646 100644 --- a/src/Sonarr.Http/SonarrRestModule.cs +++ b/src/Sonarr.Http/SonarrRestModule.cs @@ -5,11 +5,11 @@ namespace Sonarr.Http { - public abstract class SonarrRestModule<TResource> : RestModule<TResource> where TResource : RestResource, new() + public abstract class SonarrRestModule<TResource> : RestModule<TResource> + where TResource : RestResource, new() { protected string Resource { get; private set; } - private static string BaseUrl() { var isV3 = typeof(TResource).Namespace.Contains(".V3."); @@ -17,6 +17,7 @@ private static string BaseUrl() { return "/api/v3/"; } + return "/api/"; } @@ -53,4 +54,4 @@ protected PagingResource<TResource> ApplyToPage<TModel>(Func<PagingSpec<TModel>, }; } } -} \ No newline at end of file +} diff --git a/src/Sonarr.Http/SonarrRestModuleWithSignalR.cs b/src/Sonarr.Http/SonarrRestModuleWithSignalR.cs index e95db189b..64183d447 100644 --- a/src/Sonarr.Http/SonarrRestModuleWithSignalR.cs +++ b/src/Sonarr.Http/SonarrRestModuleWithSignalR.cs @@ -30,7 +30,10 @@ protected virtual TResource GetResourceByIdForBroadcast(int id) public void Handle(ModelEvent<TModel> message) { - if (!_signalRBroadcaster.IsConnected) return; + if (!_signalRBroadcaster.IsConnected) + { + return; + } if (message.Action == ModelAction.Deleted || message.Action == ModelAction.Sync) { @@ -42,11 +45,14 @@ public void Handle(ModelEvent<TModel> message) protected void BroadcastResourceChange(ModelAction action, int id) { - if (!_signalRBroadcaster.IsConnected) return; + if (!_signalRBroadcaster.IsConnected) + { + return; + } if (action == ModelAction.Deleted) { - BroadcastResourceChange(action, new TResource {Id = id}); + BroadcastResourceChange(action, new TResource { Id = id }); } else { @@ -57,7 +63,10 @@ protected void BroadcastResourceChange(ModelAction action, int id) protected void BroadcastResourceChange(ModelAction action, TResource resource) { - if (!_signalRBroadcaster.IsConnected) return; + if (!_signalRBroadcaster.IsConnected) + { + return; + } if (GetType().Namespace.Contains("V3")) { @@ -71,10 +80,13 @@ protected void BroadcastResourceChange(ModelAction action, TResource resource) _signalRBroadcaster.BroadcastMessage(signalRMessage); } } - + protected void BroadcastResourceChange(ModelAction action) { - if (!_signalRBroadcaster.IsConnected) return; + if (!_signalRBroadcaster.IsConnected) + { + return; + } if (GetType().Namespace.Contains("V3")) { diff --git a/src/Sonarr.Http/TinyIoCNancyBootstrapper.cs b/src/Sonarr.Http/TinyIoCNancyBootstrapper.cs index 75283a80b..dbdeec83f 100644 --- a/src/Sonarr.Http/TinyIoCNancyBootstrapper.cs +++ b/src/Sonarr.Http/TinyIoCNancyBootstrapper.cs @@ -1,17 +1,15 @@ -using TinyIoC; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Nancy; -using Nancy.Diagnostics; using Nancy.Bootstrapper; using Nancy.Configuration; +using Nancy.Diagnostics; +using TinyIoC; namespace Sonarr.Http { - - /// <summary> /// TinyIoC bootstrapper - registers default route resolver and registers itself as /// INancyModuleCatalog for resolving modules but behaviour can be overridden if required. @@ -53,7 +51,6 @@ protected override sealed INancyEngine GetEngineInternal() return this.ApplicationContainer.Resolve<INancyEngine>(); } - // // Summary: // Gets the Nancy.Configuration.INancyEnvironmentConfigurator used by th. // @@ -64,7 +61,6 @@ protected override INancyEnvironmentConfigurator GetEnvironmentConfigurator() return this.ApplicationContainer.Resolve<INancyEnvironmentConfigurator>(); } - // // Summary: // Get the Nancy.Configuration.INancyEnvironment instance. // @@ -79,7 +75,6 @@ public override INancyEnvironment GetEnvironment() return this.ApplicationContainer.Resolve<INancyEnvironment>(); } - // // Summary: // Registers an Nancy.Configuration.INancyEnvironment instance in the container. // diff --git a/src/Sonarr.Http/Validation/EmptyCollectionValidator.cs b/src/Sonarr.Http/Validation/EmptyCollectionValidator.cs index 287b103e3..91be1efcc 100644 --- a/src/Sonarr.Http/Validation/EmptyCollectionValidator.cs +++ b/src/Sonarr.Http/Validation/EmptyCollectionValidator.cs @@ -13,7 +13,10 @@ public EmptyCollectionValidator() protected override bool IsValid(PropertyValidatorContext context) { - if (context.PropertyValue == null) return true; + if (context.PropertyValue == null) + { + return true; + } return context.PropertyValue is IEnumerable<T> collection && collection.Empty(); } diff --git a/src/Sonarr.RuntimePatches/Mono/BoringTLSVerifyFlagsPatch.cs b/src/Sonarr.RuntimePatches/Mono/BoringTLSVerifyFlagsPatch.cs index 2d4cf2855..bf4e8246a 100644 --- a/src/Sonarr.RuntimePatches/Mono/BoringTLSVerifyFlagsPatch.cs +++ b/src/Sonarr.RuntimePatches/Mono/BoringTLSVerifyFlagsPatch.cs @@ -9,7 +9,7 @@ namespace NzbDrone.RuntimePatches.Mono { // Mono 5.x - 6.x bug 19886 - // The BoringTLS provider does not enable the trust-first option that's default on in openssl 1.1.0 and up. + // The BoringTLS provider does not enable the trust-first option that's default on in openssl 1.1.0 and up. // This prevents it from building the short trusted chain and errors out on old (expired) chains included in the certificate. // This is a problem with Cross-Signed certificates that have an expired legacy root signing the new root. // The Flags default is 0, while X509_V_FLAG_TRUSTED_FIRST is 0x8000. @@ -40,14 +40,14 @@ protected override void Patch() // + copy.SetFlags(0x8000); // + return copy; // } - static IEnumerable<CodeInstruction> Transpiler_GetSslServer(IEnumerable<CodeInstruction> instructions, MethodBase method, ILGenerator generator) + private static IEnumerable<CodeInstruction> Transpiler_GetSslServer(IEnumerable<CodeInstruction> instructions, MethodBase method, ILGenerator generator) { var codes = instructions.ToList(); var patchable = codes.Matches(OpCodes.Ldstr, OpCodes.Ldc_I4_1, OpCodes.Call, OpCodes.Ret); Instance.DebugOpcodes("Before", codes); - + var targetType = method.DeclaringType; var copyMethod = targetType.GetMethod("Copy", new Type[0]); var disposeMethod = targetType.GetMethod("Dispose", new Type[0]); diff --git a/src/Sonarr.RuntimePatches/Mono/DeflateStreamAsyncPatch.cs b/src/Sonarr.RuntimePatches/Mono/DeflateStreamAsyncPatch.cs index 0e2ed5fd8..7229419e9 100644 --- a/src/Sonarr.RuntimePatches/Mono/DeflateStreamAsyncPatch.cs +++ b/src/Sonarr.RuntimePatches/Mono/DeflateStreamAsyncPatch.cs @@ -32,10 +32,10 @@ protected override void Patch() // - throw new NotImplementedException(); // + return base.ReadAsync(destination, cancellationToken); // } - static IEnumerable<CodeInstruction> Transpiler_ReadAsyncMemory(IEnumerable<CodeInstruction> instructions, MethodBase method) + private static IEnumerable<CodeInstruction> Transpiler_ReadAsyncMemory(IEnumerable<CodeInstruction> instructions, MethodBase method) { var codes = instructions.ToList(); - + var patchable = codes.Matches(OpCodes.Newobj, OpCodes.Throw); var readAsync = method.DeclaringType.BaseType.GetMethod("ReadAsync", method.GetParameterTypes()); @@ -65,18 +65,18 @@ static IEnumerable<CodeInstruction> Transpiler_ReadAsyncMemory(IEnumerable<CodeI // - throw new NotImplementedException(); // + return base.WriteAsync(source, cancellationToken); // } - static IEnumerable<CodeInstruction> Transpiler_WriteAsyncMemory(IEnumerable<CodeInstruction> instructions, MethodBase method) + private static IEnumerable<CodeInstruction> Transpiler_WriteAsyncMemory(IEnumerable<CodeInstruction> instructions, MethodBase method) { var codes = instructions.ToList(); var patchable = codes.Matches(OpCodes.Newobj, OpCodes.Throw); var writeAsync = method.DeclaringType.BaseType.GetMethod("WriteAsync", method.GetParameterTypes()); - + if (patchable && writeAsync != null) { - codes.Clear(); - + codes.Clear(); + codes.Add(new CodeInstruction(OpCodes.Ldarg_0)); codes.Add(new CodeInstruction(OpCodes.Ldarg_1)); codes.Add(new CodeInstruction(OpCodes.Ldarg_2)); diff --git a/src/Sonarr.RuntimePatches/MonoRuntimePatchBase.cs b/src/Sonarr.RuntimePatches/MonoRuntimePatchBase.cs index f8760994c..74b846dca 100644 --- a/src/Sonarr.RuntimePatches/MonoRuntimePatchBase.cs +++ b/src/Sonarr.RuntimePatches/MonoRuntimePatchBase.cs @@ -35,7 +35,6 @@ static MonoRuntimePatchBase() } catch { - } } @@ -46,7 +45,7 @@ public override bool ShouldPatch() return false; } - return MonoVersion >= MonoMinVersion && MonoVersion < MonoMaxVersion; + return MonoMinVersion <= MonoVersion && MonoMaxVersion > MonoVersion; } protected override void Log(string log) diff --git a/src/Sonarr.RuntimePatches/RuntimePatchBase.cs b/src/Sonarr.RuntimePatches/RuntimePatchBase.cs index 76bd63e0b..9a487bc7f 100644 --- a/src/Sonarr.RuntimePatches/RuntimePatchBase.cs +++ b/src/Sonarr.RuntimePatches/RuntimePatchBase.cs @@ -30,11 +30,17 @@ protected static MethodInfo FindMethod(Type type, string methodName, params stri { foreach (var methodInfo in type.GetMethods(DefaultBindingFlags)) { - if (methodInfo.Name != methodName) continue; + if (methodInfo.Name != methodName) + { + continue; + } var parameters = methodInfo.GetParameters(); - if (parameters.Length != paramTypes.Length) continue; + if (parameters.Length != paramTypes.Length) + { + continue; + } var parametersMatch = true; for (var i = 0; i < parameters.Length; i++) @@ -49,7 +55,10 @@ protected static MethodInfo FindMethod(Type type, string methodName, params stri } } - if (!parametersMatch) continue; + if (!parametersMatch) + { + continue; + } return methodInfo; } diff --git a/src/Sonarr.RuntimePatches/RuntimePatchExtensions.cs b/src/Sonarr.RuntimePatches/RuntimePatchExtensions.cs index 6ee158c19..c14ac6ed2 100644 --- a/src/Sonarr.RuntimePatches/RuntimePatchExtensions.cs +++ b/src/Sonarr.RuntimePatches/RuntimePatchExtensions.cs @@ -14,11 +14,17 @@ public static bool Matches(this List<CodeInstruction> instructions, params OpCod { var codes = instructions.Select(v => v.opcode).Where(v => v != OpCodes.Nop).ToList(); - if (codes.Count != opcodes.Length) return false; + if (codes.Count != opcodes.Length) + { + return false; + } for (var i = 0; i < codes.Count; i++) { - if (codes[i] != opcodes[i]) return false; + if (codes[i] != opcodes[i]) + { + return false; + } } return true; @@ -52,10 +58,13 @@ public static string GetSimplifiedName(this Type t, bool includeNamespace = fals for (int i = 0; i < args.Length; i++) { if (i != 0) + { sb.Append(", "); + } sb.Append(GetSimplifiedName(args[i], includeNamespace)); } + sb.Append('>'); } else diff --git a/src/stylecop.json b/src/stylecop.json new file mode 100644 index 000000000..b4321a13b --- /dev/null +++ b/src/stylecop.json @@ -0,0 +1,21 @@ +{ + "$schema": "https://raw.githubusercontent.com/DotNetAnalyzers/StyleCopAnalyzers/master/StyleCop.Analyzers/StyleCop.Analyzers/Settings/stylecop.schema.json", + "settings": { + "documentationRules": { + "xmlHeader": false, + "documentInterfaces": false, + "documentInternalElements": false + }, + "indentation": { + "indentationSize": 4, + "useTabs": false + }, + "layoutRules": { + "newlineAtEndOfFile": "require" + }, + "orderingRules": { + "systemUsingDirectivesFirst": true, + "usingDirectivesPlacement": "outsideNamespace" + } + } +}