1
0
mirror of https://github.com/Sonarr/Sonarr.git synced 2024-12-16 11:37:58 +02: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 System.IO;
using NLog; using NLog;
using Nancy; using Nancy;
@ -11,7 +12,7 @@ public abstract class StaticResourceMapperBase : IMapHttpRequestsToDisk
{ {
private readonly IDiskProvider _diskProvider; private readonly IDiskProvider _diskProvider;
private readonly Logger _logger; private readonly Logger _logger;
private readonly bool _caseSensitive; private readonly StringComparison _caseSensitive;
private static readonly NotFoundResponse NotFoundResponse = new NotFoundResponse(); private static readonly NotFoundResponse NotFoundResponse = new NotFoundResponse();
@ -22,7 +23,7 @@ protected StaticResourceMapperBase(IDiskProvider diskProvider, Logger logger)
if (!RuntimeInfoBase.IsProduction) if (!RuntimeInfoBase.IsProduction)
{ {
_caseSensitive = true; _caseSensitive = StringComparison.OrdinalIgnoreCase;
} }
} }

View File

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

View File

@ -87,20 +87,27 @@ public bool FolderExists(string path)
public bool FileExists(string path) public bool FileExists(string path)
{ {
Ensure.That(path, () => path).IsValidPath(); 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(); Ensure.That(path, () => path).IsValidPath();
if (caseSensitive) switch (stringComparison)
{
case StringComparison.CurrentCulture:
case StringComparison.InvariantCulture:
case StringComparison.Ordinal:
{ {
return File.Exists(path) && path == path.GetActualCasing(); return File.Exists(path) && path == path.GetActualCasing();
} }
default:
{
return File.Exists(path); return File.Exists(path);
} }
}
}
public string[] GetDirectories(string path) public string[] GetDirectories(string path)
{ {

View File

@ -17,7 +17,7 @@ public interface IDiskProvider
void EnsureFolder(string path); void EnsureFolder(string path);
bool FolderExists(string path); bool FolderExists(string path);
bool FileExists(string path); bool FileExists(string path);
bool FileExists(string path, bool caseSensitive); bool FileExists(string path, StringComparison stringComparison);
string[] GetDirectories(string path); string[] GetDirectories(string path);
string[] GetFiles(string path, SearchOption searchOption); string[] GetFiles(string path, SearchOption searchOption);
long GetFolderSize(string path); long GetFolderSize(string path);

View File

@ -101,7 +101,7 @@ public static Param<string> IsValidPath(this Param<string> param)
if (param.Value.IsPathValid()) return param; 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)); 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 @@ public void Register()
{ {
_diskProvider.EnsureFolder(_appFolderInfo.AppDataFolder); _diskProvider.EnsureFolder(_appFolderInfo.AppDataFolder);
if (!OsInfo.IsMono) if (OsInfo.IsWindows)
{ {
SetPermissions(); SetPermissions();
} }

View File

@ -17,7 +17,7 @@ public class AppFolderInfo : IAppFolderInfo
public AppFolderInfo(IStartupContext startupContext) public AppFolderInfo(IStartupContext startupContext)
{ {
if (OsInfo.IsMono) if (OsInfo.IsNotWindows)
{ {
DATA_SPECIAL_FOLDER = Environment.SpecialFolder.ApplicationData; DATA_SPECIAL_FOLDER = Environment.SpecialFolder.ApplicationData;
} }

View File

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

View File

@ -9,7 +9,7 @@ public static class ExceptionExtentions
public static Exception ExceptronIgnoreOnMono(this Exception exception) public static Exception ExceptronIgnoreOnMono(this Exception exception)
{ {
if (OsInfo.IsMono) if (OsInfo.IsNotWindows)
{ {
exception.ExceptronIgnore(); exception.ExceptronIgnore();
} }

View File

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

View File

@ -20,14 +20,10 @@ public interface IHttpClient
public class HttpClient : IHttpClient public class HttpClient : IHttpClient
{ {
private readonly Logger _logger; private readonly Logger _logger;
private readonly string _userAgent;
public HttpClient(Logger logger) public HttpClient(Logger logger)
{ {
_logger = logger; _logger = logger;
_userAgent = String.Format("Sonarr/{0} ({1} {2})",
BuildInfo.Version,
OsInfo.Os, OsInfo.Version.ToString(2));
ServicePointManager.DefaultConnectionLimit = 12; ServicePointManager.DefaultConnectionLimit = 12;
} }
@ -44,7 +40,7 @@ public HttpResponse Execute(HttpRequest request)
webRequest.Credentials = request.NetworkCredential; webRequest.Credentials = request.NetworkCredential;
webRequest.Method = request.Method.ToString(); webRequest.Method = request.Method.ToString();
webRequest.UserAgent = _userAgent; webRequest.UserAgent = UserAgentBuilder.UserAgent;
webRequest.KeepAlive = false; webRequest.KeepAlive = false;
webRequest.AllowAutoRedirect = request.AllowAutoRedirect; webRequest.AllowAutoRedirect = request.AllowAutoRedirect;
@ -132,7 +128,7 @@ public void DownloadFile(string url, string fileName)
var stopWatch = Stopwatch.StartNew(); var stopWatch = Stopwatch.StartNew();
var webClient = new GZipWebClient(); var webClient = new GZipWebClient();
webClient.Headers.Add(HttpRequestHeader.UserAgent, _userAgent); webClient.Headers.Add(HttpRequestHeader.UserAgent, UserAgentBuilder.UserAgent);
webClient.DownloadFile(url, fileName); webClient.DownloadFile(url, fileName);
stopWatch.Stop(); stopWatch.Stop();
_logger.Debug("Downloading Completed. took {0:0}s", stopWatch.Elapsed.Seconds); _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 @@ public static void Register(IStartupContext startupContext, bool updateApp, bool
} }
else else
{ {
if (inConsole && (OsInfo.IsMono || RuntimeInfoBase.IsUserInteractive)) if (inConsole && (OsInfo.IsNotWindows || RuntimeInfoBase.IsUserInteractive))
{ {
RegisterConsole(); RegisterConsole();
} }

View File

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

View File

@ -21,12 +21,12 @@ public bool Equals(string x, string y)
public int GetHashCode(string obj) 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,10 +25,12 @@ public PidFileProvider(IAppFolderInfo appFolderInfo, IProcessProvider processPro
public void Write() public void Write()
{ {
var filename = Path.Combine(_appFolderInfo.AppDataFolder, "nzbdrone.pid"); if (OsInfo.IsWindows)
if (OsInfo.IsMono)
{ {
return;
}
var filename = Path.Combine(_appFolderInfo.AppDataFolder, "nzbdrone.pid");
try try
{ {
File.WriteAllText(filename, _processProvider.GetCurrentProcess().Id.ToString()); File.WriteAllText(filename, _processProvider.GetCurrentProcess().Id.ToString());
@ -41,4 +43,3 @@ public void Write()
} }
} }
} }
}

View File

@ -96,7 +96,7 @@ public void OpenDefaultBrowser(string url)
public Process Start(string path, string args = null, Action<string> onOutputDataReceived = null, Action<string> onErrorDataReceived = null) 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; args = path + " " + args;
path = "mono"; path = "mono";
@ -155,7 +155,7 @@ public Process Start(string path, string args = null, Action<string> onOutputDat
public Process SpawnNewProcess(string path, string args = null) 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; args = path + " " + args;
path = "mono"; path = "mono";

View File

@ -73,7 +73,7 @@ private void GivenInstallScript(string path)
.Returns(path); .Returns(path);
Mocker.GetMock<IDiskProvider>() Mocker.GetMock<IDiskProvider>()
.Setup(s => s.FileExists(path, true)) .Setup(s => s.FileExists(path, StringComparison.Ordinal))
.Returns(true); .Returns(true);
} }
@ -208,7 +208,7 @@ public void should_throw_if_script_path_does_not_exist()
GivenInstallScript(scriptPath); GivenInstallScript(scriptPath);
Mocker.GetMock<IDiskProvider>() Mocker.GetMock<IDiskProvider>()
.Setup(s => s.FileExists(scriptPath, true)) .Setup(s => s.FileExists(scriptPath, StringComparison.Ordinal))
.Returns(false); .Returns(false);
Subject.Execute(new ApplicationUpdateCommand()); Subject.Execute(new ApplicationUpdateCommand());

View File

@ -21,7 +21,7 @@ public MonoVersionCheck(IRuntimeInfo runtimeInfo, Logger logger)
public override HealthCheck Check() public override HealthCheck Check()
{ {
if (!OsInfo.IsMono) if (OsInfo.IsWindows)
{ {
return new HealthCheck(GetType()); return new HealthCheck(GetType());
} }

View File

@ -27,7 +27,7 @@ public UpdateCheck(IDiskProvider diskProvider,
public override HealthCheck Check() public override HealthCheck Check()
{ {
if (OsInfo.IsWindows || (OsInfo.IsMono && _configFileProvider.UpdateAutomatically)) if (OsInfo.IsWindows || _configFileProvider.UpdateAutomatically)
{ {
try try
{ {

View File

@ -38,7 +38,7 @@ public bool IsSatisfiedBy(LocalEpisode localEpisode)
{ {
if (parent.Name.StartsWith(workingFolder)) if (parent.Name.StartsWith(workingFolder))
{ {
if (OsInfo.IsMono) if (OsInfo.IsNotWindows)
{ {
_logger.Debug("{0} is still being unpacked", localEpisode.Path); _logger.Debug("{0} is still being unpacked", localEpisode.Path);
return false; return false;

View File

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

View File

@ -94,7 +94,7 @@ private void InstallUpdate(UpdatePackage updatePackage)
_backupService.Backup(BackupType.Update); _backupService.Backup(BackupType.Update);
if (OsInfo.IsMono && _configFileProvider.UpdateMechanism == UpdateMechanism.Script) if (OsInfo.IsNotWindows && _configFileProvider.UpdateMechanism == UpdateMechanism.Script)
{ {
InstallUpdateWithScript(updateSandboxFolder); InstallUpdateWithScript(updateSandboxFolder);
return; return;
@ -124,7 +124,7 @@ private void InstallUpdateWithScript(String updateSandboxFolder)
throw new ArgumentException("Update Script has not been defined"); 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); var message = String.Format("Update Script: '{0}' does not exist", scriptPath);
throw new FileNotFoundException(message, scriptPath); throw new FileNotFoundException(message, scriptPath);

View File

@ -30,7 +30,7 @@ public CheckUpdateService(IUpdatePackageProvider updatePackageProvider,
public UpdatePackage AvailableUpdate() public UpdatePackage AvailableUpdate()
{ {
if (OsInfo.IsMono && !_configFileProvider.UpdateAutomatically) if (OsInfo.IsNotWindows && !_configFileProvider.UpdateAutomatically)
{ {
return null; return null;
} }

View File

@ -87,7 +87,7 @@ private void OpenFirewallPort(int portNumber)
private bool IsFirewallEnabled() private bool IsFirewallEnabled()
{ {
if (OsInfo.IsMono) return false; if (OsInfo.IsNotWindows) return false;
try try
{ {

View File

@ -46,7 +46,7 @@ protected override void OnStart(string[] args)
public void Start() public void Start()
{ {
if (OsInfo.IsMono) if (OsInfo.IsNotWindows)
{ {
Console.CancelKeyPress += (sender, eventArgs) => LogManager.Configuration = null; Console.CancelKeyPress += (sender, eventArgs) => LogManager.Configuration = null;
} }

View File

@ -108,12 +108,12 @@ private static ApplicationModes GetApplicationMode(IStartupContext startupContex
return ApplicationModes.Help; return ApplicationModes.Help;
} }
if (!OsInfo.IsMono && startupContext.InstallService) if (OsInfo.IsWindows && startupContext.InstallService)
{ {
return ApplicationModes.InstallService; return ApplicationModes.InstallService;
} }
if (!OsInfo.IsMono && startupContext.UninstallService) if (OsInfo.IsWindows && startupContext.UninstallService)
{ {
return ApplicationModes.UninstallService; return ApplicationModes.UninstallService;
} }

View File

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

View File

@ -173,7 +173,7 @@ private void RegisterPlatformLibrary(IUnityContainer container)
{ {
var assemblyName = "NzbDrone.Windows"; var assemblyName = "NzbDrone.Windows";
if (OsInfo.IsMono) if (OsInfo.IsNotWindows)
{ {
assemblyName = "NzbDrone.Mono"; assemblyName = "NzbDrone.Mono";
} }

View File

@ -33,7 +33,7 @@ public void Start()
var nzbdroneConsoleExe = "NzbDrone.Console.exe"; var nzbdroneConsoleExe = "NzbDrone.Console.exe";
if (OsInfo.IsMono) if (OsInfo.IsNotWindows)
{ {
nzbdroneConsoleExe = "NzbDrone.exe"; nzbdroneConsoleExe = "NzbDrone.exe";
} }

View File

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

View File

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

View File

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

View File

@ -27,16 +27,8 @@ public TerminateNzbDrone(IServiceProvider serviceProvider, IProcessProvider proc
public void Terminate(int processId) 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);
return;
}
_logger.Info("Stopping all running services"); _logger.Info("Stopping all running services");
if (_serviceProvider.ServiceExist(ServiceProvider.NZBDRONE_SERVICE_NAME) if (_serviceProvider.ServiceExist(ServiceProvider.NZBDRONE_SERVICE_NAME)
@ -52,6 +44,11 @@ public void Terminate(int processId)
_logger.ErrorException("couldn't stop service", e); _logger.ErrorException("couldn't stop service", e);
} }
} }
}
else
{
_processProvider.Kill(processId);
}
_logger.Info("Killing all running processes"); _logger.Info("Killing all running processes");

View File

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