pull/5116/head
Qstick 3 years ago committed by Mark McDowall
parent 878d1561aa
commit 1c22a1ec0d

@ -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

1
.gitignore vendored

@ -84,7 +84,6 @@ TestResults
[Tt]est[Rr]esult*
*.Cache
ClientBin
[Ss]tyle[Cc]op.*
~$*
*.dbmdl
Generated_Code #added for RIA/Silverlight projects

@ -104,6 +104,16 @@
<EnableNETAnalyzers>false</EnableNETAnalyzers>
</PropertyGroup>
<!-- Set up stylecop -->
<ItemGroup Condition="'$(SonarrProject)'=='true' and '$(EnableAnalyzers)'!='false'">
<!-- StyleCop analysis -->
<PackageReference Include="StyleCop.Analyzers" Version="1.1.118">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
</PackageReference>
<AdditionalFiles Include="$(SolutionDir)stylecop.json" />
</ItemGroup>
<!--
Set runtime identifier to local system type if not specified
-->

@ -16,7 +16,6 @@ namespace NzbDrone.Api.Test.ClientSchemaTests
schema.Should().HaveCount(2);
}
[Test]
public void schema_should_have_proper_fields()
{
@ -32,7 +31,6 @@ namespace NzbDrone.Api.Test.ClientSchemaTests
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()
{

@ -7,7 +7,6 @@ namespace NzbDrone.Automation.Test
public AutomationTestAttribute()
: base("AutomationTest")
{
}
}
}
}

@ -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();
var imageName = MethodBase.GetCurrentMethod().Name;
TakeScreenshot(imageName);
page.Find(By.CssSelector("div[class*='CalendarPage']")).Should().NotBeNull();
_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();
var imageName = MethodBase.GetCurrentMethod().Name;
TakeScreenshot(imageName);
page.Find(By.CssSelector("div[class*='Health']")).Should().NotBeNull();
_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();
}
}
}

@ -59,4 +59,4 @@ namespace NzbDrone.Automation.Test.PageModel
public IWebElement SystemNavIcon => Find(By.PartialLinkText("System"));
}
}
}

@ -4,7 +4,7 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Selenium.Support" Version="3.141.0" />
<PackageReference Include="Selenium.WebDriver.ChromeDriver" Version="88.0.4324.9600" />
<PackageReference Include="Selenium.WebDriver.ChromeDriver" Version="92.0.4515.10700" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\NzbDrone.Test.Common\Sonarr.Test.Common.csproj" />

@ -99,4 +99,4 @@ namespace NzbDrone.Common.Test.CacheTests
return result;
}
}
}
}

@ -26,7 +26,6 @@ namespace NzbDrone.Common.Test.CacheTests
_cachedString.Get("Test", _worker.GetString);
_worker.HitCount.Should().Be(1);
}
[Test]
@ -38,7 +37,6 @@ namespace NzbDrone.Common.Test.CacheTests
first.Should().Be(second);
}
[Test]
public void should_be_able_to_update_key()
{
@ -48,7 +46,6 @@ namespace NzbDrone.Common.Test.CacheTests
_cachedString.Find("Key").Should().Be("New");
}
[Test]
public void should_be_able_to_remove_key()
{
@ -70,7 +67,6 @@ namespace NzbDrone.Common.Test.CacheTests
{
int hitCount = 0;
for (int i = 0; i < 10; i++)
{
_cachedString.Get("key", () =>
@ -84,6 +80,7 @@ namespace NzbDrone.Common.Test.CacheTests
}
[Test]
[Platform(Exclude = "MacOsX")]
public void should_honor_ttl()
{
int hitCount = 0;
@ -91,11 +88,13 @@ namespace NzbDrone.Common.Test.CacheTests
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 @@ namespace NzbDrone.Common.Test.CacheTests
return "Hit count is " + HitCount;
}
}
}
}

@ -26,4 +26,4 @@ namespace NzbDrone.Common.Test.CacheTests
result1.Should().BeSameAs(result2);
}
}
}
}

@ -62,10 +62,8 @@ namespace NzbDrone.Common.Test
const string key = "Port";
const int value = 8989;
var result = Subject.GetValueInt(key, value);
result.Should().Be(value);
}
@ -75,20 +73,16 @@ namespace NzbDrone.Common.Test
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 @@ namespace NzbDrone.Common.Test
{
const int value = 8989;
var result = Subject.Port;
result.Should().Be(value);
}
@ -110,10 +102,8 @@ namespace NzbDrone.Common.Test
const string key = "LaunchBrowser";
const bool value = false;
Subject.SetValue(key, value);
var result = Subject.LaunchBrowser;
result.Should().Be(value);
}
@ -124,10 +114,8 @@ namespace NzbDrone.Common.Test
const string key = "Port";
const int value = 12345;
Subject.SetValue(key, value);
var result = Subject.Port;
result.Should().Be(value);
}
@ -138,10 +126,8 @@ namespace NzbDrone.Common.Test
const string key = "Hello";
const string value = "World";
var result = Subject.GetValue(key, value);
result.Should().Be(value);
}
@ -178,7 +164,6 @@ namespace NzbDrone.Common.Test
dic["SslPort"] = origSslPort;
Subject.SaveConfigDictionary(dic);
dic = new Dictionary<string, object>();
dic["SslPort"] = sslPort;
Subject.SaveConfigDictionary(dic);
@ -213,4 +198,4 @@ namespace NzbDrone.Common.Test
Assert.Throws<InvalidConfigFileException>(() => Subject.GetValue("key", "value"));
}
}
}
}

@ -76,7 +76,7 @@ namespace NzbDrone.Common.Test.DiskTests
.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);

@ -1,4 +1,4 @@
using System;
using System;
using System.IO;
using FluentAssertions;
using NUnit.Framework;
@ -7,7 +7,8 @@ using NzbDrone.Test.Common;
namespace NzbDrone.Common.Test.DiskTests
{
public abstract class DiskProviderFixtureBase<TSubject> : TestBase<TSubject> where TSubject : class, IDiskProvider
public abstract class DiskProviderFixtureBase<TSubject> : TestBase<TSubject>
where TSubject : class, IDiskProvider
{
[Test]
[Retry(5)]
@ -154,7 +155,7 @@ namespace NzbDrone.Common.Test.DiskTests
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 @@ namespace NzbDrone.Common.Test.DiskTests
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 @@ namespace NzbDrone.Common.Test.DiskTests
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 @@ namespace NzbDrone.Common.Test.DiskTests
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 @@ namespace NzbDrone.Common.Test.DiskTests
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);

@ -751,7 +751,9 @@ namespace NzbDrone.Common.Test.DiskTests
{
var dir = Path.GetDirectoryName(path);
if (exists && dir.IsNotNullOrWhiteSpace())
{
WithExistingFolder(dir);
}
Mocker.GetMock<IDiskProvider>()
.Setup(v => v.FolderExists(path))
@ -762,7 +764,9 @@ namespace NzbDrone.Common.Test.DiskTests
{
var dir = Path.GetDirectoryName(path);
if (exists && dir.IsNotNullOrWhiteSpace())
{
WithExistingFolder(dir);
}
Mocker.GetMock<IDiskProvider>()
.Setup(v => v.FileExists(path))
@ -816,7 +820,6 @@ namespace NzbDrone.Common.Test.DiskTests
WithExistingFile(v, false);
});
Mocker.GetMock<IDiskProvider>()
.Setup(v => v.FolderExists(It.IsAny<string>()))
.Returns(false);
@ -834,6 +837,7 @@ namespace NzbDrone.Common.Test.DiskTests
{
WithExistingFolder(s, false);
WithExistingFolder(d);
// Note: Should also deal with the files.
});
@ -842,6 +846,7 @@ namespace NzbDrone.Common.Test.DiskTests
.Callback<string, bool>((f, r) =>
{
WithExistingFolder(f, false);
// Note: Should also deal with the files.
});
@ -907,8 +912,13 @@ namespace NzbDrone.Common.Test.DiskTests
Mocker.GetMock<IDiskProvider>()
.Setup(v => v.MoveFile(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<bool>()))
.Callback<string, string, bool>((s,d,o) => {
if (File.Exists(d) && o) File.Delete(d);
.Callback<string, string, bool>((s, d, o) =>
{
if (File.Exists(d) && o)
{
File.Delete(d);
}
File.Move(s, d);
});

@ -7,7 +7,8 @@ using NzbDrone.Test.Common;
namespace NzbDrone.Common.Test.DiskTests
{
public abstract class FreeSpaceFixtureBase<TSubject> : TestBase<TSubject> where TSubject : class, IDiskProvider
public abstract class FreeSpaceFixtureBase<TSubject> : TestBase<TSubject>
where TSubject : class, IDiskProvider
{
[Test]
public void should_get_free_space_for_folder()

@ -15,7 +15,6 @@ namespace NzbDrone.Common.Test.EnsureTest
Ensure.That(path, () => path).IsValidPath();
}
[TestCase(@"/var/user/file with, comma.mkv")]
public void EnsureLinuxPath(string path)
{

@ -10,13 +10,11 @@ namespace NzbDrone.Common.Test
[TestFixture]
public class IAppDirectoryInfoTest : TestBase<AppFolderInfo>
{
[Test]
public void StartupPath_should_not_be_empty()
{
Subject.StartUpFolder.Should().NotBeNullOrWhiteSpace();
Path.IsPathRooted(Subject.StartUpFolder).Should().BeTrue("Path is not rooted");
}
[Test]

@ -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));
}
}
}

@ -26,7 +26,6 @@ namespace NzbDrone.Common.Test.EnvironmentTests
args.Flags.Contains("t").Should().BeTrue();
}
[TestCase("/key=value")]
[TestCase("/KEY=value")]
[TestCase(" /key=\"value\"")]
@ -37,7 +36,6 @@ namespace NzbDrone.Common.Test.EnvironmentTests
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 @@ namespace NzbDrone.Common.Test.EnvironmentTests
args.PreservedArguments.Should().Be(preserved);
}
[Test]
public void should_preserver_both()
{

@ -56,7 +56,7 @@ namespace NzbDrone.Common.Test.ExtensionTests.IEnumerableExtensionTests
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");
}
}

@ -24,7 +24,6 @@ namespace NzbDrone.Common.Test.ExtensionTests
public void should_return_false_for_public_ip_address(string ipAddress)
{
IPAddress.Parse(ipAddress).IsLocalAddress().Should().BeFalse();
}
}
}

@ -18,4 +18,4 @@ namespace NzbDrone.Common.Test
HashUtil.AnonymousToken().Should().Be(HashUtil.AnonymousToken());
}
}
}
}

@ -23,7 +23,8 @@ namespace NzbDrone.Common.Test.Http
[Ignore("httpbin is bugged")]
[IntegrationTest]
[TestFixture(typeof(ManagedHttpDispatcher))]
public class HttpClientFixture<TDispatcher> : TestBase<HttpClient> where TDispatcher : IHttpDispatcher
public class HttpClientFixture<TDispatcher> : TestBase<HttpClient>
where TDispatcher : IHttpDispatcher
{
private string[] _httpBinHosts;
private int _httpBinSleep;
@ -35,6 +36,7 @@ namespace NzbDrone.Common.Test.Http
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 @@ namespace NzbDrone.Common.Test.Http
{
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 @@ namespace NzbDrone.Common.Test.Http
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 @@ namespace NzbDrone.Common.Test.Http
[Test]
public void should_call_interceptor()
{
Mocker.SetConstant<IEnumerable<IHttpRequestInterceptor>>(new [] { Mocker.GetMock<IHttpRequestInterceptor>().Object });
Mocker.SetConstant<IEnumerable<IHttpRequestInterceptor>>(new[] { Mocker.GetMock<IHttpRequestInterceptor>().Object });
Mocker.GetMock<IHttpRequestInterceptor>()
.Setup(v => v.PreRequest(It.IsAny<HttpRequest>()))

@ -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
{

@ -35,7 +35,6 @@ namespace NzbDrone.Common.Test.Http
var request = builder.Resource("/v1/").Build();
request.Url.FullUri.Should().Be("http://domain/v1/");
}
}
}
}

@ -6,4 +6,4 @@ namespace NzbDrone.Common.Test.Http
public class HttpRequestFixture
{
}
}
}

@ -27,4 +27,4 @@ namespace NzbDrone.Common.Test.Http
Subject.GetUserAgent(false).Should().NotBeNullOrWhiteSpace();
}
}
}
}

@ -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 @@ namespace NzbDrone.Common.Test.InstrumentationTests
[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 @@ namespace NzbDrone.Common.Test.InstrumentationTests
[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 @@ namespace NzbDrone.Common.Test.InstrumentationTests
[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 @@ namespace NzbDrone.Common.Test.InstrumentationTests
[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")]

@ -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 @@ namespace NzbDrone.Common.Test.InstrumentationTests
[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 @@ namespace NzbDrone.Common.Test.InstrumentationTests
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 @@ namespace NzbDrone.Common.Test.InstrumentationTests
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();
}
}
}
}

@ -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
{

@ -110,6 +110,7 @@ namespace NzbDrone.Common.Test
_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 @@ namespace NzbDrone.Common.Test
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 @@ namespace NzbDrone.Common.Test
path.ToLower().GetActualCasing().Should().Be(path);
}
[Test]
public void get_actual_casing_should_return_actual_casing_for_local_dir_in_windows()
{

@ -18,7 +18,6 @@ namespace NzbDrone.Common.Test
[TestFixture]
public class ProcessProviderFixture : TestBase<ProcessProvider>
{
[SetUp]
public void Setup()
{
@ -44,7 +43,6 @@ namespace NzbDrone.Common.Test
{
TestLogger.Warn(ex, "{0} when killing process", ex.Message);
}
});
}
@ -134,7 +132,6 @@ namespace NzbDrone.Common.Test
}
}
[Test]
[Platform(Exclude = "MacOsX")]
[Retry(3)]

@ -29,4 +29,4 @@ namespace NzbDrone.Common.Test
handlers.Should().OnlyHaveUniqueItems();
}
}
}
}

@ -36,7 +36,6 @@ namespace NzbDrone.Common.Test
}
}
private void CleanupService()
{
if (Subject.ServiceExist(TEMP_SERVICE_NAME))
@ -62,7 +61,6 @@ namespace NzbDrone.Common.Test
Subject.ServiceExist("random_service_name").Should().BeFalse();
}
[Test]
public void Service_should_be_installed_and_then_uninstalled()
{
@ -123,7 +121,6 @@ namespace NzbDrone.Common.Test
Subject.Start(ALWAYS_INSTALLED_SERVICE);
Assert.Throws<InvalidOperationException>(() => Subject.Start(ALWAYS_INSTALLED_SERVICE));
ExceptionVerification.ExpectedWarns(1);
}
@ -133,15 +130,14 @@ namespace NzbDrone.Common.Test
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());

@ -19,7 +19,6 @@ namespace NzbDrone.Common.Test.TPLTests
}
}
[Test]
[Retry(3)]
public void should_hold_the_call_for_debounce_duration()
@ -33,11 +32,9 @@ namespace NzbDrone.Common.Test.TPLTests
counter.Count.Should().Be(0);
Thread.Sleep(100);
counter.Count.Should().Be(1);
}
[Test]
@ -53,7 +50,6 @@ namespace NzbDrone.Common.Test.TPLTests
counter.Count.Should().Be(0);
Thread.Sleep(200);
debounceFunction.Execute();
@ -63,7 +59,6 @@ namespace NzbDrone.Common.Test.TPLTests
Thread.Sleep(200);
counter.Count.Should().Be(2);
}
[Test]
@ -126,4 +121,4 @@ namespace NzbDrone.Common.Test.TPLTests
counter.Count.Should().Be(1);
}
}
}
}

@ -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
{

@ -73,7 +73,9 @@ namespace NzbDrone.Common
{
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.

@ -21,7 +21,6 @@ namespace NzbDrone.Common.Cache
public CacheManager()
{
_cache = new Cached<ICached>();
}
public void Clear()
@ -61,4 +60,4 @@ namespace NzbDrone.Common.Cache
return (ICachedDictionary<T>)_cache.Get("dict_" + host.FullName + "_" + name, () => new CachedDictionary<T>(fetchFunc, lifeTime));
}
}
}
}

@ -7,7 +7,6 @@ using NzbDrone.Common.Extensions;
namespace NzbDrone.Common.Cache
{
public class Cached<T> : ICached<T>
{
private class CacheItem
@ -144,6 +143,5 @@ namespace NzbDrone.Common.Cache
return collection.Remove(new KeyValuePair<string, CacheItem>(key, value));
}
}
}
}

@ -5,7 +5,6 @@ using System.Diagnostics;
namespace NzbDrone.Common.Cache
{
public class CachedDictionary<TValue> : ICachedDictionary<TValue>
{
private readonly Func<IDictionary<string, TValue>> _fetchFunc;

@ -19,4 +19,4 @@ namespace NzbDrone.Common.Cache
ICollection<T> Values { get; }
}
}
}

@ -24,12 +24,14 @@ namespace NzbDrone.Common.Composition
_container.Register<TService, TImplementation>();
}
public void Register<T>(T instance) where T : class
public void Register<T>(T instance)
where T : class
{
_container.Register<T>(instance);
}
public T Resolve<T>() where T : class
public T Resolve<T>()
where T : class
{
return _container.Resolve<T>();
}
@ -44,7 +46,8 @@ namespace NzbDrone.Common.Composition
_container.Register(serviceType, implementationType);
}
public void Register<TService>(Func<IContainer, TService> factory) where TService : class
public void Register<TService>(Func<IContainer, TService> factory)
where TService : class
{
_container.Register((c, n) => factory(this));
}
@ -67,7 +70,8 @@ namespace NzbDrone.Common.Composition
});
}
public IEnumerable<T> ResolveAll<T>() where T : class
public IEnumerable<T> ResolveAll<T>()
where T : class
{
return _container.ResolveAll<T>();
}
@ -103,8 +107,7 @@ namespace NzbDrone.Common.Composition
.Where(implementation =>
contractType.IsAssignableFrom(implementation) &&
!implementation.IsInterface &&
!implementation.IsAbstract
);
!implementation.IsAbstract);
}
}
}
}

@ -121,6 +121,7 @@ namespace NzbDrone.Common.Composition
{
return;
}
if (implementations.Count == 1)
{
var impl = implementations.Single();

@ -5,20 +5,24 @@ namespace NzbDrone.Common.Composition
{
public interface IContainer
{
void Register<T>(T instance) where T : class;
void Register<T>(T instance)
where T : class;
void Register<TService, TImplementation>()
where TImplementation : class, TService
where TService : class;
T Resolve<T>() where T : class;
T Resolve<T>()
where T : class;
object Resolve(Type type);
void Register(Type serviceType, Type implementationType);
void Register<TService>(Func<IContainer, TService> factory) where TService : class;
void Register<TService>(Func<IContainer, TService> factory)
where TService : class;
void RegisterSingleton(Type service, Type implementation);
IEnumerable<T> ResolveAll<T>() where T : class;
IEnumerable<T> ResolveAll<T>()
where T : class;
void RegisterAllAsSingleton(Type registrationType, IEnumerable<Type> implementationList);
bool IsTypeRegistered(Type type);
IEnumerable<Type> GetImplementations(Type contractType);
}
}
}

@ -28,4 +28,4 @@ namespace NzbDrone.Common.Crypto
}
}
}
}
}

@ -10,19 +10,23 @@ namespace NzbDrone.Common.Disk
{
}
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)
{
}
}

@ -117,6 +117,7 @@ namespace NzbDrone.Common.Disk
{
return File.Exists(path) && path == path.GetActualCasing();
}
default:
{
return File.Exists(path);
@ -367,7 +368,7 @@ namespace NzbDrone.Common.Disk
if (attributes.HasFlag(FileAttributes.ReadOnly))
{
var newAttributes = attributes & ~(FileAttributes.ReadOnly);
var newAttributes = attributes & ~FileAttributes.ReadOnly;
File.SetAttributes(path, newAttributes);
}
}

@ -14,7 +14,7 @@ namespace NzbDrone.Common.Disk
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 @@ namespace NzbDrone.Common.Disk
return realParentPath + partialChildPath;
}
public TransferMode TransferFolder(string sourcePath, string targetPath, TransferMode mode)
{
Ensure.That(sourcePath, () => sourcePath).IsValidPath();
@ -101,14 +101,20 @@ namespace NzbDrone.Common.Disk
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 @@ namespace NzbDrone.Common.Disk
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 @@ namespace NzbDrone.Common.Disk
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 @@ namespace NzbDrone.Common.Disk
{
return TransferMode.HardLink;
}
if (!mode.HasFlag(TransferMode.Copy))
{
throw new IOException("Hardlinking from '" + sourcePath + "' to '" + targetPath + "' failed.");
@ -315,14 +334,14 @@ namespace NzbDrone.Common.Disk
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 @@ namespace NzbDrone.Common.Disk
_diskProvider.DeleteFile(sourcePath);
return TransferMode.Move;
}
TryMoveFileVerified(sourcePath, targetPath, originalSize);
return TransferMode.Move;
}

@ -6,7 +6,8 @@ namespace NzbDrone.Common.Disk
{
public string Filename { get; set; }
public FileAlreadyExistsException(string message, string filename) : base(message)
public FileAlreadyExistsException(string message, string filename)
: base(message)
{
Filename = filename;
}

@ -125,7 +125,6 @@ namespace NzbDrone.Common.Disk
result.Files = GetFiles(path);
}
}
catch (DirectoryNotFoundException)
{
return new FileSystemResult { Parent = GetParent(path) };

@ -54,7 +54,11 @@ namespace NzbDrone.Common.Disk
{
get
{
if (MAX_PATH == 0) DetectLongPathLimits();
if (MAX_PATH == 0)
{
DetectLongPathLimits();
}
return MAX_PATH;
}
}
@ -63,7 +67,11 @@ namespace NzbDrone.Common.Disk
{
get
{
if (MAX_NAME == 0) DetectLongPathLimits();
if (MAX_NAME == 0)
{
DetectLongPathLimits();
}
return MAX_NAME;
}
}

@ -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)
{
}
}

@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Generic;
using System.Linq;
using NzbDrone.Common.Extensions;
@ -44,22 +44,36 @@ namespace NzbDrone.Common.Disk
{
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 @@ namespace NzbDrone.Common.Disk
{
path = path.Replace("//", "/");
}
return path;
}
@ -98,11 +113,12 @@ namespace NzbDrone.Common.Disk
{
return _path.StartsWith(@"\\") || HasWindowsDriveLetter(_path);
}
if (IsUnixPath)
{
return _path.StartsWith("/");
}
return false;
}
}
@ -117,7 +133,7 @@ namespace NzbDrone.Common.Disk
{
return new OsPath(null);
}
return new OsPath(_path.Substring(0, index), _kind).AsDirectory();
}
}
@ -141,7 +157,7 @@ namespace NzbDrone.Common.Disk
return path;
}
return _path.Substring(index).Trim('\\', '/');
}
}
@ -196,10 +212,12 @@ namespace NzbDrone.Common.Disk
{
return Equals((OsPath)obj);
}
if (obj is string)
{
return Equals(new OsPath(obj as string));
}
return false;
}
@ -217,6 +235,7 @@ namespace NzbDrone.Common.Disk
case OsPathKind.Unix:
return new OsPath(_path.TrimEnd('/') + "/", _kind);
}
return this;
}
@ -250,7 +269,10 @@ namespace NzbDrone.Common.Disk
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 @@ namespace NzbDrone.Common.Disk
{
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 @@ namespace NzbDrone.Common.Disk
{
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 @@ namespace NzbDrone.Common.Disk
{
return new OsPath(string.Join("\\", newFragments), OsPathKind.Unknown);
}
return new OsPath(string.Join("/", newFragments), OsPathKind.Unknown);
}
}

@ -20,4 +20,4 @@ namespace NzbDrone.Common.EnsureThat
return new TypeParam(name, value.GetType());
}
}
}
}

@ -9,7 +9,9 @@ namespace NzbDrone.Common.EnsureThat
public static Param<bool> IsTrue(this Param<bool> param)
{
if (!param.Value)
{
throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotTrue);
}
return param;
}
@ -18,9 +20,11 @@ namespace NzbDrone.Common.EnsureThat
public static Param<bool> IsFalse(this Param<bool> param)
{
if (param.Value)
{
throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotFalse);
}
return param;
}
}
}
}

@ -10,10 +10,13 @@ namespace NzbDrone.Common.EnsureThat
public static class EnsureCollectionExtensions
{
[DebuggerStepThrough]
public static Param<T> HasItems<T>(this Param<T> param) where T : class, ICollection
public static Param<T> HasItems<T>(this Param<T> 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 @@ namespace NzbDrone.Common.EnsureThat
public static Param<Collection<T>> HasItems<T>(this Param<Collection<T>> param)
{
if (param.Value == null || param.Value.Count < 1)
{
throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsEmptyCollection);
}
return param;
}
@ -31,7 +36,9 @@ namespace NzbDrone.Common.EnsureThat
public static Param<IEnumerable<T>> HasItems<T>(this Param<IEnumerable<T>> param)
{
if (param.Value == null || !param.Value.Any())
{
throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsEmptyCollection);
}
return param;
}
@ -40,7 +47,9 @@ namespace NzbDrone.Common.EnsureThat
public static Param<T[]> HasItems<T>(this Param<T[]> param)
{
if (param.Value == null || param.Value.Length < 1)
{
throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsEmptyCollection);
}
return param;
}
@ -49,19 +58,22 @@ namespace NzbDrone.Common.EnsureThat
public static Param<List<T>> HasItems<T>(this Param<List<T>> param)
{
if (param.Value == null || param.Value.Count < 1)
{
throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsEmptyCollection);
}
return param;
}
[DebuggerStepThrough]
public static Param<IDictionary<TKey, TValue>> HasItems<TKey, TValue>(this Param<IDictionary<TKey, TValue>> param)
{
if (param.Value == null || param.Value.Count < 1)
{
throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsEmptyCollection);
}
return param;
}
}
}
}

@ -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<DateTime> IsLt(this Param<DateTime> 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 @@ namespace NzbDrone.Common.EnsureThat
public static Param<DateTime> IsLte(this Param<DateTime> 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 @@ namespace NzbDrone.Common.EnsureThat
public static Param<DateTime> IsGt(this Param<DateTime> 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 @@ namespace NzbDrone.Common.EnsureThat
public static Param<DateTime> IsGte(this Param<DateTime> 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 @@ namespace NzbDrone.Common.EnsureThat
public static Param<DateTime> IsInRange(this Param<DateTime> 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 @@ namespace NzbDrone.Common.EnsureThat
public static Param<DateTime> IsUtc(this Param<DateTime> 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<DateTime> IsValid(this Param<DateTime> param)
{
return IsGt(param, _minTime);
}
}
}
}

@ -10,7 +10,9 @@ namespace NzbDrone.Common.EnsureThat
public static Param<decimal> IsLt(this Param<decimal> 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 @@ namespace NzbDrone.Common.EnsureThat
public static Param<decimal> IsLte(this Param<decimal> 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 @@ namespace NzbDrone.Common.EnsureThat
public static Param<decimal> IsGt(this Param<decimal> 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 @@ namespace NzbDrone.Common.EnsureThat
public static Param<decimal> IsGte(this Param<decimal> 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 @@ namespace NzbDrone.Common.EnsureThat
public static Param<decimal> IsInRange(this Param<decimal> 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;
}
}
}
}

@ -10,7 +10,9 @@ namespace NzbDrone.Common.EnsureThat
public static Param<double> IsLt(this Param<double> 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 @@ namespace NzbDrone.Common.EnsureThat
public static Param<double> IsLte(this Param<double> 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 @@ namespace NzbDrone.Common.EnsureThat
public static Param<double> IsGt(this Param<double> 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 @@ namespace NzbDrone.Common.EnsureThat
public static Param<double> IsGte(this Param<double> 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 @@ namespace NzbDrone.Common.EnsureThat
public static Param<double> IsInRange(this Param<double> 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;
}
}
}
}

@ -10,9 +10,11 @@ namespace NzbDrone.Common.EnsureThat
public static Param<Guid> IsNotEmpty(this Param<Guid> param)
{
if (Guid.Empty.Equals(param.Value))
{
throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsEmptyGuid);
}
return param;
}
}
}
}

@ -10,7 +10,9 @@ namespace NzbDrone.Common.EnsureThat
public static Param<int> IsLessThan(this Param<int> 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 @@ namespace NzbDrone.Common.EnsureThat
public static Param<int> IsLessThanOrEqualTo(this Param<int> 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 @@ namespace NzbDrone.Common.EnsureThat
public static Param<int> IsGreaterThan(this Param<int> 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 @@ namespace NzbDrone.Common.EnsureThat
public static Param<int> IsGreaterThanZero(this Param<int> param)
{
if (param.Value <= 0)
{
throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotGt.Inject(param.Value, 0));
}
return param;
}
@ -46,7 +54,9 @@ namespace NzbDrone.Common.EnsureThat
public static Param<int> IsGreaterOrEqualTo(this Param<int> 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 @@ namespace NzbDrone.Common.EnsureThat
public static Param<int> IsInRange(this Param<int> 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;
}
}
}
}

@ -10,7 +10,9 @@ namespace NzbDrone.Common.EnsureThat
public static Param<long> IsLt(this Param<long> 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 @@ namespace NzbDrone.Common.EnsureThat
public static Param<long> IsLte(this Param<long> 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 @@ namespace NzbDrone.Common.EnsureThat
public static Param<long> IsGt(this Param<long> 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 @@ namespace NzbDrone.Common.EnsureThat
public static Param<long> IsGte(this Param<long> 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 @@ namespace NzbDrone.Common.EnsureThat
public static Param<long> IsInRange(this Param<long> 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;
}
}
}
}

@ -6,12 +6,15 @@ namespace NzbDrone.Common.EnsureThat
public static class EnsureNullableValueTypeExtensions
{
[DebuggerStepThrough]
public static Param<T?> IsNotNull<T>(this Param<T?> param) where T : struct
public static Param<T?> IsNotNull<T>(this Param<T?> param)
where T : struct
{
if (param.Value == null || !param.Value.HasValue)
{
throw ExceptionFactory.CreateForParamNullValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotNull);
}
return param;
}
}
}
}

@ -6,12 +6,15 @@ namespace NzbDrone.Common.EnsureThat
public static class EnsureObjectExtensions
{
[DebuggerStepThrough]
public static Param<T> IsNotNull<T>(this Param<T> param) where T : class
public static Param<T> IsNotNull<T>(this Param<T> param)
where T : class
{
if (param.Value == null)
{
throw ExceptionFactory.CreateForParamNullValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotNull);
}
return param;
}
}
}
}

@ -10,7 +10,9 @@ namespace NzbDrone.Common.EnsureThat
public static Param<short> IsLt(this Param<short> 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 @@ namespace NzbDrone.Common.EnsureThat
public static Param<short> IsLte(this Param<short> 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 @@ namespace NzbDrone.Common.EnsureThat
public static Param<short> IsGt(this Param<short> 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 @@ namespace NzbDrone.Common.EnsureThat
public static Param<short> IsGte(this Param<short> 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 @@ namespace NzbDrone.Common.EnsureThat
public static Param<short> IsInRange(this Param<short> 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;
}
}
}
}

@ -13,7 +13,9 @@ namespace NzbDrone.Common.EnsureThat
public static Param<string> IsNotNullOrWhiteSpace(this Param<string> param)
{
if (string.IsNullOrWhiteSpace(param.Value))
{
throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotNullOrWhiteSpace);
}
return param;
}
@ -22,7 +24,9 @@ namespace NzbDrone.Common.EnsureThat
public static Param<string> IsNotNullOrEmpty(this Param<string> param)
{
if (string.IsNullOrEmpty(param.Value))
{
throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotNullOrEmpty);
}
return param;
}
@ -31,15 +35,21 @@ namespace NzbDrone.Common.EnsureThat
public static Param<string> HasLengthBetween(this Param<string> 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 @@ namespace NzbDrone.Common.EnsureThat
public static Param<string> IsLongerThan(this Param<string> 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 @@ namespace NzbDrone.Common.EnsureThat
{
throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_NoMatch.Inject(param.Value, match));
}
return param;
}
@ -78,7 +93,9 @@ namespace NzbDrone.Common.EnsureThat
public static Param<string> IsRelativePath(this Param<string> param)
{
if (string.IsNullOrWhiteSpace(param.Value))
{
throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotNullOrWhiteSpace);
}
if (!param.Value.EndsWith("\\"))
{
@ -97,9 +114,14 @@ namespace NzbDrone.Common.EnsureThat
public static Param<string> IsValidPath(this Param<string> 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)
{

@ -9,7 +9,7 @@ namespace NzbDrone.Common.EnsureThat
{
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 @@ namespace NzbDrone.Common.EnsureThat
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;
}
}
}
}

@ -19,4 +19,4 @@ namespace NzbDrone.Common.EnsureThat
return new ArgumentNullException(paramName, message);
}
}
}
}

@ -9,7 +9,9 @@ namespace NzbDrone.Common.EnsureThat
var path = "";
if (e.Expression is MemberExpression parent)
{
path = parent.ToPath() + ".";
}
return path + e.Member.Name;
}
@ -22,17 +24,23 @@ namespace NzbDrone.Common.EnsureThat
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 @@ namespace NzbDrone.Common.EnsureThat
return null;
}
}
}
}

@ -16,9 +16,10 @@ namespace NzbDrone.Common.EnsureThat
{
public readonly T Value;
internal Param(string name, T value) : base(name)
internal Param(string name, T value)
: base(name)
{
Value = value;
}
}
}
}

@ -12,4 +12,4 @@ namespace NzbDrone.Common.EnsureThat
Type = type;
}
}
}
}

@ -95,9 +95,20 @@ namespace NzbDrone.Common.EnvironmentInfo
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");

@ -1,6 +1,5 @@
namespace NzbDrone.Common.EnvironmentInfo
{
public interface IOsVersionAdapter
{
bool Enabled { get; }

@ -34,6 +34,7 @@ namespace NzbDrone.Common.EnvironmentInfo
Os = Os.Windows;
break;
}
case PlatformID.MacOSX:
case PlatformID.Unix:
{

@ -2,8 +2,6 @@ namespace NzbDrone.Common.EnvironmentInfo
{
public class OsVersionModel
{
public OsVersionModel(string name, string version, string fullName = null)
{
Name = Trim(name);

@ -2,7 +2,6 @@ using System;
namespace NzbDrone.Common.EnvironmentInfo
{
public enum PlatformType
{
DotNet = 0,

@ -124,7 +124,6 @@ namespace NzbDrone.Common.EnvironmentInfo
public static bool IsProduction { get; }
public static bool IsDevelopment { get; }
private static bool InternalIsTesting()
{
try
@ -153,7 +152,6 @@ namespace NzbDrone.Common.EnvironmentInfo
}
catch
{
}
try

@ -7,19 +7,16 @@ namespace NzbDrone.Common.Exceptions
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)

@ -7,19 +7,16 @@ namespace NzbDrone.Common.Exceptions
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 @@ namespace NzbDrone.Common.Exceptions
public SonarrStartupException(Exception innerException)
: base("Sonarr failed to start: " + innerException.Message)
{
}
}
}

@ -9,4 +9,4 @@ namespace NzbDrone.Common.Expansive
{
}
}
}
}

@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Dynamic;
@ -11,7 +11,6 @@ namespace NzbDrone.Common.Expansive
{
private static PatternStyle _patternStyle;
public static bool RequireAllExpansions { get; set; }
public static Func<string, string> DefaultExpansionFactory { get; set; }
@ -26,7 +25,6 @@ namespace NzbDrone.Common.Expansive
return source.Expand(DefaultExpansionFactory);
}
public static string Expand(this string source, params string[] args)
{
var output = source;
@ -50,9 +48,11 @@ namespace NzbDrone.Common.Expansive
{
tokenIndex = tokens.IndexOf(token);
}
output = Regex.Replace(output, _patternStyle.OutputFilter(match.Value), "{" + tokenIndex + "}");
}
}
var newArgs = new List<string>();
foreach (var arg in args)
{
@ -63,15 +63,20 @@ namespace NzbDrone.Common.Expansive
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 @@ namespace NzbDrone.Common.Expansive
return source.ExpandInternal(expansionFactory);
}
public static string Expand(this string source, object model)
{
return source.ExpandInternal(
@ -116,7 +118,10 @@ namespace NzbDrone.Common.Expansive
private static string ExpandInternal(this string source, Func<string, string> expansionFactory)
{
if (expansionFactory == null) throw new ApplicationException("ExpansionFactory not defined.\nDefine a DefaultExpansionFactory or call Expand(source, Func<string, string> expansionFactory))");
if (expansionFactory == null)
{
throw new ApplicationException("ExpansionFactory not defined.\nDefine a DefaultExpansionFactory or call Expand(source, Func<string, string> expansionFactory))");
}
var pattern = new Regex(_patternStyle.TokenMatchPattern, RegexOptions.IgnoreCase);
@ -139,9 +144,12 @@ namespace NzbDrone.Common.Expansive
// 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 @@ namespace NzbDrone.Common.Expansive
output = Regex.Replace(output, patternStyle.OutputFilter(match.Value), child);
}
}
return output;
}
@ -171,7 +180,11 @@ namespace NzbDrone.Common.Expansive
{
var result = new ExpandoObject();
var d = result as IDictionary<string, object>; //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 @@ namespace NzbDrone.Common.Expansive
d.Add(item.Name, item.GetValue(o, null));
}
}
return result;
}
/// <summary>
/// Turns the object into a Dictionary
/// </summary>
@ -195,4 +210,4 @@ namespace NzbDrone.Common.Expansive
return (IDictionary<string, object>)thingy.ToExpando();
}
}
}
}

@ -9,4 +9,4 @@ namespace NzbDrone.Common.Expansive
public Func<string, string> TokenReplaceFilter { get; set; }
public Func<string, string> OutputFilter { get; set; }
}
}
}

@ -8,4 +8,4 @@
Value = rootValue;
}
}
}
}

@ -1,4 +1,4 @@
using System.Collections.Generic;
using System.Collections.Generic;
namespace NzbDrone.Common.Expansive
{
@ -7,25 +7,29 @@ namespace NzbDrone.Common.Expansive
private List<T> _CallTree;
private TreeNode<T> _Parent;
public TreeNode(T Value)
public TreeNode(T value)
{
this.Value = Value;
Value = value;
Parent = null;
Children = new TreeNodeList<T>(this);
_CallTree = new List<T>();
}
public TreeNode(T Value, TreeNode<T> Parent)
public TreeNode(T value, TreeNode<T> parent)
{
this.Value = Value;
this.Parent = Parent;
Value = value;
Parent = parent;
Children = new TreeNodeList<T>(this);
_CallTree = new List<T>();
}
public TreeNode<T> Parent
{
get { return _Parent; }
get
{
return _Parent;
}
set
{
if (value == _Parent)
@ -58,6 +62,7 @@ namespace NzbDrone.Common.Expansive
{
node = node.Parent;
}
return node;
}
}
@ -75,11 +80,16 @@ namespace NzbDrone.Common.Expansive
node = node.Parent;
_CallTree.Add(node.Value);
}
return _CallTree;
}
private set { _CallTree = value; }
private set
{
_CallTree = value;
}
}
public T Value { get; set; }
}
}
}

@ -6,27 +6,26 @@ namespace NzbDrone.Common.Expansive
{
public TreeNode<T> Parent;
public TreeNodeList(TreeNode<T> Parent)
public TreeNodeList(TreeNode<T> parent)
{
this.Parent = Parent;
this.Parent = parent;
}
public new TreeNode<T> Add(TreeNode<T> Node)
public new TreeNode<T> Add(TreeNode<T> node)
{
base.Add(Node);
Node.Parent = Parent;
return Node;
base.Add(node);
node.Parent = Parent;
return node;
}
public TreeNode<T> Add(T Value)
public TreeNode<T> Add(T value)
{
return Add(new TreeNode<T>(Value));
return Add(new TreeNode<T>(value));
}
public override string ToString()
{
return "Count=" + Count.ToString();
}
}
}
}

@ -7,30 +7,37 @@ namespace NzbDrone.Common.Extensions
{
public static class ExceptionExtensions
{
public static T WithData<T>(this T ex, string key, string value) where T : Exception
public static T WithData<T>(this T ex, string key, string value)
where T : Exception
{
ex.AddData(key, value);
return ex;
}
public static T WithData<T>(this T ex, string key, int value) where T : Exception
public static T WithData<T>(this T ex, string key, int value)
where T : Exception
{
ex.AddData(key, value.ToString());
return ex;
}
public static T WithData<T>(this T ex, string key, Http.HttpUri value) where T : Exception
public static T WithData<T>(this T ex, string key, Http.HttpUri value)
where T : Exception
{
ex.AddData(key, value.ToString());
return ex;
}
public static T WithData<T>(this T ex, Http.HttpResponse response, int maxSampleLength = 512) where T : Exception
public static T WithData<T>(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 @@ namespace NzbDrone.Common.Extensions
{
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;
}

@ -7,9 +7,11 @@ namespace NzbDrone.Common.Extensions
{
public static class EnumerableExtensions
{
public static IEnumerable<TFirst> IntersectBy<TFirst, TSecond, TKey>(this IEnumerable<TFirst> first, Func<TFirst, TKey> firstKeySelector,
IEnumerable<TSecond> second, Func<TSecond, TKey> secondKeySelector,
IEqualityComparer<TKey> keyComparer)
public static IEnumerable<TFirst> IntersectBy<TFirst, TSecond, TKey>(this IEnumerable<TFirst> first,
Func<TFirst, TKey> firstKeySelector,
IEnumerable<TSecond> second,
Func<TSecond, TKey> secondKeySelector,
IEqualityComparer<TKey> keyComparer)
{
var keys = new HashSet<TKey>(second.Select(secondKeySelector), keyComparer);
@ -25,9 +27,11 @@ namespace NzbDrone.Common.Extensions
}
}
public static IEnumerable<TFirst> ExceptBy<TFirst, TSecond, TKey>(this IEnumerable<TFirst> first, Func<TFirst, TKey> firstKeySelector,
IEnumerable<TSecond> second, Func<TSecond, TKey> secondKeySelector,
IEqualityComparer<TKey> keyComparer)
public static IEnumerable<TFirst> ExceptBy<TFirst, TSecond, TKey>(this IEnumerable<TFirst> first,
Func<TFirst, TKey> firstKeySelector,
IEnumerable<TSecond> second,
Func<TSecond, TKey> secondKeySelector,
IEqualityComparer<TKey> keyComparer)
{
var keys = new HashSet<TKey>(second.Select(secondKeySelector), keyComparer);
var matchedKeys = new HashSet<TKey>();
@ -56,6 +60,7 @@ namespace NzbDrone.Common.Extensions
result[key] = item;
}
}
return result;
}
@ -70,6 +75,7 @@ namespace NzbDrone.Common.Extensions
result[key] = valueSelector(item);
}
}
return result;
}

@ -11,8 +11,15 @@ namespace NzbDrone.Common.Extensions
{
const int bytesInKb = 1024;
if (bytes < 0) return "-" + SizeSuffix(-bytes);
if (bytes == 0) return "0 B";
if (bytes < 0)
{
return "-" + SizeSuffix(-bytes);
}
if (bytes == 0)
{
return "0 B";
}
var mag = (int)Math.Log(bytes, bytesInKb);
var adjustedSize = bytes / (decimal)Math.Pow(bytesInKb, mag);

@ -6,9 +6,20 @@ namespace NzbDrone.Common.Extensions
{
public static int LevenshteinDistance(this string text, string other, int costInsert = 1, int costDelete = 1, int costSubstitute = 1)
{
if (text == other) return 0;
if (text.Length == 0) return other.Length * costInsert;
if (other.Length == 0) return text.Length * costDelete;
if (text == other)
{
return 0;
}
if (text.Length == 0)
{
return other.Length * costInsert;
}
if (other.Length == 0)
{
return text.Length * costDelete;
}
int[] matrix = new int[other.Length + 1];
@ -47,4 +58,4 @@ namespace NzbDrone.Common.Extensions
return expected.LevenshteinDistance(other, 1, 3, 3);
}
}
}
}

@ -4,10 +4,11 @@ namespace NzbDrone.Common.Extensions
{
public static class ObjectExtensions
{
public static T JsonClone<T>(this T source) where T : new()
public static T JsonClone<T>(this T source)
where T : new()
{
var json = source.ToJson();
return Json.Deserialize<T>(json);
}
}
}
}

@ -113,6 +113,7 @@ namespace NzbDrone.Common.Extensions
{
parentPath = parentPath.TrimEnd(Path.DirectorySeparatorChar);
}
if (childPath != "/" && !parentPath.EndsWith(":\\"))
{
childPath = childPath.TrimEnd(Path.DirectorySeparatorChar);

@ -14,6 +14,7 @@ namespace NzbDrone.Common.Extensions
{
ms.Write(buffer, 0, read);
}
return ms.ToArray();
}
}

@ -18,7 +18,11 @@ namespace NzbDrone.Common.Extensions
public static object NullSafe(this object target)
{
if (target != null) return target;
if (target != null)
{
return target;
}
return "[NULL]";
}
@ -76,7 +80,9 @@ namespace NzbDrone.Common.Extensions
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 @@ namespace NzbDrone.Common.Extensions
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 @@ namespace NzbDrone.Common.Extensions
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 @@ namespace NzbDrone.Common.Extensions
{
return source.Contains(value, StringComparer.InvariantCultureIgnoreCase);
}
public static string ToUrlSlug(this string value)
{
//First to lower case

@ -28,7 +28,6 @@ namespace NzbDrone.Common.Extensions
}
return true;
}
}
}

@ -24,6 +24,7 @@ namespace NzbDrone.Common
}
}
}
return $"{mCrc:x8}";
}

@ -197,6 +197,7 @@ namespace NzbDrone.Common.Http.Dispatchers
{
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();
}

@ -12,4 +12,4 @@ namespace NzbDrone.Common.Http
return request;
}
}
}
}

@ -6,7 +6,7 @@
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)

@ -18,10 +18,12 @@ namespace NzbDrone.Common.Http
HttpResponse Execute(HttpRequest request);
void DownloadFile(string url, string fileName);
HttpResponse Get(HttpRequest request);
HttpResponse<T> Get<T>(HttpRequest request) where T : new();
HttpResponse<T> Get<T>(HttpRequest request)
where T : new();
HttpResponse Head(HttpRequest request);
HttpResponse Post(HttpRequest request);
HttpResponse<T> Post<T>(HttpRequest request) where T : new();
HttpResponse<T> Post<T>(HttpRequest request)
where T : new();
}
public class HttpClient : IHttpClient
@ -258,11 +260,13 @@ namespace NzbDrone.Common.Http
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 @@ namespace NzbDrone.Common.Http
if (File.Exists(fileNamePart))
{
File.Delete(fileNamePart);
}
}
}
}
@ -281,7 +285,8 @@ namespace NzbDrone.Common.Http
return Execute(request);
}
public HttpResponse<T> Get<T>(HttpRequest request) where T : new()
public HttpResponse<T> Get<T>(HttpRequest request)
where T : new()
{
var response = Get(request);
CheckResponseContentType(response);
@ -300,7 +305,8 @@ namespace NzbDrone.Common.Http
return Execute(request);
}
public HttpResponse<T> Post<T>(HttpRequest request) where T : new()
public HttpResponse<T> Post<T>(HttpRequest request)
where T : new()
{
var response = Post(request);
CheckResponseContentType(response);

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save