Merge branch 'develop'

This commit is contained in:
Mark McDowall 2014-03-17 16:44:53 -07:00
commit 591daa0917
193 changed files with 2432 additions and 487 deletions

View File

@ -78,6 +78,7 @@ module.exports = function (grunt) {
'**/*.png', '**/*.png',
'**/*.jpg', '**/*.jpg',
'**/*.ico', '**/*.ico',
'**/*.swf',
'**/FontAwesome/*.*', '**/FontAwesome/*.*',
'**/fonts/*.*' '**/fonts/*.*'
], ],

View File

@ -119,7 +119,7 @@ Function PackageOsx()
if(Test-Path $outputFolderOsx) if(Test-Path $outputFolderOsx)
{ {
Remove-Item -Recurse -Force $outputFolderMono -ErrorAction Continue Remove-Item -Recurse -Force $outputFolderOsx -ErrorAction Continue
} }
Copy-Item $outputFolderMono $outputFolderOsx -recurse Copy-Item $outputFolderMono $outputFolderOsx -recurse

View File

@ -295,6 +295,14 @@ namespace Microsoft.AspNet.SignalR.Messaging
Trace.TraceEvent(TraceEventType.Verbose, 0, "Dispoing the broker"); Trace.TraceEvent(TraceEventType.Verbose, 0, "Dispoing the broker");
//Check if OS is not Windows and exit
var platform = (int)Environment.OSVersion.Platform;
if ((platform == 4) || (platform == 6) || (platform == 128))
{
return;
}
// Wait for all threads to stop working // Wait for all threads to stop working
WaitForDrain(); WaitForDrain();

View File

@ -275,6 +275,7 @@
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<Target Name="AfterBuild"> <Target Name="AfterBuild">
</Target> </Target>
<Import Project="$(SolutionDir)\.nuget\NuGet.targets" Condition="Exists('$(SolutionDir)\.nuget\NuGet.targets')" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it. <!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets. Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild"> <Target Name="BeforeBuild">

View File

@ -101,6 +101,7 @@
</ItemGroup> </ItemGroup>
<Import Project="..\Common\Microsoft.AspNet.SignalR.targets" /> <Import Project="..\Common\Microsoft.AspNet.SignalR.targets" />
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<Import Project="$(SolutionDir)\.nuget\NuGet.targets" Condition="Exists('$(SolutionDir)\.nuget\NuGet.targets')" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it. <!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets. Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild"> <Target Name="BeforeBuild">

View File

@ -4,6 +4,7 @@ using Nancy;
using Nancy.Bootstrapper; using Nancy.Bootstrapper;
using NzbDrone.Api.Extensions; using NzbDrone.Api.Extensions;
using NzbDrone.Api.Extensions.Pipelines; using NzbDrone.Api.Extensions.Pipelines;
using NzbDrone.Common;
using NzbDrone.Common.EnvironmentInfo; using NzbDrone.Common.EnvironmentInfo;
using NzbDrone.Core.Configuration; using NzbDrone.Core.Configuration;
@ -12,12 +13,12 @@ namespace NzbDrone.Api.Authentication
public class EnableStatelessAuthInNancy : IRegisterNancyPipeline public class EnableStatelessAuthInNancy : IRegisterNancyPipeline
{ {
private readonly IAuthenticationService _authenticationService; private readonly IAuthenticationService _authenticationService;
private readonly IConfigFileProvider _configFileProvider; private static String API_KEY;
public EnableStatelessAuthInNancy(IAuthenticationService authenticationService, IConfigFileProvider configFileProvider) public EnableStatelessAuthInNancy(IAuthenticationService authenticationService, IConfigFileProvider configFileProvider)
{ {
_authenticationService = authenticationService; _authenticationService = authenticationService;
_configFileProvider = configFileProvider; API_KEY = configFileProvider.ApiKey;
} }
public void Register(IPipelines pipelines) public void Register(IPipelines pipelines)
@ -36,9 +37,9 @@ namespace NzbDrone.Api.Authentication
var authorizationHeader = context.Request.Headers.Authorization; var authorizationHeader = context.Request.Headers.Authorization;
var apiKeyHeader = context.Request.Headers["X-Api-Key"].FirstOrDefault(); var apiKeyHeader = context.Request.Headers["X-Api-Key"].FirstOrDefault();
var apiKey = String.IsNullOrWhiteSpace(apiKeyHeader) ? authorizationHeader : apiKeyHeader; var apiKey = apiKeyHeader.IsNullOrWhiteSpace() ? authorizationHeader : apiKeyHeader;
if (context.Request.IsApiRequest() && !ValidApiKey(apiKey) && !_authenticationService.IsAuthenticated(context)) if (context.Request.IsApiRequest() && !ValidApiKey(apiKey) && !IsAuthenticated(context))
{ {
response = new Response { StatusCode = HttpStatusCode.Unauthorized }; response = new Response { StatusCode = HttpStatusCode.Unauthorized };
} }
@ -48,10 +49,15 @@ namespace NzbDrone.Api.Authentication
private bool ValidApiKey(string apiKey) private bool ValidApiKey(string apiKey)
{ {
if (String.IsNullOrWhiteSpace(apiKey)) return false; if (apiKey.IsNullOrWhiteSpace()) return false;
if (!apiKey.Equals(_configFileProvider.ApiKey)) return false; if (!apiKey.Equals(API_KEY)) return false;
return true; return true;
} }
private bool IsAuthenticated(NancyContext context)
{
return _authenticationService.Enabled && _authenticationService.IsAuthenticated(context);
}
} }
} }

View File

@ -7,6 +7,7 @@ namespace NzbDrone.Api.Config
{ {
public String DownloadedEpisodesFolder { get; set; } public String DownloadedEpisodesFolder { get; set; }
public String DownloadClientWorkingFolders { get; set; } public String DownloadClientWorkingFolders { get; set; }
public Int32 DownloadedEpisodesScanInterval { get; set; }
public Boolean AutoRedownloadFailed { get; set; } public Boolean AutoRedownloadFailed { get; set; }
public Boolean RemoveFailedDownloads { get; set; } public Boolean RemoveFailedDownloads { get; set; }

View File

@ -14,6 +14,7 @@ namespace NzbDrone.Api.Config
public String Password { get; set; } public String Password { get; set; }
public String LogLevel { get; set; } public String LogLevel { get; set; }
public String Branch { get; set; } public String Branch { get; set; }
public Boolean AutoUpdate { get; set; }
public String ApiKey { get; set; } public String ApiKey { get; set; }
public Boolean Torrent { get; set; } public Boolean Torrent { get; set; }
public String SslCertHash { get; set; } public String SslCertHash { get; set; }

View File

@ -1,5 +1,6 @@
using System; using System;
using NzbDrone.Api.REST; using NzbDrone.Api.REST;
using NzbDrone.Core.MediaFiles;
namespace NzbDrone.Api.Config namespace NzbDrone.Api.Config
{ {
@ -9,6 +10,7 @@ namespace NzbDrone.Api.Config
public String RecycleBin { get; set; } public String RecycleBin { get; set; }
public Boolean AutoDownloadPropers { get; set; } public Boolean AutoDownloadPropers { get; set; }
public Boolean CreateEmptySeriesFolders { get; set; } public Boolean CreateEmptySeriesFolders { get; set; }
public FileDateType FileDate { get; set; }
public Boolean SetPermissionsLinux { get; set; } public Boolean SetPermissionsLinux { get; set; }
public String FileChmod { get; set; } public String FileChmod { get; set; }

View File

@ -1,8 +1,8 @@
using System;
using System.IO; using System.IO;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using Nancy; using Nancy;
using NLog; using NLog;
using NzbDrone.Common;
using NzbDrone.Common.Disk; using NzbDrone.Common.Disk;
using NzbDrone.Common.EnvironmentInfo; using NzbDrone.Common.EnvironmentInfo;
using NzbDrone.Core.Configuration; using NzbDrone.Core.Configuration;
@ -12,10 +12,12 @@ namespace NzbDrone.Api.Frontend.Mappers
public class IndexHtmlMapper : StaticResourceMapperBase public class IndexHtmlMapper : StaticResourceMapperBase
{ {
private readonly IDiskProvider _diskProvider; private readonly IDiskProvider _diskProvider;
private readonly IConfigFileProvider _configFileProvider;
private readonly string _indexPath; private readonly string _indexPath;
private static readonly Regex ReplaceRegex = new Regex("(?<=(?:href|src|data-main)=\").*?(?=\")", RegexOptions.Compiled | RegexOptions.IgnoreCase); private static readonly Regex ReplaceRegex = new Regex("(?<=(?:href|src|data-main)=\").*?(?=\")", RegexOptions.Compiled | RegexOptions.IgnoreCase);
private static String API_KEY;
private static String URL_BASE;
public IndexHtmlMapper(IAppFolderInfo appFolderInfo, public IndexHtmlMapper(IAppFolderInfo appFolderInfo,
IDiskProvider diskProvider, IDiskProvider diskProvider,
IConfigFileProvider configFileProvider, IConfigFileProvider configFileProvider,
@ -23,8 +25,10 @@ namespace NzbDrone.Api.Frontend.Mappers
: base(diskProvider, logger) : base(diskProvider, logger)
{ {
_diskProvider = diskProvider; _diskProvider = diskProvider;
_configFileProvider = configFileProvider;
_indexPath = Path.Combine(appFolderInfo.StartUpFolder, "UI", "index.html"); _indexPath = Path.Combine(appFolderInfo.StartUpFolder, "UI", "index.html");
API_KEY = configFileProvider.ApiKey;
URL_BASE = configFileProvider.UrlBase;
} }
protected override string Map(string resourceUrl) protected override string Map(string resourceUrl)
@ -54,12 +58,12 @@ namespace NzbDrone.Api.Frontend.Mappers
{ {
var text = _diskProvider.ReadAllText(_indexPath); var text = _diskProvider.ReadAllText(_indexPath);
text = ReplaceRegex.Replace(text, match => _configFileProvider.UrlBase + match.Value); text = ReplaceRegex.Replace(text, match => URL_BASE + match.Value);
text = text.Replace(".css", ".css?v=" + BuildInfo.Version); text = text.Replace(".css", ".css?v=" + BuildInfo.Version);
text = text.Replace(".js", ".js?v=" + BuildInfo.Version); text = text.Replace(".js", ".js?v=" + BuildInfo.Version);
text = text.Replace("API_ROOT", _configFileProvider.UrlBase + "/api"); text = text.Replace("API_ROOT", URL_BASE + "/api");
text = text.Replace("API_KEY", _configFileProvider.ApiKey); text = text.Replace("API_KEY", API_KEY);
text = text.Replace("APP_VERSION", BuildInfo.Version.ToString()); text = text.Replace("APP_VERSION", BuildInfo.Version.ToString());
return text; return text;

View File

@ -26,7 +26,11 @@ namespace NzbDrone.Api.Frontend.Mappers
public override bool CanHandle(string resourceUrl) public override bool CanHandle(string resourceUrl)
{ {
return resourceUrl.StartsWith("/Content") || resourceUrl.EndsWith(".js") || resourceUrl.EndsWith(".css") || resourceUrl.EndsWith(".ico"); return resourceUrl.StartsWith("/Content") ||
resourceUrl.EndsWith(".js") ||
resourceUrl.EndsWith(".css") ||
resourceUrl.EndsWith(".ico") ||
resourceUrl.EndsWith(".swf");
} }
} }
} }

View File

@ -35,7 +35,7 @@ namespace NzbDrone.Api.Logs
{ {
Id = i + 1, Id = i + 1,
Filename = Path.GetFileName(file), Filename = Path.GetFileName(file),
LastWriteTime = _diskProvider.GetLastFileWrite(file) LastWriteTime = _diskProvider.FileGetLastWriteUtc(file)
}); });
} }

View File

@ -16,7 +16,11 @@ namespace NzbDrone.Api.System
private readonly IConfigFileProvider _configFileProvider; private readonly IConfigFileProvider _configFileProvider;
private readonly IDatabase _database; private readonly IDatabase _database;
public SystemModule(IAppFolderInfo appFolderInfo, IRuntimeInfo runtimeInfo, IRouteCacheProvider routeCacheProvider, IConfigFileProvider configFileProvider, IDatabase database) public SystemModule(IAppFolderInfo appFolderInfo,
IRuntimeInfo runtimeInfo,
IRouteCacheProvider routeCacheProvider,
IConfigFileProvider configFileProvider,
IDatabase database)
: base("system") : base("system")
{ {
_appFolderInfo = appFolderInfo; _appFolderInfo = appFolderInfo;
@ -41,8 +45,10 @@ namespace NzbDrone.Api.System
StartupPath = _appFolderInfo.StartUpFolder, StartupPath = _appFolderInfo.StartUpFolder,
AppData = _appFolderInfo.GetAppDataPath(), AppData = _appFolderInfo.GetAppDataPath(),
OsVersion = OsInfo.Version.ToString(), OsVersion = OsInfo.Version.ToString(),
IsMonoRuntime = OsInfo.IsMono,
IsMono = OsInfo.IsMono, IsMono = OsInfo.IsMono,
IsLinux = OsInfo.IsLinux, IsLinux = OsInfo.IsMono,
IsOsx = OsInfo.IsOsx,
IsWindows = OsInfo.IsWindows, IsWindows = OsInfo.IsWindows,
Branch = _configFileProvider.Branch, Branch = _configFileProvider.Branch,
Authentication = _configFileProvider.AuthenticationEnabled, Authentication = _configFileProvider.AuthenticationEnabled,
@ -50,10 +56,8 @@ namespace NzbDrone.Api.System
SqliteVersion = _database.Version, SqliteVersion = _database.Version,
UrlBase = _configFileProvider.UrlBase UrlBase = _configFileProvider.UrlBase
}.AsResponse(); }.AsResponse();
} }
private Response GetRoutes() private Response GetRoutes()
{ {
return _routeCacheProvider.GetCache().Values.AsResponse(); return _routeCacheProvider.GetCache().Values.AsResponse();

View File

@ -144,7 +144,7 @@ namespace NzbDrone.Common.Test.DiskProviderTests
public void empty_folder_should_return_folder_modified_date() public void empty_folder_should_return_folder_modified_date()
{ {
var tempfolder = new DirectoryInfo(TempFolder); var tempfolder = new DirectoryInfo(TempFolder);
Subject.GetLastFolderWrite(TempFolder).Should().Be(tempfolder.LastWriteTimeUtc); Subject.FolderGetLastWrite(TempFolder).Should().Be(tempfolder.LastWriteTimeUtc);
} }
[Test] [Test]
@ -159,8 +159,8 @@ namespace NzbDrone.Common.Test.DiskProviderTests
Subject.WriteAllText(testFile, "Test"); Subject.WriteAllText(testFile, "Test");
Subject.GetLastFolderWrite(SandboxFolder).Should().BeOnOrAfter(DateTime.UtcNow.AddMinutes(-1)); Subject.FolderGetLastWrite(SandboxFolder).Should().BeOnOrAfter(DateTime.UtcNow.AddMinutes(-1));
Subject.GetLastFolderWrite(SandboxFolder).Should().BeBefore(DateTime.UtcNow.AddMinutes(1)); Subject.FolderGetLastWrite(SandboxFolder).Should().BeBefore(DateTime.UtcNow.AddMinutes(1));
} }
[Test] [Test]
@ -208,7 +208,7 @@ namespace NzbDrone.Common.Test.DiskProviderTests
[Explicit] [Explicit]
public void check_last_write() public void check_last_write()
{ {
Console.WriteLine(Subject.GetLastFolderWrite(_binFolder.FullName)); Console.WriteLine(Subject.FolderGetLastWrite(_binFolder.FullName));
Console.WriteLine(_binFolder.LastWriteTimeUtc); Console.WriteLine(_binFolder.LastWriteTimeUtc);
} }

View File

@ -36,7 +36,7 @@ namespace NzbDrone.Common.Test.DiskProviderTests
[Test] [Test]
public void should_be_able_to_check_space_on_ramdrive() public void should_be_able_to_check_space_on_ramdrive()
{ {
LinuxOnly(); MonoOnly();
Subject.GetAvailableSpace("/run/").Should().NotBe(0); Subject.GetAvailableSpace("/run/").Should().NotBe(0);
} }

View File

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

View File

@ -50,7 +50,7 @@ namespace NzbDrone.Common.Test
[TestCase(@"//CAPITAL//lower// ", @"/CAPITAL/lower")] [TestCase(@"//CAPITAL//lower// ", @"/CAPITAL/lower")]
public void Clean_Path_Linux(string dirty, string clean) public void Clean_Path_Linux(string dirty, string clean)
{ {
LinuxOnly(); MonoOnly();
var result = dirty.CleanFilePath(); var result = dirty.CleanFilePath();
result.Should().Be(clean); result.Should().Be(clean);
@ -139,7 +139,7 @@ namespace NzbDrone.Common.Test
[Test] [Test]
public void get_actual_casing_should_return_original_value_in_linux() public void get_actual_casing_should_return_original_value_in_linux()
{ {
LinuxOnly(); MonoOnly();
var path = Directory.GetCurrentDirectory(); var path = Directory.GetCurrentDirectory();
path.GetActualCasing().Should().Be(path); path.GetActualCasing().Should().Be(path);
path.GetActualCasing().Should().Be(path); path.GetActualCasing().Should().Be(path);

View File

@ -1,8 +1,11 @@
using System; using System;
using System.IO; using System.IO;
using ICSharpCode.SharpZipLib.Core; using ICSharpCode.SharpZipLib.Core;
using ICSharpCode.SharpZipLib.GZip;
using ICSharpCode.SharpZipLib.Tar;
using ICSharpCode.SharpZipLib.Zip; using ICSharpCode.SharpZipLib.Zip;
using NLog; using NLog;
using NzbDrone.Common.EnvironmentInfo;
namespace NzbDrone.Common namespace NzbDrone.Common
{ {
@ -22,8 +25,23 @@ namespace NzbDrone.Common
public void Extract(string compressedFile, string destination) public void Extract(string compressedFile, string destination)
{ {
_logger.Trace("Extracting archive [{0}] to [{1}]", compressedFile, destination); _logger.Debug("Extracting archive [{0}] to [{1}]", compressedFile, destination);
if (OsInfo.IsWindows)
{
ExtractZip(compressedFile, destination);
}
else
{
ExtractTgz(compressedFile, destination);
}
_logger.Debug("Extraction complete.");
}
private void ExtractZip(string compressedFile, string destination)
{
using (var fileStream = File.OpenRead(compressedFile)) using (var fileStream = File.OpenRead(compressedFile))
{ {
var zipFile = new ZipFile(fileStream); var zipFile = new ZipFile(fileStream);
@ -64,8 +82,19 @@ namespace NzbDrone.Common
} }
} }
} }
}
_logger.Trace("Extraction complete."); private void ExtractTgz(string compressedFile, string destination)
{
Stream inStream = File.OpenRead(compressedFile);
Stream gzipStream = new GZipInputStream(inStream);
TarArchive tarArchive = TarArchive.CreateInputTarArchive(gzipStream);
tarArchive.ExtractContents(destination);
tarArchive.Close();
gzipStream.Close();
inStream.Close();
} }
private void OnZipError(TestStatus status, string message) private void OnZipError(TestStatus status, string message)

View File

@ -56,7 +56,7 @@ namespace NzbDrone.Common.Disk
return false; return false;
} }
public DateTime GetLastFolderWrite(string path) public DateTime FolderGetLastWrite(string path)
{ {
Ensure.That(path, () => path).IsValidPath(); Ensure.That(path, () => path).IsValidPath();
@ -76,7 +76,21 @@ namespace NzbDrone.Common.Disk
.Max(c => c.LastWriteTimeUtc); .Max(c => c.LastWriteTimeUtc);
} }
public DateTime GetLastFileWrite(string path) public DateTime FileGetLastWrite(string path)
{
PathEnsureFileExists(path);
return new FileInfo(path).LastWriteTime;
}
public DateTime FileGetLastWriteUtc(string path)
{
PathEnsureFileExists(path);
return new FileInfo(path).LastWriteTimeUtc;
}
private void PathEnsureFileExists(string path)
{ {
Ensure.That(path, () => path).IsValidPath(); Ensure.That(path, () => path).IsValidPath();
@ -84,8 +98,6 @@ namespace NzbDrone.Common.Disk
{ {
throw new FileNotFoundException("File doesn't exist: " + path); throw new FileNotFoundException("File doesn't exist: " + path);
} }
return new FileInfo(path).LastWriteTimeUtc;
} }
public void EnsureFolder(string path) public void EnsureFolder(string path)
@ -189,7 +201,7 @@ namespace NzbDrone.Common.Disk
Ensure.That(source, () => source).IsValidPath(); Ensure.That(source, () => source).IsValidPath();
Ensure.That(target, () => target).IsValidPath(); Ensure.That(target, () => target).IsValidPath();
Logger.Trace("{0} {1} -> {2}", transferAction, source, target); Logger.Debug("{0} {1} -> {2}", transferAction, source, target);
var sourceFolder = new DirectoryInfo(source); var sourceFolder = new DirectoryInfo(source);
var targetFolder = new DirectoryInfo(target); var targetFolder = new DirectoryInfo(target);
@ -208,7 +220,7 @@ namespace NzbDrone.Common.Disk
{ {
var destFile = Path.Combine(target, sourceFile.Name); var destFile = Path.Combine(target, sourceFile.Name);
Logger.Trace("{0} {1} -> {2}", transferAction, sourceFile, destFile); Logger.Debug("{0} {1} -> {2}", transferAction, sourceFile, destFile);
switch (transferAction) switch (transferAction)
{ {
@ -305,6 +317,26 @@ namespace NzbDrone.Common.Disk
Directory.SetLastWriteTimeUtc(path, dateTime); Directory.SetLastWriteTimeUtc(path, dateTime);
} }
public void FileSetLastWriteTime(string path, DateTime dateTime)
{
Ensure.That(path, () => path).IsValidPath();
File.SetLastWriteTime(path, dateTime);
}
public void FileSetLastAccessTime(string path, DateTime dateTime)
{
Ensure.That(path, () => path).IsValidPath();
File.SetLastAccessTimeUtc(path, dateTime);
}
public void FileSetLastAccessTimeUtc(string path, DateTime dateTime)
{
Ensure.That(path, () => path).IsValidPath();
File.SetLastAccessTimeUtc(path, dateTime);
}
public bool IsFileLocked(string file) public bool IsFileLocked(string file)
{ {
try try

View File

@ -12,8 +12,9 @@ namespace NzbDrone.Common.Disk
void SetPermissions(string path, string mask, string user, string group); void SetPermissions(string path, string mask, string user, string group);
long? GetTotalSize(string path); long? GetTotalSize(string path);
DateTime GetLastFolderWrite(string path); DateTime FolderGetLastWrite(string path);
DateTime GetLastFileWrite(string path); DateTime FileGetLastWrite(string path);
DateTime FileGetLastWriteUtc(string path);
void EnsureFolder(string path); void EnsureFolder(string path);
bool FolderExists(string path); bool FolderExists(string path);
bool FileExists(string path); bool FileExists(string path);
@ -33,6 +34,8 @@ namespace NzbDrone.Common.Disk
void WriteAllText(string filename, string contents); void WriteAllText(string filename, string contents);
void FileSetLastWriteTimeUtc(string path, DateTime dateTime); void FileSetLastWriteTimeUtc(string path, DateTime dateTime);
void FolderSetLastWriteTimeUtc(string path, DateTime dateTime); void FolderSetLastWriteTimeUtc(string path, DateTime dateTime);
void FileSetLastWriteTime(string path, DateTime dateTime);
void FileSetLastAccessTime(string path, DateTime dateTime);
bool IsFileLocked(string path); bool IsFileLocked(string path);
string GetPathRoot(string path); string GetPathRoot(string path);
string GetParentFolder(string path); string GetParentFolder(string path);

View File

@ -100,7 +100,7 @@ namespace NzbDrone.Common.EnsureThat
if (param.Value.IsPathValid()) return param; if (param.Value.IsPathValid()) return param;
if (OsInfo.IsLinux) if (OsInfo.IsMono)
{ {
throw ExceptionFactory.CreateForParamValidation(param.Name, string.Format("value [{0}] is not a valid *nix path. paths must start with /", param.Value)); throw ExceptionFactory.CreateForParamValidation(param.Name, string.Format("value [{0}] is not a valid *nix path. paths must start with /", param.Value));
} }

View File

@ -32,7 +32,7 @@ namespace NzbDrone.Common.EnvironmentInfo
{ {
_diskProvider.EnsureFolder(_appFolderInfo.AppDataFolder); _diskProvider.EnsureFolder(_appFolderInfo.AppDataFolder);
if (!OsInfo.IsLinux) if (!OsInfo.IsMono)
{ {
SetPermissions(); SetPermissions();
} }

View File

@ -17,7 +17,7 @@ namespace NzbDrone.Common.EnvironmentInfo
public AppFolderInfo(IStartupContext startupContext) public AppFolderInfo(IStartupContext startupContext)
{ {
if (OsInfo.IsLinux) if (OsInfo.IsMono)
{ {
DATA_SPECIAL_FOLDER = Environment.SpecialFolder.ApplicationData; DATA_SPECIAL_FOLDER = Environment.SpecialFolder.ApplicationData;
} }

View File

@ -1,4 +1,5 @@
using System; using System;
using System.Runtime.InteropServices;
namespace NzbDrone.Common.EnvironmentInfo namespace NzbDrone.Common.EnvironmentInfo
{ {
@ -7,34 +8,80 @@ namespace NzbDrone.Common.EnvironmentInfo
static OsInfo() static OsInfo()
{ {
Version = Environment.OSVersion.Version; var platform = (int)Environment.OSVersion.Platform;
IsMono = Type.GetType("Mono.Runtime") != null;
int platform = (int)Environment.OSVersion.Platform; Version = Environment.OSVersion.Version;
IsLinux = (platform == 4) || (platform == 6) || (platform == 128);
IsMonoRuntime = Type.GetType("Mono.Runtime") != null;
IsMono = (platform == 4) || (platform == 6) || (platform == 128);
IsOsx = IsRunningOnMac();
IsLinux = IsMono && !IsOsx;
IsWindows = !IsMono;
FirstDayOfWeek = DateTime.Today.GetFirstDayOfWeek().DayOfWeek;
if (!IsMono)
{
Os = Os.Windows;
}
else
{
Os = IsOsx ? Os.Osx : Os.Linux;
}
} }
public static Version Version { get; private set; } public static Version Version { get; private set; }
public static bool IsMonoRuntime { get; private set; }
public static bool IsMono { get; private set; } public static bool IsMono { get; private set; }
public static bool IsLinux { get; private set; } public static bool IsLinux { get; private set; }
public static bool IsOsx { get; private set; }
public static bool IsWindows { get; private set; }
public static Os Os { get; private set; }
public static DayOfWeek FirstDayOfWeek { get; private set; }
public static bool IsWindows //Borrowed from: https://github.com/jpobst/Pinta/blob/master/Pinta.Core/Managers/SystemManager.cs
{ //From Managed.Windows.Forms/XplatUI
get [DllImport("libc")]
{ static extern int uname(IntPtr buf);
return !IsLinux;
}
}
public static DayOfWeek FirstDayOfWeek static bool IsRunningOnMac()
{ {
get var buf = IntPtr.Zero;
try
{ {
return DateTime.Today.GetFirstDayOfWeek().DayOfWeek; buf = Marshal.AllocHGlobal(8192);
// This is a hacktastic way of getting sysname from uname ()
if (uname(buf) == 0)
{
var os = Marshal.PtrToStringAnsi(buf);
if (os == "Darwin")
{
return true;
}
}
} }
catch
{
}
finally
{
if (buf != IntPtr.Zero)
{
Marshal.FreeHGlobal(buf);
}
}
return false;
} }
} }
public enum Os
{
Windows,
Linux,
Osx
}
} }

View File

@ -16,6 +16,7 @@ namespace NzbDrone.Common.EnvironmentInfo
bool IsWindowsService { get; } bool IsWindowsService { get; }
bool IsConsole { get; } bool IsConsole { get; }
bool IsRunning { get; set; } bool IsRunning { get; set; }
bool RestartPending { get; set; }
string ExecutingApplication { get; } string ExecutingApplication { get; }
} }
@ -78,11 +79,12 @@ namespace NzbDrone.Common.EnvironmentInfo
return (OsInfo.IsWindows && return (OsInfo.IsWindows &&
IsUserInteractive && IsUserInteractive &&
ProcessName.Equals(ProcessProvider.NZB_DRONE_CONSOLE_PROCESS_NAME, StringComparison.InvariantCultureIgnoreCase)) || ProcessName.Equals(ProcessProvider.NZB_DRONE_CONSOLE_PROCESS_NAME, StringComparison.InvariantCultureIgnoreCase)) ||
OsInfo.IsLinux; OsInfo.IsMono;
} }
} }
public bool IsRunning { get; set; } public bool IsRunning { get; set; }
public bool RestartPending { get; set; }
public string ExecutingApplication { get; private set; } public string ExecutingApplication { get; private set; }
public static bool IsProduction { get; private set; } public static bool IsProduction { get; private set; }

View File

@ -18,6 +18,7 @@ namespace NzbDrone.Common.EnvironmentInfo
internal const string UNINSTALL_SERVICE = "u"; internal const string UNINSTALL_SERVICE = "u";
public const string HELP = "?"; public const string HELP = "?";
public const string TERMINATE = "terminateexisting"; public const string TERMINATE = "terminateexisting";
public const string RESTART = "restart";
public StartupContext(params string[] args) public StartupContext(params string[] args)
{ {

View File

@ -102,14 +102,14 @@ namespace NzbDrone.Common
fileInfo.Directory.Create(); fileInfo.Directory.Create();
} }
_logger.Trace("Downloading [{0}] to [{1}]", url, fileName); _logger.Debug("Downloading [{0}] to [{1}]", url, fileName);
var stopWatch = Stopwatch.StartNew(); var stopWatch = Stopwatch.StartNew();
var webClient = new WebClient(); var webClient = new WebClient();
webClient.Headers.Add(HttpRequestHeader.UserAgent, _userAgent); webClient.Headers.Add(HttpRequestHeader.UserAgent, _userAgent);
webClient.DownloadFile(url, fileName); webClient.DownloadFile(url, fileName);
stopWatch.Stop(); stopWatch.Stop();
_logger.Trace("Downloading Completed. took {0:0}s", stopWatch.Elapsed.Seconds); _logger.Debug("Downloading Completed. took {0:0}s", stopWatch.Elapsed.Seconds);
} }
catch (WebException e) catch (WebException e)
{ {
@ -127,7 +127,7 @@ namespace NzbDrone.Common
{ {
address = String.Format("http://{0}/jsonrpc", address); address = String.Format("http://{0}/jsonrpc", address);
_logger.Trace("Posting command: {0}, to {1}", command, address); _logger.Debug("Posting command: {0}, to {1}", command, address);
byte[] byteArray = Encoding.ASCII.GetBytes(command); byte[] byteArray = Encoding.ASCII.GetBytes(command);

View File

@ -48,7 +48,7 @@ namespace NzbDrone.Common.Instrumentation
{ {
if (logEvent == null || logEvent.Exception == null) return; if (logEvent == null || logEvent.Exception == null) return;
InternalLogger.Trace("Sending Exception to api.exceptron.com. Process Name: {0}", Process.GetCurrentProcess().ProcessName); InternalLogger.Debug("Sending Exception to api.exceptron.com. Process Name: {0}", Process.GetCurrentProcess().ProcessName);
try try
{ {

View File

@ -31,7 +31,7 @@ namespace NzbDrone.Common.Instrumentation
} }
else else
{ {
if (inConsole && (OsInfo.IsLinux || new RuntimeInfo(null, new ServiceProvider(new ProcessProvider())).IsUserInteractive)) if (inConsole && (OsInfo.IsMono || new RuntimeInfo(null, new ServiceProvider(new ProcessProvider())).IsUserInteractive))
{ {
RegisterConsole(); RegisterConsole();
} }

View File

@ -20,7 +20,7 @@ namespace NzbDrone.Common
public int GetHashCode(string obj) public int GetHashCode(string obj)
{ {
if (OsInfo.IsLinux) if (OsInfo.IsMono)
{ {
return obj.CleanFilePath().GetHashCode(); return obj.CleanFilePath().GetHashCode();
} }

View File

@ -29,7 +29,7 @@ namespace NzbDrone.Common
var info = new FileInfo(path.Trim()); var info = new FileInfo(path.Trim());
if (!OsInfo.IsLinux && info.FullName.StartsWith(@"\\")) //UNC if (!OsInfo.IsMono && info.FullName.StartsWith(@"\\")) //UNC
{ {
return info.FullName.TrimEnd('/', '\\', ' '); return info.FullName.TrimEnd('/', '\\', ' ');
} }
@ -39,7 +39,7 @@ namespace NzbDrone.Common
public static bool PathEquals(this string firstPath, string secondPath) public static bool PathEquals(this string firstPath, string secondPath)
{ {
if (OsInfo.IsLinux) if (OsInfo.IsMono)
{ {
if (firstPath.Equals(secondPath)) return true; if (firstPath.Equals(secondPath)) return true;
return String.Equals(firstPath.CleanFilePath(), secondPath.CleanFilePath()); return String.Equals(firstPath.CleanFilePath(), secondPath.CleanFilePath());
@ -58,7 +58,7 @@ namespace NzbDrone.Common
return false; return false;
} }
if (OsInfo.IsLinux) if (OsInfo.IsMono)
{ {
return path.StartsWith(Path.DirectorySeparatorChar.ToString()); return path.StartsWith(Path.DirectorySeparatorChar.ToString());
} }
@ -97,7 +97,7 @@ namespace NzbDrone.Common
public static string GetActualCasing(this string path) public static string GetActualCasing(this string path)
{ {
if (OsInfo.IsLinux || path.StartsWith("\\")) if (OsInfo.IsMono || path.StartsWith("\\"))
{ {
return path; return path;
} }

View File

@ -60,7 +60,7 @@ namespace NzbDrone.Common.Processes
public ProcessInfo GetProcessById(int id) public ProcessInfo GetProcessById(int id)
{ {
Logger.Trace("Finding process with Id:{0}", id); Logger.Debug("Finding process with Id:{0}", id);
var processInfo = ConvertToProcessInfo(Process.GetProcesses().FirstOrDefault(p => p.Id == id)); var processInfo = ConvertToProcessInfo(Process.GetProcesses().FirstOrDefault(p => p.Id == id));
@ -70,7 +70,7 @@ namespace NzbDrone.Common.Processes
} }
else else
{ {
Logger.Trace("Found process {0}", processInfo.ToString()); Logger.Debug("Found process {0}", processInfo.ToString());
} }
return processInfo; return processInfo;
@ -186,7 +186,7 @@ namespace NzbDrone.Common.Processes
public void WaitForExit(Process process) public void WaitForExit(Process process)
{ {
Logger.Trace("Waiting for process {0} to exit.", process.ProcessName); Logger.Debug("Waiting for process {0} to exit.", process.ProcessName);
process.WaitForExit(); process.WaitForExit();
} }
@ -268,7 +268,7 @@ namespace NzbDrone.Common.Processes
if (process.HasExited) if (process.HasExited)
{ {
Logger.Trace("Process has already exited"); Logger.Debug("Process has already exited");
return; return;
} }

View File

@ -253,5 +253,22 @@ namespace NzbDrone.Core.Test.Download
VerifyNoFailedDownloads(); VerifyNoFailedDownloads();
} }
[Test]
public void should_not_process_if_failed_due_to_lack_of_disk_space()
{
var history = Builder<History.History>.CreateListOfSize(1)
.Build()
.ToList();
GivenGrabbedHistory(history);
GivenFailedDownloadClientHistory();
_failed.First().Message = "Unpacking failed, write error or disk is full?";
Subject.Execute(new CheckForFailedDownloadCommand());
VerifyNoFailedDownloads();
}
} }
} }

Binary file not shown.

View File

@ -0,0 +1,82 @@
using System;
using System.Collections.Generic;
using FluentAssertions;
using NUnit.Framework;
using NzbDrone.Common.Processes;
using NzbDrone.Core.HealthCheck.Checks;
using NzbDrone.Core.Test.Framework;
namespace NzbDrone.Core.Test.HealthCheck.Checks
{
[TestFixture]
public class MonoVersionCheckFixture : CoreTest<MonoVersionCheck>
{
[SetUp]
public void Setup()
{
MonoOnly();
}
private void GivenOutput(string version)
{
Mocker.GetMock<IProcessProvider>()
.Setup(s => s.StartAndCapture("mono", "--version"))
.Returns(new ProcessOutput
{
Standard = new List<string>
{
String.Format("Mono JIT compiler version {0} (Debian {0}-8)", version),
"Copyright (C) 2002-2011 Novell, Inc, Xamarin, Inc and Contributors. www.mono-project.com"
}
});
}
[Test]
public void should_return_warning_when_mono_3_0()
{
GivenOutput("3.0.0.1");
Subject.Check().ShouldBeWarning();
}
[Test]
public void should_return_warning_when_mono_2_10_8()
{
GivenOutput("2.10.8.1");
Subject.Check().ShouldBeWarning();
}
[Test]
public void should_return_null_when_mono_3_2()
{
GivenOutput("3.2.0.1");
Subject.Check().Should().BeNull();
}
[Test]
public void should_return_null_when_mono_4_0()
{
GivenOutput("4.0.0.0");
Subject.Check().Should().BeNull();
}
[Test]
public void should_return_null_when_mono_3_2_7()
{
GivenOutput("3.2.7");
Subject.Check().Should().BeNull();
}
[Test]
public void should_return_null_when_mono_3_2_1()
{
GivenOutput("3.2.1");
Subject.Check().Should().BeNull();
}
}
}

View File

@ -4,7 +4,6 @@ using FluentAssertions;
using NLog; using NLog;
using NUnit.Framework; using NUnit.Framework;
using NzbDrone.Common.Instrumentation; using NzbDrone.Common.Instrumentation;
using NzbDrone.Core.Datastore;
using NzbDrone.Core.Datastore.Migration.Framework; using NzbDrone.Core.Datastore.Migration.Framework;
using NzbDrone.Core.MediaFiles; using NzbDrone.Core.MediaFiles;
using NzbDrone.Core.Instrumentation; using NzbDrone.Core.Instrumentation;
@ -103,7 +102,7 @@ namespace NzbDrone.Core.Test.InstrumentationTests
public void null_string_as_arg_should_not_fail() public void null_string_as_arg_should_not_fail()
{ {
var epFile = new EpisodeFile(); var epFile = new EpisodeFile();
_logger.Trace("File {0} no longer exists on disk. removing from database.", epFile.Path); _logger.Debug("File {0} no longer exists on disk. removing from database.", epFile.Path);
epFile.Path.Should().BeNull(); epFile.Path.Should().BeNull();
} }

View File

@ -29,7 +29,7 @@ namespace NzbDrone.Core.Test.MediaCoverTests
new MediaCover.MediaCover {CoverType = MediaCoverTypes.Banner} new MediaCover.MediaCover {CoverType = MediaCoverTypes.Banner}
}; };
Mocker.GetMock<IDiskProvider>().Setup(c => c.GetLastFileWrite(It.IsAny<string>())) Mocker.GetMock<IDiskProvider>().Setup(c => c.FileGetLastWriteUtc(It.IsAny<string>()))
.Returns(new DateTime(1234)); .Returns(new DateTime(1234));
Mocker.GetMock<IDiskProvider>().Setup(c => c.FileExists(It.IsAny<string>())) Mocker.GetMock<IDiskProvider>().Setup(c => c.FileExists(It.IsAny<string>()))

View File

@ -42,7 +42,7 @@ namespace NzbDrone.Core.Test.MediaFiles.EpisodeImport.Specifications
private void GivenLastWriteTimeUtc(DateTime time) private void GivenLastWriteTimeUtc(DateTime time)
{ {
Mocker.GetMock<IDiskProvider>() Mocker.GetMock<IDiskProvider>()
.Setup(s => s.GetLastFileWrite(It.IsAny<string>())) .Setup(s => s.FileGetLastWriteUtc(It.IsAny<string>()))
.Returns(time); .Returns(time);
} }
@ -75,7 +75,7 @@ namespace NzbDrone.Core.Test.MediaFiles.EpisodeImport.Specifications
[Test] [Test]
public void should_return_false_if_unopacking_on_linux() public void should_return_false_if_unopacking_on_linux()
{ {
LinuxOnly(); MonoOnly();
GivenInWorkingFolder(); GivenInWorkingFolder();
GivenLastWriteTimeUtc(DateTime.UtcNow.AddDays(-5)); GivenLastWriteTimeUtc(DateTime.UtcNow.AddDays(-5));

View File

@ -108,7 +108,7 @@ namespace NzbDrone.Core.Test.MediaFiles
[Test] [Test]
public void filter_should_return_none_existing_files_not_ignoring_case() public void filter_should_return_none_existing_files_not_ignoring_case()
{ {
LinuxOnly(); MonoOnly();
var files = new List<string>() var files = new List<string>()
{ {

View File

@ -125,10 +125,11 @@
<Compile Include="Framework\CoreTest.cs" /> <Compile Include="Framework\CoreTest.cs" />
<Compile Include="Framework\DbTest.cs" /> <Compile Include="Framework\DbTest.cs" />
<Compile Include="Framework\NBuilderExtensions.cs" /> <Compile Include="Framework\NBuilderExtensions.cs" />
<Compile Include="HealthCheck\Checks\DownloadClientCheckFixture.cs" />
<Compile Include="HealthCheck\Checks\UpdateCheckFixture.cs" /> <Compile Include="HealthCheck\Checks\UpdateCheckFixture.cs" />
<Compile Include="HealthCheck\Checks\IndexerCheckFixture.cs" /> <Compile Include="HealthCheck\Checks\IndexerCheckFixture.cs" />
<Compile Include="HealthCheck\Checks\DroneFactoryCheckFixture.cs" /> <Compile Include="HealthCheck\Checks\DroneFactoryCheckFixture.cs" />
<Compile Include="HealthCheck\Checks\DownloadClientCheckFixture.cs" /> <Compile Include="HealthCheck\Checks\MonoVersionCheckFixture.cs" />
<Compile Include="HealthCheck\Checks\HealthCheckFixtureExtentions.cs" /> <Compile Include="HealthCheck\Checks\HealthCheckFixtureExtentions.cs" />
<Compile Include="HistoryTests\HistoryServiceFixture.cs" /> <Compile Include="HistoryTests\HistoryServiceFixture.cs" />
<Compile Include="Housekeeping\Housekeepers\CleanupOrphanedHistoryItemsFixture.cs" /> <Compile Include="Housekeeping\Housekeepers\CleanupOrphanedHistoryItemsFixture.cs" />
@ -362,6 +363,9 @@
<None Include="Files\SceneMappings.json"> <None Include="Files\SceneMappings.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory> <CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None> </None>
<None Include="Files\TestArchive.tar.gz">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Include="Files\TestArchive.zip"> <None Include="Files\TestArchive.zip">
<CopyToOutputDirectory>Always</CopyToOutputDirectory> <CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None> </None>

View File

@ -15,8 +15,6 @@ namespace NzbDrone.Core.Test.ParserTests
public class NormalizeTitleFixture : CoreTest public class NormalizeTitleFixture : CoreTest
{ {
[TestCase("Conan", "conan")] [TestCase("Conan", "conan")]
[TestCase("The Tonight Show With Jay Leno", "tonightshowwithjayleno")]
[TestCase("The.Daily.Show", "dailyshow")]
[TestCase("Castle (2009)", "castle2009")] [TestCase("Castle (2009)", "castle2009")]
[TestCase("Parenthood.2010", "parenthood2010")] [TestCase("Parenthood.2010", "parenthood2010")]
[TestCase("Law_and_Order_SVU", "lawordersvu")] [TestCase("Law_and_Order_SVU", "lawordersvu")]
@ -51,9 +49,6 @@ namespace NzbDrone.Core.Test.ParserTests
"word.{0}.word", "word.{0}.word",
"word {0} word", "word {0} word",
"word-{0}-word", "word-{0}-word",
"{0}.word.word",
"{0}-word-word",
"{0} word word",
"word.word.{0}", "word.word.{0}",
"word-word-{0}", "word-word-{0}",
"word-word {0}", "word-word {0}",
@ -64,7 +59,6 @@ namespace NzbDrone.Core.Test.ParserTests
var dirty = String.Format(s, word); var dirty = String.Format(s, word);
dirty.CleanSeriesTitle().Should().Be("wordword"); dirty.CleanSeriesTitle().Should().Be("wordword");
} }
} }
[TestCase("the")] [TestCase("the")]
@ -92,5 +86,36 @@ namespace NzbDrone.Core.Test.ParserTests
} }
} }
[TestCase("The Office", "theoffice")]
[TestCase("The Tonight Show With Jay Leno", "thetonightshowwithjayleno")]
[TestCase("The.Daily.Show", "thedailyshow")]
public void should_not_remove_from_the_beginning_of_the_title(string parsedSeriesName, string seriesName)
{
var result = parsedSeriesName.CleanSeriesTitle();
result.Should().Be(seriesName);
}
[TestCase("the")]
[TestCase("and")]
[TestCase("or")]
[TestCase("a")]
[TestCase("an")]
[TestCase("of")]
public void should_not_clean_word_from_beginning_of_string(string word)
{
var dirtyFormat = new[]
{
"{0}.word.word",
"{0}-word-word",
"{0} word word"
};
foreach (var s in dirtyFormat)
{
var dirty = String.Format(s, word);
dirty.CleanSeriesTitle().Should().Be(word + "wordword");
}
}
} }
} }

View File

@ -23,46 +23,13 @@ namespace NzbDrone.Core.Test.ParserTests
* Superman.-.The.Man.of.Steel.1994-05.33.hybrid.DreamGirl-Novus-HD * Superman.-.The.Man.of.Steel.1994-05.33.hybrid.DreamGirl-Novus-HD
*/ */
[TestCase("[SubDESU]_High_School_DxD_07_(1280x720_x264-AAC)_[6B7FD717]", "High School DxD", 7, 0, 0)]
[TestCase("[Chihiro]_Working!!_-_06_[848x480_H.264_AAC][859EEAFA]", "Working!!", 6, 0, 0)]
[TestCase("[Commie]_Senki_Zesshou_Symphogear_-_11_[65F220B4]", "Senki_Zesshou_Symphogear", 11, 0, 0)]
[TestCase("[Underwater]_Rinne_no_Lagrange_-_12_(720p)_[5C7BC4F9]", "Rinne_no_Lagrange", 12, 0, 0)]
[TestCase("[Commie]_Rinne_no_Lagrange_-_15_[E76552EA]", "Rinne_no_Lagrange", 15, 0, 0)]
[TestCase("[HorribleSubs]_Hunter_X_Hunter_-_33_[720p]", "Hunter_X_Hunter", 33, 0, 0)]
[TestCase("[HorribleSubs]_Fairy_Tail_-_145_[720p]", "Fairy_Tail", 145, 0, 0)]
[TestCase("[HorribleSubs] Tonari no Kaibutsu-kun - 13 [1080p].mkv", "Tonari no Kaibutsu-kun", 13, 0, 0)]
[TestCase("[Doremi].Yes.Pretty.Cure.5.Go.Go!.31.[1280x720].[C65D4B1F].mkv", "Yes.Pretty.Cure.5.Go.Go!", 31, 0, 0)]
[TestCase("[K-F] One Piece 214", "One Piece", 214, 0, 0)]
[TestCase("[K-F] One Piece S10E14 214", "One Piece", 214, 10, 14)]
[TestCase("[K-F] One Piece 10x14 214", "One Piece", 214, 10, 14)]
[TestCase("[K-F] One Piece 214 10x14", "One Piece", 214, 10, 14)]
// [TestCase("One Piece S10E14 214", "One Piece", 214, 10, 14)]
// [TestCase("One Piece 10x14 214", "One Piece", 214, 10, 14)]
// [TestCase("One Piece 214 10x14", "One Piece", 214, 10, 14)]
// [TestCase("214 One Piece 10x14", "One Piece", 214, 10, 14)]
[TestCase("Bleach - 031 - The Resolution to Kill [Lunar].avi", "Bleach", 31, 0, 0)]
[TestCase("Bleach - 031 - The Resolution to Kill [Lunar]", "Bleach", 31, 0, 0)]
[TestCase("[ACX]Hack Sign 01 Role Play [Kosaka] [9C57891E].mkv", "Hack Sign", 1, 0, 0)]
[TestCase("[SFW-sage] Bakuman S3 - 12 [720p][D07C91FC]", "Bakuman S3", 12, 0, 0)]
[TestCase("ducktales_e66_time_is_money_part_one_marking_time", "DuckTales", 66, 0, 0)]
public void parse_absolute_numbers(string postTitle, string title, int absoluteEpisodeNumber, int seasonNumber, int episodeNumber)
{
var result = Parser.Parser.ParseTitle(postTitle);
result.Should().NotBeNull();
result.AbsoluteEpisodeNumbers.First().Should().Be(absoluteEpisodeNumber);
result.SeasonNumber.Should().Be(seasonNumber);
result.EpisodeNumbers.FirstOrDefault().Should().Be(episodeNumber);
result.SeriesTitle.Should().Be(title.CleanSeriesTitle());
result.FullSeason.Should().BeFalse();
}
[TestCase("Chuck - 4x05 - Title", "Chuck")] [TestCase("Chuck - 4x05 - Title", "Chuck")]
[TestCase("Law & Order - 4x05 - Title", "laworder")] [TestCase("Law & Order - 4x05 - Title", "laworder")]
[TestCase("Bad Format", "badformat")] [TestCase("Bad Format", "badformat")]
[TestCase("Mad Men - Season 1 [Bluray720p]", "madmen")] [TestCase("Mad Men - Season 1 [Bluray720p]", "madmen")]
[TestCase("Mad Men - Season 1 [Bluray1080p]", "madmen")] [TestCase("Mad Men - Season 1 [Bluray1080p]", "madmen")]
[TestCase("The Daily Show With Jon Stewart -", "dailyshowwithjonstewart")] [TestCase("The Daily Show With Jon Stewart -", "thedailyshowwithjonstewart")]
[TestCase("The Venture Bros. (2004)", "venturebros2004")] [TestCase("The Venture Bros. (2004)", "theventurebros2004")]
[TestCase("Castle (2011)", "castle2011")] [TestCase("Castle (2011)", "castle2011")]
[TestCase("Adventure Time S02 720p HDTV x264 CRON", "adventuretime")] [TestCase("Adventure Time S02 720p HDTV x264 CRON", "adventuretime")]
[TestCase("Hawaii Five 0", "hawaiifive0")] [TestCase("Hawaii Five 0", "hawaiifive0")]

View File

@ -2,6 +2,7 @@
using NUnit.Framework; using NUnit.Framework;
using NzbDrone.Common; using NzbDrone.Common;
using System.IO; using System.IO;
using NzbDrone.Common.EnvironmentInfo;
using NzbDrone.Test.Common; using NzbDrone.Test.Common;
namespace NzbDrone.Core.Test.ProviderTests.DiskProviderTests namespace NzbDrone.Core.Test.ProviderTests.DiskProviderTests
@ -13,7 +14,9 @@ namespace NzbDrone.Core.Test.ProviderTests.DiskProviderTests
public void Should_extract_to_correct_folder() public void Should_extract_to_correct_folder()
{ {
var destination = Path.Combine(TempFolder, "destination"); var destination = Path.Combine(TempFolder, "destination");
Subject.Extract(GetTestFilePath("TestArchive.zip"), destination); var testArchive = OsInfo.IsWindows ? "TestArchive.zip" : "TestArchive.tar.gz";
Subject.Extract(GetTestFilePath(testArchive), destination);
var destinationFolder = new DirectoryInfo(destination); var destinationFolder = new DirectoryInfo(destination);

View File

@ -18,19 +18,19 @@ namespace NzbDrone.Core.Test.ProviderTests.RecycleBinProviderTests
private void WithExpired() private void WithExpired()
{ {
Mocker.GetMock<IDiskProvider>().Setup(s => s.GetLastFolderWrite(It.IsAny<String>())) Mocker.GetMock<IDiskProvider>().Setup(s => s.FolderGetLastWrite(It.IsAny<String>()))
.Returns(DateTime.UtcNow.AddDays(-10)); .Returns(DateTime.UtcNow.AddDays(-10));
Mocker.GetMock<IDiskProvider>().Setup(s => s.GetLastFileWrite(It.IsAny<String>())) Mocker.GetMock<IDiskProvider>().Setup(s => s.FileGetLastWriteUtc(It.IsAny<String>()))
.Returns(DateTime.UtcNow.AddDays(-10)); .Returns(DateTime.UtcNow.AddDays(-10));
} }
private void WithNonExpired() private void WithNonExpired()
{ {
Mocker.GetMock<IDiskProvider>().Setup(s => s.GetLastFolderWrite(It.IsAny<String>())) Mocker.GetMock<IDiskProvider>().Setup(s => s.FolderGetLastWrite(It.IsAny<String>()))
.Returns(DateTime.UtcNow.AddDays(-3)); .Returns(DateTime.UtcNow.AddDays(-3));
Mocker.GetMock<IDiskProvider>().Setup(s => s.GetLastFileWrite(It.IsAny<String>())) Mocker.GetMock<IDiskProvider>().Setup(s => s.FileGetLastWriteUtc(It.IsAny<String>()))
.Returns(DateTime.UtcNow.AddDays(-3)); .Returns(DateTime.UtcNow.AddDays(-3));
} }

View File

@ -21,17 +21,30 @@ namespace NzbDrone.Core.Test.UpdateTests
{ {
private string _sandboxFolder; private string _sandboxFolder;
private readonly UpdatePackage _updatePackage = new UpdatePackage private UpdatePackage _updatePackage;
{
FileName = "NzbDrone.develop.2.0.0.zip",
Url = "http://update.nzbdrone.com/v2/develop/NzbDrone.develop.zip",
Version = new Version("2.0.0")
};
[SetUp] [SetUp]
public void Setup() public void Setup()
{ {
WindowsOnly(); if (OsInfo.IsLinux)
{
_updatePackage = new UpdatePackage
{
FileName = "NzbDrone.develop.2.0.0.0.tar.gz",
Url = "http://update.nzbdrone.com/v2/develop/mono/NzbDrone.develop.tar.gz",
Version = new Version("2.0.0.0")
};
}
else
{
_updatePackage = new UpdatePackage
{
FileName = "NzbDrone.develop.2.0.0.0.zip",
Url = "http://update.nzbdrone.com/v2/develop/windows/NzbDrone.develop.zip",
Version = new Version("2.0.0.0")
};
}
Mocker.GetMock<IAppFolderInfo>().SetupGet(c => c.TempFolder).Returns(TempFolder); Mocker.GetMock<IAppFolderInfo>().SetupGet(c => c.TempFolder).Returns(TempFolder);
Mocker.GetMock<ICheckUpdateService>().Setup(c => c.AvailableUpdate()).Returns(_updatePackage); Mocker.GetMock<ICheckUpdateService>().Setup(c => c.AvailableUpdate()).Returns(_updatePackage);
@ -42,7 +55,6 @@ namespace NzbDrone.Core.Test.UpdateTests
} }
[Test] [Test]
public void should_delete_sandbox_before_update_if_folder_exists() public void should_delete_sandbox_before_update_if_folder_exists()
{ {
@ -136,7 +148,7 @@ namespace NzbDrone.Core.Test.UpdateTests
updateSubFolder.Refresh(); updateSubFolder.Refresh();
updateSubFolder.Exists.Should().BeTrue(); updateSubFolder.Exists.Should().BeTrue();
updateSubFolder.GetDirectories("nzbdrone").Should().HaveCount(1); updateSubFolder.GetDirectories("NzbDrone").Should().HaveCount(1);
updateSubFolder.GetDirectories().Should().HaveCount(1); updateSubFolder.GetDirectories().Should().HaveCount(1);
updateSubFolder.GetFiles().Should().NotBeEmpty(); updateSubFolder.GetFiles().Should().NotBeEmpty();
} }

View File

@ -9,12 +9,14 @@ using NzbDrone.Common.Cache;
using NzbDrone.Common.EnvironmentInfo; using NzbDrone.Common.EnvironmentInfo;
using NzbDrone.Core.Configuration.Events; using NzbDrone.Core.Configuration.Events;
using NzbDrone.Core.Lifecycle; using NzbDrone.Core.Lifecycle;
using NzbDrone.Core.Messaging.Commands;
using NzbDrone.Core.Messaging.Events; using NzbDrone.Core.Messaging.Events;
namespace NzbDrone.Core.Configuration namespace NzbDrone.Core.Configuration
{ {
public interface IConfigFileProvider : IHandleAsync<ApplicationStartedEvent> public interface IConfigFileProvider : IHandleAsync<ApplicationStartedEvent>,
IExecute<ResetApiKeyCommand>
{ {
Dictionary<string, object> GetConfigDictionary(); Dictionary<string, object> GetConfigDictionary();
void SaveConfigDictionary(Dictionary<string, object> configValues); void SaveConfigDictionary(Dictionary<string, object> configValues);
@ -28,6 +30,7 @@ namespace NzbDrone.Core.Configuration
string Password { get; } string Password { get; }
string LogLevel { get; } string LogLevel { get; }
string Branch { get; } string Branch { get; }
bool AutoUpdate { get; }
string ApiKey { get; } string ApiKey { get; }
bool Torrent { get; } bool Torrent { get; }
string SslCertHash { get; } string SslCertHash { get; }
@ -75,6 +78,11 @@ namespace NzbDrone.Core.Configuration
foreach (var configValue in configValues) foreach (var configValue in configValues)
{ {
if (configValue.Key.Equals("ApiKey", StringComparison.InvariantCultureIgnoreCase))
{
continue;
}
object currentValue; object currentValue;
allWithDefaults.TryGetValue(configValue.Key, out currentValue); allWithDefaults.TryGetValue(configValue.Key, out currentValue);
if (currentValue == null) continue; if (currentValue == null) continue;
@ -114,7 +122,7 @@ namespace NzbDrone.Core.Configuration
{ {
get get
{ {
return GetValue("ApiKey", Guid.NewGuid().ToString().Replace("-", "")); return GetValue("ApiKey", GenerateApiKey());
} }
} }
@ -133,6 +141,11 @@ namespace NzbDrone.Core.Configuration
get { return GetValue("Branch", "master").ToLowerInvariant(); } get { return GetValue("Branch", "master").ToLowerInvariant(); }
} }
public bool AutoUpdate
{
get { return GetValueBoolean("AutoUpdate", false, persist: false); }
}
public string Username public string Username
{ {
get { return GetValue("Username", ""); } get { return GetValue("Username", ""); }
@ -290,9 +303,19 @@ namespace NzbDrone.Core.Configuration
} }
} }
private string GenerateApiKey()
{
return Guid.NewGuid().ToString().Replace("-", "");
}
public void HandleAsync(ApplicationStartedEvent message) public void HandleAsync(ApplicationStartedEvent message)
{ {
DeleteOldValues(); DeleteOldValues();
} }
public void Execute(ResetApiKeyCommand message)
{
SetValue("ApiKey", GenerateApiKey());
}
} }
} }

View File

@ -4,9 +4,7 @@ using System.Linq;
using NLog; using NLog;
using NzbDrone.Common.EnsureThat; using NzbDrone.Common.EnsureThat;
using NzbDrone.Core.Configuration.Events; using NzbDrone.Core.Configuration.Events;
using NzbDrone.Core.Download; using NzbDrone.Core.MediaFiles;
using NzbDrone.Core.Download.Clients.Nzbget;
using NzbDrone.Core.Download.Clients.Sabnzbd;
using NzbDrone.Core.Messaging.Events; using NzbDrone.Core.Messaging.Events;
@ -141,18 +139,31 @@ namespace NzbDrone.Core.Configuration
public Boolean CreateEmptySeriesFolders public Boolean CreateEmptySeriesFolders
{ {
//TODO: only create if the parent folder exists (check first)
get { return GetValueBoolean("CreateEmptySeriesFolders", false); } get { return GetValueBoolean("CreateEmptySeriesFolders", false); }
set { SetValue("CreateEmptySeriesFolders", value); } set { SetValue("CreateEmptySeriesFolders", value); }
} }
public FileDateType FileDate
{
get { return GetValueEnum("FileDate", FileDateType.None); }
set { SetValue("FileDate", value); }
}
public String DownloadClientWorkingFolders public String DownloadClientWorkingFolders
{ {
get { return GetValue("DownloadClientWorkingFolders", "_UNPACK_|_FAILED_"); } get { return GetValue("DownloadClientWorkingFolders", "_UNPACK_|_FAILED_"); }
set { SetValue("DownloadClientWorkingFolders", value); } set { SetValue("DownloadClientWorkingFolders", value); }
} }
public Int32 DownloadedEpisodesScanInterval
{
get { return GetValueInt("DownloadedEpisodesScanInterval", 1); }
set { SetValue("DownloadedEpisodesScanInterval", value); }
}
public Boolean SetPermissionsLinux public Boolean SetPermissionsLinux
{ {
get { return GetValueBoolean("SetPermissionsLinux", false); } get { return GetValueBoolean("SetPermissionsLinux", false); }
@ -243,7 +254,7 @@ namespace NzbDrone.Core.Configuration
{ {
key = key.ToLowerInvariant(); key = key.ToLowerInvariant();
_logger.Trace("Writing Setting to file. Key:'{0}' Value:'{1}'", key, value); _logger.Trace("Writing Setting to database. Key:'{0}' Value:'{1}'", key, value);
var dbValue = _repository.Get(key); var dbValue = _repository.Get(key);

View File

@ -1,5 +1,6 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using NzbDrone.Core.MediaFiles;
namespace NzbDrone.Core.Configuration namespace NzbDrone.Core.Configuration
{ {
@ -12,6 +13,7 @@ namespace NzbDrone.Core.Configuration
//Download Client //Download Client
String DownloadedEpisodesFolder { get; set; } String DownloadedEpisodesFolder { get; set; }
String DownloadClientWorkingFolders { get; set; } String DownloadClientWorkingFolders { get; set; }
Int32 DownloadedEpisodesScanInterval { get; set; }
//Failed Download Handling (Download client) //Failed Download Handling (Download client)
Boolean AutoRedownloadFailed { get; set; } Boolean AutoRedownloadFailed { get; set; }
@ -23,6 +25,7 @@ namespace NzbDrone.Core.Configuration
String RecycleBin { get; set; } String RecycleBin { get; set; }
Boolean AutoDownloadPropers { get; set; } Boolean AutoDownloadPropers { get; set; }
Boolean CreateEmptySeriesFolders { get; set; } Boolean CreateEmptySeriesFolders { get; set; }
FileDateType FileDate { get; set; }
//Permissions (Media Management) //Permissions (Media Management)
Boolean SetPermissionsLinux { get; set; } Boolean SetPermissionsLinux { get; set; }

View File

@ -0,0 +1,15 @@
using NzbDrone.Core.Messaging.Commands;
namespace NzbDrone.Core.Configuration
{
public class ResetApiKeyCommand : Command
{
public override bool SendUpdatesToClient
{
get
{
return true;
}
}
}
}

View File

@ -38,7 +38,7 @@ namespace NzbDrone.Core.DataAugmentation.Xem
public List<int> GetXemSeriesIds() public List<int> GetXemSeriesIds()
{ {
_logger.Trace("Fetching Series IDs from"); _logger.Debug("Fetching Series IDs from");
var restClient = new RestClient(XEM_BASE_URL); var restClient = new RestClient(XEM_BASE_URL);
@ -52,9 +52,7 @@ namespace NzbDrone.Core.DataAugmentation.Xem
public List<XemSceneTvdbMapping> GetSceneTvdbMappings(int id) public List<XemSceneTvdbMapping> GetSceneTvdbMappings(int id)
{ {
_logger.Trace("Fetching Mappings for: {0}", id); _logger.Debug("Fetching Mappings for: {0}", id);
var url = String.Format("{0}all?id={1}&origin=tvdb", XEM_BASE_URL, id);
var restClient = new RestClient(XEM_BASE_URL); var restClient = new RestClient(XEM_BASE_URL);

View File

@ -30,7 +30,7 @@ namespace NzbDrone.Core.DataAugmentation.Xem
private void PerformUpdate(Series series) private void PerformUpdate(Series series)
{ {
_logger.Trace("Updating scene numbering mapping for: {0}", series); _logger.Debug("Updating scene numbering mapping for: {0}", series);
try try
{ {
@ -38,7 +38,7 @@ namespace NzbDrone.Core.DataAugmentation.Xem
if (!mappings.Any()) if (!mappings.Any())
{ {
_logger.Trace("Mappings for: {0} are empty, skipping", series); _logger.Debug("Mappings for: {0} are empty, skipping", series);
_cache.Remove(series.TvdbId.ToString()); _cache.Remove(series.TvdbId.ToString());
return; return;
} }
@ -54,13 +54,13 @@ namespace NzbDrone.Core.DataAugmentation.Xem
foreach (var mapping in mappings) foreach (var mapping in mappings)
{ {
_logger.Trace("Setting scene numbering mappings for {0} S{1:00}E{2:00}", series, mapping.Tvdb.Season, mapping.Tvdb.Episode); _logger.Debug("Setting scene numbering mappings for {0} S{1:00}E{2:00}", series, mapping.Tvdb.Season, mapping.Tvdb.Episode);
var episode = episodes.SingleOrDefault(e => e.SeasonNumber == mapping.Tvdb.Season && e.EpisodeNumber == mapping.Tvdb.Episode); var episode = episodes.SingleOrDefault(e => e.SeasonNumber == mapping.Tvdb.Season && e.EpisodeNumber == mapping.Tvdb.Episode);
if (episode == null) if (episode == null)
{ {
_logger.Trace("Information hasn't been added to TheTVDB yet, skipping."); _logger.Debug("Information hasn't been added to TheTVDB yet, skipping.");
continue; continue;
} }
@ -105,7 +105,7 @@ namespace NzbDrone.Core.DataAugmentation.Xem
if (!_cache.Find(message.Series.TvdbId.ToString())) if (!_cache.Find(message.Series.TvdbId.ToString()))
{ {
_logger.Trace("Scene numbering is not available for {0} [{1}]", message.Series.Title, message.Series.TvdbId); _logger.Debug("Scene numbering is not available for {0} [{1}]", message.Series.Title, message.Series.TvdbId);
return; return;
} }

View File

@ -0,0 +1,16 @@
using FluentMigrator;
using NzbDrone.Core.Datastore.Migration.Framework;
namespace NzbDrone.Core.Datastore.Migration
{
[Migration(46)]
public class fix_nzb_su_url : NzbDroneMigrationBase
{
protected override void MainDbUpgrade()
{
Execute.Sql("UPDATE Indexers SET Settings = replace(Settings, '//nzb.su', '//api.nzb.su')" +
"WHERE Implementation = 'Newznab'" +
"AND Settings LIKE '%//nzb.su%'");
}
}
}

View File

@ -32,7 +32,7 @@ namespace NzbDrone.Core.Datastore.Migration.Framework
public void Sql(string sql) public void Sql(string sql)
{ {
_logger.Trace(sql); _logger.Debug(sql);
} }
public void ElapsedTime(TimeSpan timeSpan) public void ElapsedTime(TimeSpan timeSpan)

View File

@ -4,7 +4,7 @@ using System.Linq;
using NLog; using NLog;
using NzbDrone.Core.DecisionEngine.Specifications; using NzbDrone.Core.DecisionEngine.Specifications;
using NzbDrone.Core.IndexerSearch.Definitions; using NzbDrone.Core.IndexerSearch.Definitions;
using NzbDrone.Core.Instrumentation; using NzbDrone.Core.Instrumentation.Extensions;
using NzbDrone.Core.Parser; using NzbDrone.Core.Parser;
using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Parser.Model;
using NzbDrone.Common.Serializer; using NzbDrone.Common.Serializer;

View File

@ -26,7 +26,7 @@ namespace NzbDrone.Core.DecisionEngine
int compare = new QualityModelComparer(profile).Compare(newQuality, currentQuality); int compare = new QualityModelComparer(profile).Compare(newQuality, currentQuality);
if (compare <= 0) if (compare <= 0)
{ {
_logger.Trace("existing item has better or equal quality. skipping"); _logger.Debug("existing item has better or equal quality. skipping");
return false; return false;
} }
@ -50,7 +50,7 @@ namespace NzbDrone.Core.DecisionEngine
return true; return true;
} }
_logger.Trace("Existing item meets cut-off. skipping."); _logger.Debug("Existing item meets cut-off. skipping.");
return false; return false;
} }
@ -63,7 +63,7 @@ namespace NzbDrone.Core.DecisionEngine
if (currentQuality.Quality == newQuality.Quality && compare > 0) if (currentQuality.Quality == newQuality.Quality && compare > 0)
{ {
_logger.Trace("New quality is a proper for existing quality"); _logger.Debug("New quality is a proper for existing quality");
return true; return true;
} }

View File

@ -27,19 +27,19 @@ namespace NzbDrone.Core.DecisionEngine.Specifications
public virtual bool IsSatisfiedBy(RemoteEpisode subject, SearchCriteriaBase searchCriteria) public virtual bool IsSatisfiedBy(RemoteEpisode subject, SearchCriteriaBase searchCriteria)
{ {
_logger.Trace("Beginning size check for: {0}", subject); _logger.Debug("Beginning size check for: {0}", subject);
var quality = subject.ParsedEpisodeInfo.Quality.Quality; var quality = subject.ParsedEpisodeInfo.Quality.Quality;
if (quality == Quality.RAWHD) if (quality == Quality.RAWHD)
{ {
_logger.Trace("Raw-HD release found, skipping size check."); _logger.Debug("Raw-HD release found, skipping size check.");
return true; return true;
} }
if (quality == Quality.Unknown) if (quality == Quality.Unknown)
{ {
_logger.Trace("Unknown quality. skipping size check."); _logger.Debug("Unknown quality. skipping size check.");
return false; return false;
} }
@ -52,12 +52,12 @@ namespace NzbDrone.Core.DecisionEngine.Specifications
//If the parsed size is smaller than minSize we don't want it //If the parsed size is smaller than minSize we don't want it
if (subject.Release.Size < minSize) if (subject.Release.Size < minSize)
{ {
_logger.Trace("Item: {0}, Size: {1} is smaller than minimum allowed size ({2}), rejecting.", subject, subject.Release.Size, minSize); _logger.Debug("Item: {0}, Size: {1} is smaller than minimum allowed size ({2}), rejecting.", subject, subject.Release.Size, minSize);
return false; return false;
} }
if (qualityDefinition.MaxSize == 0) if (qualityDefinition.MaxSize == 0)
{ {
_logger.Trace("Max size is 0 (unlimited) - skipping check."); _logger.Debug("Max size is 0 (unlimited) - skipping check.");
} }
else else
{ {
@ -75,11 +75,11 @@ namespace NzbDrone.Core.DecisionEngine.Specifications
//If the parsed size is greater than maxSize we don't want it //If the parsed size is greater than maxSize we don't want it
if (subject.Release.Size > maxSize) if (subject.Release.Size > maxSize)
{ {
_logger.Trace("Item: {0}, Size: {1} is greater than maximum allowed size ({2}), rejecting.", subject, subject.Release.Size, maxSize); _logger.Debug("Item: {0}, Size: {1} is greater than maximum allowed size ({2}), rejecting.", subject, subject.Release.Size, maxSize);
return false; return false;
} }
} }
_logger.Trace("Item: {0}, meets size constraints.", subject); _logger.Debug("Item: {0}, meets size constraints.", subject);
return true; return true;
} }
} }

View File

@ -31,13 +31,13 @@ namespace NzbDrone.Core.DecisionEngine.Specifications
{ {
if (!_configService.EnableFailedDownloadHandling) if (!_configService.EnableFailedDownloadHandling)
{ {
_logger.Trace("Failed Download Handling is not enabled"); _logger.Debug("Failed Download Handling is not enabled");
return true; return true;
} }
if (_blacklistService.Blacklisted(subject.Series.Id, subject.Release.Title)) if (_blacklistService.Blacklisted(subject.Series.Id, subject.Release.Title))
{ {
_logger.Trace("{0} is blacklisted, rejecting.", subject.Release.Title); _logger.Debug("{0} is blacklisted, rejecting.", subject.Release.Title);
return false; return false;
} }

View File

@ -28,12 +28,12 @@ namespace NzbDrone.Core.DecisionEngine.Specifications
{ {
foreach (var file in subject.Episodes.Where(c => c.EpisodeFileId != 0).Select(c => c.EpisodeFile.Value)) foreach (var file in subject.Episodes.Where(c => c.EpisodeFileId != 0).Select(c => c.EpisodeFile.Value))
{ {
_logger.Trace("Comparing file quality with report. Existing file is {0}", file.Quality); _logger.Debug("Comparing file quality with report. Existing file is {0}", file.Quality);
if (!_qualityUpgradableSpecification.CutoffNotMet(subject.Series.QualityProfile, file.Quality, subject.ParsedEpisodeInfo.Quality)) if (!_qualityUpgradableSpecification.CutoffNotMet(subject.Series.QualityProfile, file.Quality, subject.ParsedEpisodeInfo.Quality))
{ {
_logger.Trace("Cutoff already met, rejecting."); _logger.Debug("Cutoff already met, rejecting.");
return false; return false;
} }
} }

View File

@ -24,10 +24,10 @@ namespace NzbDrone.Core.DecisionEngine.Specifications
public virtual bool IsSatisfiedBy(RemoteEpisode subject, SearchCriteriaBase searchCriteria) public virtual bool IsSatisfiedBy(RemoteEpisode subject, SearchCriteriaBase searchCriteria)
{ {
_logger.Trace("Checking if report meets language requirements. {0}", subject.ParsedEpisodeInfo.Language); _logger.Debug("Checking if report meets language requirements. {0}", subject.ParsedEpisodeInfo.Language);
if (subject.ParsedEpisodeInfo.Language != Language.English) if (subject.ParsedEpisodeInfo.Language != Language.English)
{ {
_logger.Trace("Report Language: {0} rejected because it is not English", subject.ParsedEpisodeInfo.Language); _logger.Debug("Report Language: {0} rejected because it is not English", subject.ParsedEpisodeInfo.Language);
return false; return false;
} }

View File

@ -41,7 +41,7 @@ namespace NzbDrone.Core.DecisionEngine.Specifications
if (IsInQueue(subject, queue)) if (IsInQueue(subject, queue))
{ {
_logger.Trace("Already in queue, rejecting."); _logger.Debug("Already in queue, rejecting.");
return false; return false;
} }

View File

@ -27,13 +27,13 @@ namespace NzbDrone.Core.DecisionEngine.Specifications
public virtual bool IsSatisfiedBy(RemoteEpisode subject, SearchCriteriaBase searchCriteria) public virtual bool IsSatisfiedBy(RemoteEpisode subject, SearchCriteriaBase searchCriteria)
{ {
_logger.Trace("Checking if release contains any restricted terms: {0}", subject); _logger.Debug("Checking if release contains any restricted terms: {0}", subject);
var restrictionsString = _configService.ReleaseRestrictions; var restrictionsString = _configService.ReleaseRestrictions;
if (String.IsNullOrWhiteSpace(restrictionsString)) if (String.IsNullOrWhiteSpace(restrictionsString))
{ {
_logger.Trace("No restrictions configured, allowing: {0}", subject); _logger.Debug("No restrictions configured, allowing: {0}", subject);
return true; return true;
} }
@ -43,12 +43,12 @@ namespace NzbDrone.Core.DecisionEngine.Specifications
{ {
if (subject.Release.Title.ToLowerInvariant().Contains(restriction.ToLowerInvariant())) if (subject.Release.Title.ToLowerInvariant().Contains(restriction.ToLowerInvariant()))
{ {
_logger.Trace("{0} is restricted: {1}", subject, restriction); _logger.Debug("{0} is restricted: {1}", subject, restriction);
return false; return false;
} }
} }
_logger.Trace("No restrictions apply, allowing: {0}", subject); _logger.Debug("No restrictions apply, allowing: {0}", subject);
return true; return true;
} }
} }

View File

@ -18,7 +18,7 @@ namespace NzbDrone.Core.DecisionEngine.Specifications
{ {
if (subject.Release.Title.ToLower().Contains("sample") && subject.Release.Size < 70.Megabytes()) if (subject.Release.Title.ToLower().Contains("sample") && subject.Release.Size < 70.Megabytes())
{ {
_logger.Trace("Sample release, rejecting."); _logger.Debug("Sample release, rejecting.");
return false; return false;
} }

View File

@ -23,10 +23,10 @@ namespace NzbDrone.Core.DecisionEngine.Specifications
public virtual bool IsSatisfiedBy(RemoteEpisode subject, SearchCriteriaBase searchCriteria) public virtual bool IsSatisfiedBy(RemoteEpisode subject, SearchCriteriaBase searchCriteria)
{ {
_logger.Trace("Checking if report meets quality requirements. {0}", subject.ParsedEpisodeInfo.Quality); _logger.Debug("Checking if report meets quality requirements. {0}", subject.ParsedEpisodeInfo.Quality);
if (!subject.Series.QualityProfile.Value.Items.Exists(v => v.Allowed && v.Quality == subject.ParsedEpisodeInfo.Quality.Quality)) if (!subject.Series.QualityProfile.Value.Items.Exists(v => v.Allowed && v.Quality == subject.ParsedEpisodeInfo.Quality.Quality))
{ {
_logger.Trace("Quality {0} rejected by Series' quality profile", subject.ParsedEpisodeInfo.Quality); _logger.Debug("Quality {0} rejected by Series' quality profile", subject.ParsedEpisodeInfo.Quality);
return false; return false;
} }

View File

@ -30,10 +30,10 @@ namespace NzbDrone.Core.DecisionEngine.Specifications
var age = subject.Release.Age; var age = subject.Release.Age;
var retention = _configService.Retention; var retention = _configService.Retention;
_logger.Trace("Checking if report meets retention requirements. {0}", age); _logger.Debug("Checking if report meets retention requirements. {0}", age);
if (retention > 0 && age > retention) if (retention > 0 && age > retention)
{ {
_logger.Trace("Report age: {0} rejected by user's retention limit", age); _logger.Debug("Report age: {0} rejected by user's retention limit", age);
return false; return false;
} }

View File

@ -37,21 +37,23 @@ namespace NzbDrone.Core.DecisionEngine.Specifications.RssSync
{ {
if (searchCriteria != null) if (searchCriteria != null)
{ {
_logger.Trace("Skipping history check during search"); _logger.Debug("Skipping history check during search");
return true; return true;
} }
if (_downloadClientProvider.GetDownloadClient().GetType() == typeof (Sabnzbd)) var downloadClient = _downloadClientProvider.GetDownloadClient();
if (downloadClient != null && downloadClient.GetType() == typeof (Sabnzbd))
{ {
_logger.Trace("Performing history status check on report"); _logger.Debug("Performing history status check on report");
foreach (var episode in subject.Episodes) foreach (var episode in subject.Episodes)
{ {
_logger.Trace("Checking current status of episode [{0}] in history", episode.Id); _logger.Debug("Checking current status of episode [{0}] in history", episode.Id);
var mostRecent = _historyService.MostRecentForEpisode(episode.Id); var mostRecent = _historyService.MostRecentForEpisode(episode.Id);
if (mostRecent != null && mostRecent.EventType == HistoryEventType.Grabbed) if (mostRecent != null && mostRecent.EventType == HistoryEventType.Grabbed)
{ {
_logger.Trace("Latest history item is downloading, rejecting."); _logger.Debug("Latest history item is downloading, rejecting.");
return false; return false;
} }
} }
@ -63,7 +65,7 @@ namespace NzbDrone.Core.DecisionEngine.Specifications.RssSync
var bestQualityInHistory = _historyService.GetBestQualityInHistory(subject.Series.QualityProfile, episode.Id); var bestQualityInHistory = _historyService.GetBestQualityInHistory(subject.Series.QualityProfile, episode.Id);
if (bestQualityInHistory != null) if (bestQualityInHistory != null)
{ {
_logger.Trace("Comparing history quality with report. History is {0}", bestQualityInHistory); _logger.Debug("Comparing history quality with report. History is {0}", bestQualityInHistory);
if (!_qualityUpgradableSpecification.IsUpgradable(subject.Series.QualityProfile, bestQualityInHistory, subject.ParsedEpisodeInfo.Quality)) if (!_qualityUpgradableSpecification.IsUpgradable(subject.Series.QualityProfile, bestQualityInHistory, subject.ParsedEpisodeInfo.Quality))
return false; return false;
} }

View File

@ -26,7 +26,7 @@ namespace NzbDrone.Core.DecisionEngine.Specifications.RssSync
{ {
if (searchCriteria != null) if (searchCriteria != null)
{ {
_logger.Trace("Skipping monitored check during search"); _logger.Debug("Skipping monitored check during search");
return true; return true;
} }

View File

@ -41,13 +41,13 @@ namespace NzbDrone.Core.DecisionEngine.Specifications.RssSync
{ {
if (file.DateAdded < DateTime.Today.AddDays(-7)) if (file.DateAdded < DateTime.Today.AddDays(-7))
{ {
_logger.Trace("Proper for old file, rejecting: {0}", subject); _logger.Debug("Proper for old file, rejecting: {0}", subject);
return false; return false;
} }
if (!_configService.AutoDownloadPropers) if (!_configService.AutoDownloadPropers)
{ {
_logger.Trace("Auto downloading of propers is disabled"); _logger.Debug("Auto downloading of propers is disabled");
return false; return false;
} }
} }

View File

@ -38,7 +38,7 @@ namespace NzbDrone.Core.DecisionEngine.Specifications.Search
if (!remoteEpisode.ParsedEpisodeInfo.IsDaily() || remoteEpisode.ParsedEpisodeInfo.AirDate != episode.AirDate) if (!remoteEpisode.ParsedEpisodeInfo.IsDaily() || remoteEpisode.ParsedEpisodeInfo.AirDate != episode.AirDate)
{ {
_logger.Trace("Episode AirDate does not match searched episode number, skipping."); _logger.Debug("Episode AirDate does not match searched episode number, skipping.");
return false; return false;
} }

View File

@ -33,7 +33,7 @@ namespace NzbDrone.Core.DecisionEngine.Specifications.Search
if (singleEpisodeSpec.SeasonNumber != remoteEpisode.ParsedEpisodeInfo.SeasonNumber) if (singleEpisodeSpec.SeasonNumber != remoteEpisode.ParsedEpisodeInfo.SeasonNumber)
{ {
_logger.Trace("Season number does not match searched season number, skipping."); _logger.Debug("Season number does not match searched season number, skipping.");
return false; return false;
} }

View File

@ -28,11 +28,11 @@ namespace NzbDrone.Core.DecisionEngine.Specifications.Search
return true; return true;
} }
_logger.Trace("Checking if series matches searched series"); _logger.Debug("Checking if series matches searched series");
if (remoteEpisode.Series.Id != searchCriteria.Series.Id) if (remoteEpisode.Series.Id != searchCriteria.Series.Id)
{ {
_logger.Trace("Series {0} does not match {1}", remoteEpisode.Series, searchCriteria.Series); _logger.Debug("Series {0} does not match {1}", remoteEpisode.Series, searchCriteria.Series);
return false; return false;
} }

View File

@ -34,13 +34,13 @@ namespace NzbDrone.Core.DecisionEngine.Specifications.Search
if (singleEpisodeSpec.SeasonNumber != remoteEpisode.ParsedEpisodeInfo.SeasonNumber) if (singleEpisodeSpec.SeasonNumber != remoteEpisode.ParsedEpisodeInfo.SeasonNumber)
{ {
_logger.Trace("Season number does not match searched season number, skipping."); _logger.Debug("Season number does not match searched season number, skipping.");
return false; return false;
} }
if (!remoteEpisode.ParsedEpisodeInfo.EpisodeNumbers.Contains(singleEpisodeSpec.EpisodeNumber)) if (!remoteEpisode.ParsedEpisodeInfo.EpisodeNumbers.Contains(singleEpisodeSpec.EpisodeNumber))
{ {
_logger.Trace("Episode number does not match searched episode number, skipping."); _logger.Debug("Episode number does not match searched episode number, skipping.");
return false; return false;
} }

View File

@ -28,7 +28,7 @@ namespace NzbDrone.Core.DecisionEngine.Specifications
{ {
foreach (var file in subject.Episodes.Where(c => c.EpisodeFileId != 0).Select(c => c.EpisodeFile.Value)) foreach (var file in subject.Episodes.Where(c => c.EpisodeFileId != 0).Select(c => c.EpisodeFile.Value))
{ {
_logger.Trace("Comparing file quality with report. Existing file is {0}", file.Quality); _logger.Debug("Comparing file quality with report. Existing file is {0}", file.Quality);
if (!_qualityUpgradableSpecification.IsUpgradable(subject.Series.QualityProfile, file.Quality, subject.ParsedEpisodeInfo.Quality)) if (!_qualityUpgradableSpecification.IsUpgradable(subject.Series.QualityProfile, file.Quality, subject.ParsedEpisodeInfo.Quality))
{ {

View File

@ -33,9 +33,9 @@ namespace NzbDrone.Core.Download.Clients.Blackhole
var filename = Path.Combine(Settings.Folder, title + ".nzb"); var filename = Path.Combine(Settings.Folder, title + ".nzb");
_logger.Trace("Downloading NZB from: {0} to: {1}", url, filename); _logger.Debug("Downloading NZB from: {0} to: {1}", url, filename);
_httpProvider.DownloadFile(url, filename); _httpProvider.DownloadFile(url, filename);
_logger.Trace("NZB Download succeeded, saved to: {0}", filename); _logger.Debug("NZB Download succeeded, saved to: {0}", filename);
return null; return null;
} }

View File

@ -48,7 +48,7 @@ namespace NzbDrone.Core.Download.Clients.Nzbget
{ {
var client = BuildClient(settings); var client = BuildClient(settings);
var response = client.Execute(restRequest); var response = client.Execute(restRequest);
_logger.Trace("Response: {0}", response.Content); _logger.Debug("Response: {0}", response.Content);
CheckForError(response); CheckForError(response);

View File

@ -43,10 +43,10 @@ namespace NzbDrone.Core.Download.Clients.Pneumatic
//Save to the Pneumatic directory (The user will need to ensure its accessible by XBMC) //Save to the Pneumatic directory (The user will need to ensure its accessible by XBMC)
var filename = Path.Combine(Settings.Folder, title + ".nzb"); var filename = Path.Combine(Settings.Folder, title + ".nzb");
logger.Trace("Downloading NZB from: {0} to: {1}", url, filename); logger.Debug("Downloading NZB from: {0} to: {1}", url, filename);
_httpProvider.DownloadFile(url, filename); _httpProvider.DownloadFile(url, filename);
logger.Trace("NZB Download succeeded, saved to: {0}", filename); logger.Debug("NZB Download succeeded, saved to: {0}", filename);
var contents = String.Format("plugin://plugin.program.pneumatic/?mode=strm&type=add_file&nzb={0}&nzbname={1}", filename, title); var contents = String.Format("plugin://plugin.program.pneumatic/?mode=strm&type=add_file&nzb={0}&nzbname={1}", filename, title);
_diskProvider.WriteAllText(Path.Combine(_configService.DownloadedEpisodesFolder, title + ".strm"), contents); _diskProvider.WriteAllText(Path.Combine(_configService.DownloadedEpisodesFolder, title + ".strm"), contents);

View File

@ -5,6 +5,7 @@ using NLog;
using NzbDrone.Common; using NzbDrone.Common;
using NzbDrone.Common.Serializer; using NzbDrone.Common.Serializer;
using NzbDrone.Core.Download.Clients.Sabnzbd.Responses; using NzbDrone.Core.Download.Clients.Sabnzbd.Responses;
using NzbDrone.Core.Instrumentation.Extensions;
using RestSharp; using RestSharp;
namespace NzbDrone.Core.Download.Clients.Sabnzbd namespace NzbDrone.Core.Download.Clients.Sabnzbd
@ -124,7 +125,7 @@ namespace NzbDrone.Core.Download.Clients.Sabnzbd
action, action,
authentication); authentication);
_logger.Trace(url); _logger.CleansedDebug(url);
return new RestClient(url); return new RestClient(url);
} }

View File

@ -1,7 +1,7 @@
using System; using System;
using NLog; using NLog;
using NzbDrone.Common.EnsureThat; using NzbDrone.Common.EnsureThat;
using NzbDrone.Core.Instrumentation; using NzbDrone.Core.Instrumentation.Extensions;
using NzbDrone.Core.Messaging.Events; using NzbDrone.Core.Messaging.Events;
using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Parser.Model;

View File

@ -1,4 +1,5 @@
using System.Collections.Generic; using System;
using System.Collections.Generic;
using System.Linq; using System.Linq;
using NLog; using NLog;
using NzbDrone.Common; using NzbDrone.Common;
@ -58,7 +59,7 @@ namespace NzbDrone.Core.Download
if (!failedItems.Any()) if (!failedItems.Any())
{ {
_logger.Trace("Yay! No encrypted downloads"); _logger.Debug("Yay! No encrypted downloads");
return; return;
} }
@ -69,13 +70,13 @@ namespace NzbDrone.Core.Download
if (!historyItems.Any()) if (!historyItems.Any())
{ {
_logger.Trace("Unable to find matching history item"); _logger.Debug("Unable to find matching history item");
continue; continue;
} }
if (failedHistory.Any(h => failedLocal.Id.Equals(h.Data.GetValueOrDefault(DOWNLOAD_CLIENT_ID)))) if (failedHistory.Any(h => failedLocal.Id.Equals(h.Data.GetValueOrDefault(DOWNLOAD_CLIENT_ID))))
{ {
_logger.Trace("Already added to history as failed"); _logger.Debug("Already added to history as failed");
continue; continue;
} }
@ -103,7 +104,7 @@ namespace NzbDrone.Core.Download
if (!failedItems.Any()) if (!failedItems.Any())
{ {
_logger.Trace("Yay! No failed downloads"); _logger.Debug("Yay! No failed downloads");
return; return;
} }
@ -114,13 +115,21 @@ namespace NzbDrone.Core.Download
if (!historyItems.Any()) if (!historyItems.Any())
{ {
_logger.Trace("Unable to find matching history item"); _logger.Debug("Unable to find matching history item");
continue;
}
//TODO: Make this more configurable (ignore failure reasons) to support changes and other failures that should be ignored
if (failedLocal.Message.Equals("Unpacking failed, write error or disk is full?",
StringComparison.InvariantCultureIgnoreCase))
{
_logger.Debug("Failed due to lack of disk space, do not blacklist");
continue; continue;
} }
if (failedHistory.Any(h => failedLocal.Id.Equals(h.Data.GetValueOrDefault(DOWNLOAD_CLIENT_ID)))) if (failedHistory.Any(h => failedLocal.Id.Equals(h.Data.GetValueOrDefault(DOWNLOAD_CLIENT_ID))))
{ {
_logger.Trace("Already added to history as failed"); _logger.Debug("Already added to history as failed");
continue; continue;
} }
@ -164,7 +173,7 @@ namespace NzbDrone.Core.Download
if (downloadClient == null) if (downloadClient == null)
{ {
_logger.Trace("No download client is configured"); _logger.Debug("No download client is configured");
} }
return downloadClient; return downloadClient;
@ -174,7 +183,7 @@ namespace NzbDrone.Core.Download
{ {
if (!_configService.EnableFailedDownloadHandling) if (!_configService.EnableFailedDownloadHandling)
{ {
_logger.Trace("Failed Download Handling is not enabled"); _logger.Debug("Failed Download Handling is not enabled");
return; return;
} }

View File

@ -32,13 +32,13 @@ namespace NzbDrone.Core.Download
{ {
if (!_configService.AutoRedownloadFailed) if (!_configService.AutoRedownloadFailed)
{ {
_logger.Trace("Auto redownloading failed episodes is disabled"); _logger.Debug("Auto redownloading failed episodes is disabled");
return; return;
} }
if (episodeIds.Count == 1) if (episodeIds.Count == 1)
{ {
_logger.Trace("Failed download only contains one episode, searching again"); _logger.Debug("Failed download only contains one episode, searching again");
_commandExecutor.PublishCommandAsync(new EpisodeSearchCommand _commandExecutor.PublishCommandAsync(new EpisodeSearchCommand
{ {
@ -53,7 +53,7 @@ namespace NzbDrone.Core.Download
if (episodeIds.Count == episodesInSeason.Count) if (episodeIds.Count == episodesInSeason.Count)
{ {
_logger.Trace("Failed download was entire season, searching again"); _logger.Debug("Failed download was entire season, searching again");
_commandExecutor.PublishCommandAsync(new SeasonSearchCommand _commandExecutor.PublishCommandAsync(new SeasonSearchCommand
{ {
@ -64,7 +64,7 @@ namespace NzbDrone.Core.Download
return; return;
} }
_logger.Trace("Failed download contains multiple episodes, probably a double episode, searching again"); _logger.Debug("Failed download contains multiple episodes, probably a double episode, searching again");
_commandExecutor.PublishCommandAsync(new EpisodeSearchCommand _commandExecutor.PublishCommandAsync(new EpisodeSearchCommand
{ {

View File

@ -0,0 +1,49 @@
using System;
using System.Text.RegularExpressions;
using NLog;
using NzbDrone.Common.EnvironmentInfo;
using NzbDrone.Common.Processes;
namespace NzbDrone.Core.HealthCheck.Checks
{
public class MonoVersionCheck : IProvideHealthCheck
{
private readonly IProcessProvider _processProvider;
private readonly Logger _logger;
private static readonly Regex VersionRegex = new Regex(@"(?<=\W)(?<version>\d+\.\d+\.\d+(\.\d+)?)(?=\W)", RegexOptions.Compiled | RegexOptions.IgnoreCase);
public MonoVersionCheck(IProcessProvider processProvider, Logger logger)
{
_processProvider = processProvider;
_logger = logger;
}
public HealthCheck Check()
{
if (!OsInfo.IsMono)
{
return null;
}
var output = _processProvider.StartAndCapture("mono", "--version");
foreach (var line in output.Standard)
{
var versionMatch = VersionRegex.Match(line);
if (versionMatch.Success)
{
var version = new Version(versionMatch.Groups["version"].Value);
if (version >= new Version(3, 2))
{
_logger.Debug("mono version is 3.2 or better: {0}", version.ToString());
return null;
}
}
}
return new HealthCheck(HealthCheckResultType.Warning, "mono version is less than 3.2, upgrade for improved stability");
}
}
}

View File

@ -1,5 +1,4 @@
using System; using System.Collections.Generic;
using System.Collections.Generic;
using System.Linq; using System.Linq;
using NLog; using NLog;
using NzbDrone.Core.Configuration.Events; using NzbDrone.Core.Configuration.Events;

View File

@ -16,7 +16,7 @@ namespace NzbDrone.Core.Housekeeping.Housekeepers
public void Clean() public void Clean()
{ {
_logger.Trace("Running naming spec cleanup"); _logger.Debug("Running naming spec cleanup");
var mapper = _database.GetDataMapper(); var mapper = _database.GetDataMapper();

View File

@ -16,7 +16,7 @@ namespace NzbDrone.Core.Housekeeping.Housekeepers
public void Clean() public void Clean()
{ {
_logger.Trace("Running orphaned blacklist cleanup"); _logger.Debug("Running orphaned blacklist cleanup");
var mapper = _database.GetDataMapper(); var mapper = _database.GetDataMapper();

View File

@ -16,7 +16,7 @@ namespace NzbDrone.Core.Housekeeping.Housekeepers
public void Clean() public void Clean()
{ {
_logger.Trace("Running orphaned episode files cleanup"); _logger.Debug("Running orphaned episode files cleanup");
var mapper = _database.GetDataMapper(); var mapper = _database.GetDataMapper();

View File

@ -16,7 +16,7 @@ namespace NzbDrone.Core.Housekeeping.Housekeepers
public void Clean() public void Clean()
{ {
_logger.Trace("Running orphaned episodes cleanup"); _logger.Debug("Running orphaned episodes cleanup");
var mapper = _database.GetDataMapper(); var mapper = _database.GetDataMapper();

View File

@ -16,7 +16,7 @@ namespace NzbDrone.Core.Housekeeping.Housekeepers
public void Clean() public void Clean()
{ {
_logger.Trace("Running orphaned history cleanup"); _logger.Debug("Running orphaned history cleanup");
CleanupOrphanedBySeries(); CleanupOrphanedBySeries();
CleanupOrphanedByEpisode(); CleanupOrphanedByEpisode();
} }

View File

@ -16,7 +16,7 @@ namespace NzbDrone.Core.Housekeeping.Housekeepers
public void Clean() public void Clean()
{ {
_logger.Trace("Running orphaned episode files cleanup"); _logger.Debug("Running orphaned episode files cleanup");
DeleteOrphanedBySeries(); DeleteOrphanedBySeries();
DeleteOrphanedByEpisodeFile(); DeleteOrphanedByEpisodeFile();

View File

@ -21,10 +21,10 @@ namespace NzbDrone.Core.Housekeeping.Housekeepers
{ {
if (BuildInfo.IsDebug) if (BuildInfo.IsDebug)
{ {
_logger.Trace("Not running scheduled task last execution cleanup during debug"); _logger.Debug("Not running scheduled task last execution cleanup during debug");
} }
_logger.Trace("Running scheduled task last execution cleanup"); _logger.Debug("Running scheduled task last execution cleanup");
var mapper = _database.GetDataMapper(); var mapper = _database.GetDataMapper();
mapper.AddParameter("time", DateTime.UtcNow); mapper.AddParameter("time", DateTime.UtcNow);

View File

@ -18,7 +18,7 @@ namespace NzbDrone.Core.Housekeeping.Housekeepers
public void Clean() public void Clean()
{ {
_logger.Trace("Updating CleanTitle for all series"); _logger.Debug("Updating CleanTitle for all series");
var series = _seriesRepository.All().ToList(); var series = _seriesRepository.All().ToList();

View File

@ -1,6 +1,6 @@
using NLog; using NLog;
using NzbDrone.Core.Download; using NzbDrone.Core.Download;
using NzbDrone.Core.Instrumentation; using NzbDrone.Core.Instrumentation.Extensions;
using NzbDrone.Core.Messaging.Commands; using NzbDrone.Core.Messaging.Commands;
namespace NzbDrone.Core.IndexerSearch namespace NzbDrone.Core.IndexerSearch

View File

@ -8,7 +8,7 @@ using NzbDrone.Core.DecisionEngine;
using NzbDrone.Core.DecisionEngine.Specifications; using NzbDrone.Core.DecisionEngine.Specifications;
using NzbDrone.Core.IndexerSearch.Definitions; using NzbDrone.Core.IndexerSearch.Definitions;
using NzbDrone.Core.Indexers; using NzbDrone.Core.Indexers;
using NzbDrone.Core.Instrumentation; using NzbDrone.Core.Instrumentation.Extensions;
using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Parser.Model;
using NzbDrone.Core.Tv; using NzbDrone.Core.Tv;
using System.Linq; using System.Linq;

View File

@ -1,6 +1,6 @@
using NLog; using NLog;
using NzbDrone.Core.Download; using NzbDrone.Core.Download;
using NzbDrone.Core.Instrumentation; using NzbDrone.Core.Instrumentation.Extensions;
using NzbDrone.Core.Messaging.Commands; using NzbDrone.Core.Messaging.Commands;
namespace NzbDrone.Core.IndexerSearch namespace NzbDrone.Core.IndexerSearch

View File

@ -1,6 +1,6 @@
using NLog; using NLog;
using NzbDrone.Core.Download; using NzbDrone.Core.Download;
using NzbDrone.Core.Instrumentation; using NzbDrone.Core.Instrumentation.Extensions;
using NzbDrone.Core.Messaging.Commands; using NzbDrone.Core.Messaging.Commands;
using NzbDrone.Core.Tv; using NzbDrone.Core.Tv;

View File

@ -5,6 +5,7 @@ using NLog;
using NzbDrone.Common; using NzbDrone.Common;
using NzbDrone.Core.Indexers.Exceptions; using NzbDrone.Core.Indexers.Exceptions;
using NzbDrone.Core.IndexerSearch.Definitions; using NzbDrone.Core.IndexerSearch.Definitions;
using NzbDrone.Core.Instrumentation.Extensions;
using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Parser.Model;
using System.Linq; using System.Linq;
@ -36,7 +37,7 @@ namespace NzbDrone.Core.Indexers
var result = Fetch(indexer, indexer.RecentFeed); var result = Fetch(indexer, indexer.RecentFeed);
_logger.Debug("Finished processing feeds from " + indexer); _logger.Debug("Finished processing feeds from {0} found {1} releases", indexer, result.Count);
return result; return result;
} }
@ -115,7 +116,7 @@ namespace NzbDrone.Core.Indexers
{ {
try try
{ {
_logger.Trace("Downloading Feed " + url); _logger.CleansedDebug("Downloading Feed " + url);
var xml = _httpProvider.DownloadString(url); var xml = _httpProvider.DownloadString(url);
if (!string.IsNullOrWhiteSpace(xml)) if (!string.IsNullOrWhiteSpace(xml))
{ {

View File

@ -35,7 +35,7 @@ namespace NzbDrone.Core.Indexers.Newznab
Enable = false, Enable = false,
Name = "Nzb.su", Name = "Nzb.su",
Implementation = GetType().Name, Implementation = GetType().Name,
Settings = GetSettings("https://nzb.su", new List<Int32>()) Settings = GetSettings("https://api.nzb.su", new List<Int32>())
}); });
list.Add(new IndexerDefinition list.Add(new IndexerDefinition

View File

@ -82,7 +82,7 @@ namespace NzbDrone.Core.Indexers
throw new SizeParsingException("Unable to parse size from: {0} [{1}]", reportInfo.Title, url); throw new SizeParsingException("Unable to parse size from: {0} [{1}]", reportInfo.Title, url);
} }
_logger.Trace("Parsed: {0} from: {1}", reportInfo, item.Title()); _logger.Trace("Parsed: {0}", item.Title());
return PostProcessor(item, reportInfo); return PostProcessor(item, reportInfo);
} }

View File

@ -2,7 +2,7 @@
using NLog; using NLog;
using NzbDrone.Core.DecisionEngine; using NzbDrone.Core.DecisionEngine;
using NzbDrone.Core.Download; using NzbDrone.Core.Download;
using NzbDrone.Core.Instrumentation; using NzbDrone.Core.Instrumentation.Extensions;
using NzbDrone.Core.Messaging.Commands; using NzbDrone.Core.Messaging.Commands;
namespace NzbDrone.Core.Indexers namespace NzbDrone.Core.Indexers

View File

@ -24,7 +24,7 @@ namespace NzbDrone.Core.Instrumentation
{ {
Layout = new SimpleLayout("${callsite:className=false:fileName=false:includeSourcePath=false:methodName=true}"); Layout = new SimpleLayout("${callsite:className=false:fileName=false:includeSourcePath=false:methodName=true}");
Rule = new LoggingRule("*", LogLevel.Debug, this); Rule = new LoggingRule("*", LogLevel.Info, this);
LogManager.Configuration.AddTarget("DbLogger", this); LogManager.Configuration.AddTarget("DbLogger", this);
LogManager.Configuration.LoggingRules.Add(Rule); LogManager.Configuration.LoggingRules.Add(Rule);

View File

@ -0,0 +1,45 @@
using System;
using System.Text.RegularExpressions;
using NLog;
namespace NzbDrone.Core.Instrumentation.Extensions
{
public static class LoggerCleansedExtensions
{
private static readonly Regex CleansingRegex = new Regex(@"(?<=apikey=)(\w+?)(?=\W|$|_)", RegexOptions.Compiled | RegexOptions.IgnoreCase);
public static void CleansedInfo(this Logger logger, string message, params object[] args)
{
var formattedMessage = String.Format(message, args);
LogCleansedMessage(logger, LogLevel.Info, formattedMessage);
}
public static void CleansedDebug(this Logger logger, string message, params object[] args)
{
var formattedMessage = String.Format(message, args);
LogCleansedMessage(logger, LogLevel.Debug, formattedMessage);
}
public static void CleansedTrace(this Logger logger, string message, params object[] args)
{
var formattedMessage = String.Format(message, args);
LogCleansedMessage(logger, LogLevel.Trace, formattedMessage);
}
private static void LogCleansedMessage(Logger logger, LogLevel level, string message)
{
message = Cleanse(message);
var logEvent = new LogEventInfo(level, logger.Name, message);
logger.Log(logEvent);
}
private static string Cleanse(string message)
{
//TODO: password=
return CleansingRegex.Replace(message, "<removed>");
}
}
}

View File

@ -1,7 +1,7 @@
using System; using System;
using NLog; using NLog;
namespace NzbDrone.Core.Instrumentation namespace NzbDrone.Core.Instrumentation.Extensions
{ {
public static class LoggerExtensions public static class LoggerExtensions
{ {

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