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 NLog;
using Nancy;
@ -11,7 +12,7 @@ public abstract class StaticResourceMapperBase : IMapHttpRequestsToDisk
{
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 @@ protected StaticResourceMapperBase(IDiskProvider diskProvider, Logger logger)
if (!RuntimeInfoBase.IsProduction)
{
_caseSensitive = true;
_caseSensitive = StringComparison.OrdinalIgnoreCase;
}
}

View File

@ -51,16 +51,16 @@ private Response GetStatus()
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 @@ private Response Restart()
}
}
}

View File

@ -87,19 +87,26 @@ public bool FolderExists(string path)
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 @@ public interface IDiskProvider
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 @@ public static Param<string> IsValidPath(this Param<string> 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));
}

View File

@ -29,7 +29,7 @@ public void Register()
{
_diskProvider.EnsureFolder(_appFolderInfo.AppDataFolder);
if (!OsInfo.IsMono)
if (OsInfo.IsWindows)
{
SetPermissions();
}

View File

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

View File

@ -15,17 +15,16 @@ static OsInfo()
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 @@ static OsInfo()
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 @@ public static class ExceptionExtentions
public static Exception ExceptronIgnoreOnMono(this Exception exception)
{
if (OsInfo.IsMono)
if (OsInfo.IsNotWindows)
{
exception.ExceptronIgnore();
}

View File

@ -29,7 +29,7 @@ public static string CleanFilePath(this string path)
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 @@ public static bool IsPathValid(this string path)
return false;
}
if (OsInfo.IsMono)
if (OsInfo.IsNotWindows)
{
return path.StartsWith(Path.DirectorySeparatorChar.ToString());
}
@ -135,7 +135,7 @@ private static string GetProperCapitalization(DirectoryInfo dirInfo)
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 @@ public interface IHttpClient
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 @@ public HttpResponse Execute(HttpRequest request)
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 @@ public void DownloadFile(string url, string fileName)
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 @@ public static void Register(IStartupContext startupContext, bool updateApp, bool
}
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 @@ public bool Equals(string x, string y)
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 @@ public PidFileProvider(IAppFolderInfo appFolderInfo, IProcessProvider processPro
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 @@ public void OpenDefaultBrowser(string url)
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 @@ public Process Start(string path, string args = null, Action<string> onOutputDat
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 @@ private void GivenInstallScript(string path)
.Returns(path);
Mocker.GetMock<IDiskProvider>()
.Setup(s => s.FileExists(path, true))
.Setup(s => s.FileExists(path, StringComparison.Ordinal))
.Returns(true);
}
@ -208,7 +208,7 @@ public void should_throw_if_script_path_does_not_exist()
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 @@ public MonoVersionCheck(IRuntimeInfo runtimeInfo, Logger logger)
public override HealthCheck Check()
{
if (!OsInfo.IsMono)
if (OsInfo.IsWindows)
{
return new HealthCheck(GetType());
}

View File

@ -24,10 +24,10 @@ public UpdateCheck(IDiskProvider diskProvider,
_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 @@ public bool IsSatisfiedBy(LocalEpisode localEpisode)
{
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 @@ public void SetFilePermissions(string path)
public void SetFolderPermissions(string path)
{
if (OsInfo.IsMono)
if (OsInfo.IsNotWindows)
{
SetMonoPermissions(path, _configService.FolderChmod);
}

View File

@ -94,7 +94,7 @@ private void InstallUpdate(UpdatePackage updatePackage)
_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 @@ private void InstallUpdateWithScript(String updateSandboxFolder)
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 @@ public CheckUpdateService(IUpdatePackageProvider updatePackageProvider,
public UpdatePackage AvailableUpdate()
{
if (OsInfo.IsMono && !_configFileProvider.UpdateAutomatically)
if (OsInfo.IsNotWindows && !_configFileProvider.UpdateAutomatically)
{
return null;
}

View File

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

View File

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

View File

@ -108,12 +108,12 @@ private static ApplicationModes GetApplicationMode(IStartupContext startupContex
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 @@ public static class PlatformValidation
public static bool IsValidate(IUserAlert userAlert)
{
if (OsInfo.IsMono)
if (OsInfo.IsNotWindows)
{
return true;
}

View File

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

View File

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

View File

@ -7,7 +7,7 @@ public static class StringExtensions
{
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 @@ public void TestBaseTearDown()
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 @@ public DetectApplicationType(IServiceProvider serviceProvider, IProcessProvider
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 @@ public TerminateNzbDrone(IServiceProvider serviceProvider, IProcessProvider proc
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}}