1
0
mirror of https://github.com/Sonarr/Sonarr.git synced 2024-10-30 15:32:31 +01:00

Cleaned up environment detection

This commit is contained in:
Keivan Beigi 2014-12-07 12:54:07 -08:00
parent cf77104a02
commit f4c202441c
35 changed files with 112 additions and 95 deletions

View File

@ -1,3 +1,4 @@
using System;
using System.IO;
using NLog;
using Nancy;
@ -11,7 +12,7 @@ namespace NzbDrone.Api.Frontend.Mappers
{
private readonly IDiskProvider _diskProvider;
private readonly Logger _logger;
private readonly bool _caseSensitive;
private readonly StringComparison _caseSensitive;
private static readonly NotFoundResponse NotFoundResponse = new NotFoundResponse();
@ -22,7 +23,7 @@ namespace NzbDrone.Api.Frontend.Mappers
if (!RuntimeInfoBase.IsProduction)
{
_caseSensitive = true;
_caseSensitive = StringComparison.OrdinalIgnoreCase;
}
}

View File

@ -51,16 +51,16 @@ namespace NzbDrone.Api.System
StartupPath = _appFolderInfo.StartUpFolder,
AppData = _appFolderInfo.GetAppDataPath(),
OsVersion = OsInfo.Version.ToString(),
IsMonoRuntime = OsInfo.IsMono,
IsMono = OsInfo.IsMono,
IsLinux = OsInfo.IsMono,
IsMonoRuntime = OsInfo.IsMonoRuntime,
IsMono = OsInfo.IsNotWindows,
IsLinux = OsInfo.IsLinux,
IsOsx = OsInfo.IsOsx,
IsWindows = OsInfo.IsWindows,
Branch = _configFileProvider.Branch,
Authentication = _configFileProvider.AuthenticationEnabled,
SqliteVersion = _database.Version,
UrlBase = _configFileProvider.UrlBase,
RuntimeVersion = OsInfo.IsMono ? _runtimeInfo.RuntimeVersion : null
RuntimeVersion = _runtimeInfo.RuntimeVersion
}.AsResponse();
}
@ -82,4 +82,3 @@ namespace NzbDrone.Api.System
}
}
}

View File

@ -87,19 +87,26 @@ namespace NzbDrone.Common.Disk
public bool FileExists(string path)
{
Ensure.That(path, () => path).IsValidPath();
return FileExists(path, OsInfo.IsMono);
return FileExists(path, OsInfo.PathStringComparison);
}
public bool FileExists(string path, bool caseSensitive)
public bool FileExists(string path, StringComparison stringComparison)
{
Ensure.That(path, () => path).IsValidPath();
if (caseSensitive)
switch (stringComparison)
{
return File.Exists(path) && path == path.GetActualCasing();
case StringComparison.CurrentCulture:
case StringComparison.InvariantCulture:
case StringComparison.Ordinal:
{
return File.Exists(path) && path == path.GetActualCasing();
}
default:
{
return File.Exists(path);
}
}
return File.Exists(path);
}
public string[] GetDirectories(string path)

View File

@ -17,7 +17,7 @@ namespace NzbDrone.Common.Disk
void EnsureFolder(string path);
bool FolderExists(string path);
bool FileExists(string path);
bool FileExists(string path, bool caseSensitive);
bool FileExists(string path, StringComparison stringComparison);
string[] GetDirectories(string path);
string[] GetFiles(string path, SearchOption searchOption);
long GetFolderSize(string path);

View File

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

View File

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

View File

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

View File

@ -15,17 +15,16 @@ namespace NzbDrone.Common.EnvironmentInfo
Version = Environment.OSVersion.Version;
IsMonoRuntime = Type.GetType("Mono.Runtime") != null;
IsMono = (platform == 4) || (platform == 6) || (platform == 128);
IsNotWindows = (platform == 4) || (platform == 6) || (platform == 128);
IsOsx = IsRunningOnMac();
IsLinux = IsMono && !IsOsx;
IsWindows = !IsMono;
IsLinux = IsNotWindows && !IsOsx;
IsWindows = !IsNotWindows;
FirstDayOfWeek = CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek;
if (!IsMono)
if (IsWindows)
{
Os = Os.Windows;
PathStringComparison = StringComparison.OrdinalIgnoreCase;
}
else
@ -38,7 +37,7 @@ namespace NzbDrone.Common.EnvironmentInfo
public static Version Version { get; private set; }
public static bool IsMonoRuntime { get; private set; }
public static bool IsMono { get; private set; }
public static bool IsNotWindows { get; private set; }
public static bool IsLinux { get; private set; }
public static bool IsOsx { get; private set; }
public static bool IsWindows { get; private set; }

View File

@ -9,7 +9,7 @@ namespace NzbDrone.Common.Exceptron
public static Exception ExceptronIgnoreOnMono(this Exception exception)
{
if (OsInfo.IsMono)
if (OsInfo.IsNotWindows)
{
exception.ExceptronIgnore();
}

View File

@ -29,7 +29,7 @@ namespace NzbDrone.Common.Extensions
var info = new FileInfo(path.Trim());
if (!OsInfo.IsMono && info.FullName.StartsWith(@"\\")) //UNC
if (OsInfo.IsWindows && info.FullName.StartsWith(@"\\")) //UNC
{
return info.FullName.TrimEnd('/', '\\', ' ');
}
@ -96,7 +96,7 @@ namespace NzbDrone.Common.Extensions
return false;
}
if (OsInfo.IsMono)
if (OsInfo.IsNotWindows)
{
return path.StartsWith(Path.DirectorySeparatorChar.ToString());
}
@ -135,7 +135,7 @@ namespace NzbDrone.Common.Extensions
public static string GetActualCasing(this string path)
{
if (OsInfo.IsMono || path.StartsWith("\\"))
if (OsInfo.IsNotWindows || path.StartsWith("\\"))
{
return path;
}

View File

@ -20,14 +20,10 @@ namespace NzbDrone.Common.Http
public class HttpClient : IHttpClient
{
private readonly Logger _logger;
private readonly string _userAgent;
public HttpClient(Logger logger)
{
_logger = logger;
_userAgent = String.Format("Sonarr/{0} ({1} {2})",
BuildInfo.Version,
OsInfo.Os, OsInfo.Version.ToString(2));
ServicePointManager.DefaultConnectionLimit = 12;
}
@ -44,7 +40,7 @@ namespace NzbDrone.Common.Http
webRequest.Credentials = request.NetworkCredential;
webRequest.Method = request.Method.ToString();
webRequest.UserAgent = _userAgent;
webRequest.UserAgent = UserAgentBuilder.UserAgent;
webRequest.KeepAlive = false;
webRequest.AllowAutoRedirect = request.AllowAutoRedirect;
@ -132,7 +128,7 @@ namespace NzbDrone.Common.Http
var stopWatch = Stopwatch.StartNew();
var webClient = new GZipWebClient();
webClient.Headers.Add(HttpRequestHeader.UserAgent, _userAgent);
webClient.Headers.Add(HttpRequestHeader.UserAgent, UserAgentBuilder.UserAgent);
webClient.DownloadFile(url, fileName);
stopWatch.Stop();
_logger.Debug("Downloading Completed. took {0:0}s", stopWatch.Elapsed.Seconds);

View File

@ -0,0 +1,17 @@
using System;
using NzbDrone.Common.EnvironmentInfo;
namespace NzbDrone.Common.Http
{
public static class UserAgentBuilder
{
public static string UserAgent { get; private set; }
static UserAgentBuilder()
{
UserAgent = String.Format("Sonarr/{0} ({1} {2}) ",
BuildInfo.Version,
OsInfo.Os, OsInfo.Version.ToString(2));
}
}
}

View File

@ -31,7 +31,7 @@ namespace NzbDrone.Common.Instrumentation
}
else
{
if (inConsole && (OsInfo.IsMono || RuntimeInfoBase.IsUserInteractive))
if (inConsole && (OsInfo.IsNotWindows || RuntimeInfoBase.IsUserInteractive))
{
RegisterConsole();
}

View File

@ -152,6 +152,7 @@
<Compile Include="Http\HttpRequestBuilder.cs" />
<Compile Include="Http\UriExtensions.cs" />
<Compile Include="Extensions\IEnumerableExtensions.cs" />
<Compile Include="Http\UserAgentBuilder.cs" />
<Compile Include="Instrumentation\CleanseLogMessage.cs" />
<Compile Include="Instrumentation\ExceptronTarget.cs" />
<Compile Include="Instrumentation\Extensions\LoggerProgressExtensions.cs" />

View File

@ -21,12 +21,12 @@ namespace NzbDrone.Common
public int GetHashCode(string obj)
{
if (OsInfo.IsMono)
if (OsInfo.IsWindows)
{
return obj.CleanFilePath().GetHashCode();
return obj.CleanFilePath().ToLower().GetHashCode();
}
return obj.CleanFilePath().ToLower().GetHashCode();
return obj.CleanFilePath().GetHashCode();
}
}
}

View File

@ -25,19 +25,20 @@ namespace NzbDrone.Common.Processes
public void Write()
{
var filename = Path.Combine(_appFolderInfo.AppDataFolder, "nzbdrone.pid");
if (OsInfo.IsMono)
if (OsInfo.IsWindows)
{
try
{
File.WriteAllText(filename, _processProvider.GetCurrentProcess().Id.ToString());
}
catch (Exception ex)
{
_logger.Error("Unable to write PID file: " + filename, ex);
throw;
}
return;
}
var filename = Path.Combine(_appFolderInfo.AppDataFolder, "nzbdrone.pid");
try
{
File.WriteAllText(filename, _processProvider.GetCurrentProcess().Id.ToString());
}
catch (Exception ex)
{
_logger.Error("Unable to write PID file: " + filename, ex);
throw;
}
}
}

View File

@ -96,7 +96,7 @@ namespace NzbDrone.Common.Processes
public Process Start(string path, string args = null, Action<string> onOutputDataReceived = null, Action<string> onErrorDataReceived = null)
{
if (OsInfo.IsMono && path.EndsWith(".exe", StringComparison.InvariantCultureIgnoreCase))
if (OsInfo.IsMonoRuntime && path.EndsWith(".exe", StringComparison.InvariantCultureIgnoreCase))
{
args = path + " " + args;
path = "mono";
@ -155,7 +155,7 @@ namespace NzbDrone.Common.Processes
public Process SpawnNewProcess(string path, string args = null)
{
if (OsInfo.IsMono && path.EndsWith(".exe", StringComparison.InvariantCultureIgnoreCase))
if (OsInfo.IsMonoRuntime && path.EndsWith(".exe", StringComparison.InvariantCultureIgnoreCase))
{
args = path + " " + args;
path = "mono";

View File

@ -73,7 +73,7 @@ namespace NzbDrone.Core.Test.UpdateTests
.Returns(path);
Mocker.GetMock<IDiskProvider>()
.Setup(s => s.FileExists(path, true))
.Setup(s => s.FileExists(path, StringComparison.Ordinal))
.Returns(true);
}
@ -208,7 +208,7 @@ namespace NzbDrone.Core.Test.UpdateTests
GivenInstallScript(scriptPath);
Mocker.GetMock<IDiskProvider>()
.Setup(s => s.FileExists(scriptPath, true))
.Setup(s => s.FileExists(scriptPath, StringComparison.Ordinal))
.Returns(false);
Subject.Execute(new ApplicationUpdateCommand());

View File

@ -21,7 +21,7 @@ namespace NzbDrone.Core.HealthCheck.Checks
public override HealthCheck Check()
{
if (!OsInfo.IsMono)
if (OsInfo.IsWindows)
{
return new HealthCheck(GetType());
}

View File

@ -24,10 +24,10 @@ namespace NzbDrone.Core.HealthCheck.Checks
_checkUpdateService = checkUpdateService;
_configFileProvider = configFileProvider;
}
public override HealthCheck Check()
{
if (OsInfo.IsWindows || (OsInfo.IsMono && _configFileProvider.UpdateAutomatically))
if (OsInfo.IsWindows || _configFileProvider.UpdateAutomatically)
{
try
{

View File

@ -38,7 +38,7 @@ namespace NzbDrone.Core.MediaFiles.EpisodeImport.Specifications
{
if (parent.Name.StartsWith(workingFolder))
{
if (OsInfo.IsMono)
if (OsInfo.IsNotWindows)
{
_logger.Debug("{0} is still being unpacked", localEpisode.Path);
return false;

View File

@ -60,7 +60,7 @@ namespace NzbDrone.Core.MediaFiles
public void SetFolderPermissions(string path)
{
if (OsInfo.IsMono)
if (OsInfo.IsNotWindows)
{
SetMonoPermissions(path, _configService.FolderChmod);
}

View File

@ -94,7 +94,7 @@ namespace NzbDrone.Core.Update
_backupService.Backup(BackupType.Update);
if (OsInfo.IsMono && _configFileProvider.UpdateMechanism == UpdateMechanism.Script)
if (OsInfo.IsNotWindows && _configFileProvider.UpdateMechanism == UpdateMechanism.Script)
{
InstallUpdateWithScript(updateSandboxFolder);
return;
@ -124,7 +124,7 @@ namespace NzbDrone.Core.Update
throw new ArgumentException("Update Script has not been defined");
}
if (!_diskProvider.FileExists(scriptPath, true))
if (!_diskProvider.FileExists(scriptPath, StringComparison.Ordinal))
{
var message = String.Format("Update Script: '{0}' does not exist", scriptPath);
throw new FileNotFoundException(message, scriptPath);

View File

@ -30,7 +30,7 @@ namespace NzbDrone.Core.Update
public UpdatePackage AvailableUpdate()
{
if (OsInfo.IsMono && !_configFileProvider.UpdateAutomatically)
if (OsInfo.IsNotWindows && !_configFileProvider.UpdateAutomatically)
{
return null;
}

View File

@ -87,7 +87,7 @@ namespace NzbDrone.Host.AccessControl
private bool IsFirewallEnabled()
{
if (OsInfo.IsMono) return false;
if (OsInfo.IsNotWindows) return false;
try
{

View File

@ -46,7 +46,7 @@ namespace NzbDrone.Host
public void Start()
{
if (OsInfo.IsMono)
if (OsInfo.IsNotWindows)
{
Console.CancelKeyPress += (sender, eventArgs) => LogManager.Configuration = null;
}

View File

@ -108,12 +108,12 @@ namespace NzbDrone.Host
return ApplicationModes.Help;
}
if (!OsInfo.IsMono && startupContext.InstallService)
if (OsInfo.IsWindows && startupContext.InstallService)
{
return ApplicationModes.InstallService;
}
if (!OsInfo.IsMono && startupContext.UninstallService)
if (OsInfo.IsWindows && startupContext.UninstallService)
{
return ApplicationModes.UninstallService;
}

View File

@ -15,7 +15,7 @@ namespace NzbDrone.Host
public static bool IsValidate(IUserAlert userAlert)
{
if (OsInfo.IsMono)
if (OsInfo.IsNotWindows)
{
return true;
}

View File

@ -173,7 +173,7 @@ namespace NzbDrone.Test.Common.AutoMoq
{
var assemblyName = "NzbDrone.Windows";
if (OsInfo.IsMono)
if (OsInfo.IsNotWindows)
{
assemblyName = "NzbDrone.Mono";
}

View File

@ -33,7 +33,7 @@ namespace NzbDrone.Test.Common
var nzbdroneConsoleExe = "NzbDrone.Console.exe";
if (OsInfo.IsMono)
if (OsInfo.IsNotWindows)
{
nzbdroneConsoleExe = "NzbDrone.exe";
}

View File

@ -7,7 +7,7 @@ namespace NzbDrone.Test.Common
{
public static string AsOsAgnostic(this string path)
{
if (OsInfo.IsMono)
if (OsInfo.IsNotWindows)
{
if (path.Length > 2 && path[1] == ':')
{

View File

@ -128,16 +128,15 @@ namespace NzbDrone.Test.Common
protected void WindowsOnly()
{
if (OsInfo.IsMono)
if (OsInfo.IsNotWindows)
{
throw new IgnoreException("windows specific test");
}
}
protected void MonoOnly()
{
if (!OsInfo.IsMono)
if (OsInfo.IsWindows)
{
throw new IgnoreException("mono specific test");
}

View File

@ -22,7 +22,7 @@ namespace NzbDrone.Update.UpdateEngine
public AppType GetAppType()
{
if (OsInfo.IsMono)
if (OsInfo.IsNotWindows)
{
//Tehcnically its the console, but its been renamed for mono (Linux/OS X)
return AppType.Normal;

View File

@ -27,34 +27,31 @@ namespace NzbDrone.Update.UpdateEngine
public void Terminate(int processId)
{
if (OsInfo.IsMono)
if (OsInfo.IsWindows)
{
_logger.Info("Stopping all instances");
_processProvider.Kill(processId);
_processProvider.KillAll(ProcessProvider.NZB_DRONE_CONSOLE_PROCESS_NAME);
_processProvider.KillAll(ProcessProvider.NZB_DRONE_PROCESS_NAME);
_logger.Info("Stopping all running services");
return;
if (_serviceProvider.ServiceExist(ServiceProvider.NZBDRONE_SERVICE_NAME)
&& _serviceProvider.IsServiceRunning(ServiceProvider.NZBDRONE_SERVICE_NAME))
{
try
{
_logger.Info("NzbDrone Service is installed and running");
_serviceProvider.Stop(ServiceProvider.NZBDRONE_SERVICE_NAME);
}
catch (Exception e)
{
_logger.ErrorException("couldn't stop service", e);
}
}
}
_logger.Info("Stopping all running services");
if (_serviceProvider.ServiceExist(ServiceProvider.NZBDRONE_SERVICE_NAME)
&& _serviceProvider.IsServiceRunning(ServiceProvider.NZBDRONE_SERVICE_NAME))
else
{
try
{
_logger.Info("NzbDrone Service is installed and running");
_serviceProvider.Stop(ServiceProvider.NZBDRONE_SERVICE_NAME);
}
catch (Exception e)
{
_logger.ErrorException("couldn't stop service", e);
}
_processProvider.Kill(processId);
}
_logger.Info("Killing all running processes");
_processProvider.KillAll(ProcessProvider.NZB_DRONE_CONSOLE_PROCESS_NAME);
_processProvider.KillAll(ProcessProvider.NZB_DRONE_PROCESS_NAME);
}

View File

@ -5,7 +5,7 @@
<dt>Version</dt>
<dd>{{version}}</dd>
{{#if isMono}}
{{#if isMonoRuntime}}
<dt>Mono Version</dt>
<dd>{{runtimeVersion}}</dd>
{{/if}}