core: code cleanup, exception messages (#9631)

This commit is contained in:
Diego Heras
2020-09-24 22:02:45 +02:00
committed by GitHub
parent 39f7add32b
commit b212169dc2
11 changed files with 180 additions and 276 deletions

View File

@@ -43,7 +43,7 @@ namespace Jackett.Server.Controllers
var indexer = indexerService.GetWebIndexer(indexerID);
if (!indexer.IsConfigured)
{
logger.Warn(string.Format("Rejected a request to {0} which is unconfigured.", indexer.DisplayName));
logger.Warn($"Rejected a request to {indexer.DisplayName} which is unconfigured.");
throw new Exception("This indexer is not configured.");
}
@@ -79,7 +79,7 @@ namespace Jackett.Server.Controllers
if (!Directory.Exists(serverConfig.BlackholeDir))
{
throw new Exception("Blackhole directory does not exist: " + serverConfig.BlackholeDir);
throw new Exception($"Blackhole directory does not exist: {serverConfig.BlackholeDir}");
}
var fileName = DateTime.Now.Ticks.ToString() + "-" + StringUtil.MakeValidFileName(indexer.DisplayName, '_', false);
@@ -91,11 +91,11 @@ namespace Jackett.Server.Controllers
System.IO.File.WriteAllBytes(Path.Combine(serverConfig.BlackholeDir, fileName), downloadBytes);
jsonReply["result"] = "success";
}
catch (Exception ex)
catch (Exception e)
{
logger.Error(ex, "Error downloading to blackhole " + indexerID + " " + path);
logger.Error($"Error downloading to blackhole. indexer: {indexerID} path: {path}\n{e}");
jsonReply["result"] = "error";
jsonReply["error"] = ex.Message;
jsonReply["error"] = e.Message;
}
return Json(jsonReply);

View File

@@ -45,7 +45,7 @@ namespace Jackett.Server.Controllers
if (!indexer.IsConfigured)
{
logger.Warn(string.Format("Rejected a request to {0} which is unconfigured.", indexer.DisplayName));
logger.Warn($"Rejected a request to {indexer.DisplayName} which is unconfigured.");
return Forbid("This indexer is not configured.");
}
@@ -91,7 +91,7 @@ namespace Jackett.Server.Controllers
}
catch (Exception e)
{
logger.Error(e, "Error downloading " + indexerID + " " + path);
logger.Error($"Error downloading. indexer: {indexerID} path: {path}\n{e}");
return NotFound();
}
}

View File

@@ -223,16 +223,16 @@ namespace Jackett.Server.Controllers
var aggregateTask = Task.WhenAll(tasks);
await aggregateTask;
}
catch (AggregateException aex)
catch (AggregateException e)
{
foreach (var ex in aex.InnerExceptions)
foreach (var ex in e.InnerExceptions)
{
logger.Error(ex);
}
}
catch (Exception ex)
catch (Exception e)
{
logger.Error(ex);
logger.Error(e);
}
manualResult.Indexers = tasks.Select(t =>
@@ -440,10 +440,10 @@ namespace Jackett.Server.Controllers
return Content(xml, "application/rss+xml", Encoding.UTF8);
}
catch (Exception ex)
catch (Exception e)
{
logger.Error(ex);
return GetErrorXML(900, ex.ToString());
logger.Error(e);
return GetErrorXML(900, e.ToString());
}
}

View File

@@ -25,44 +25,35 @@ namespace Jackett.Server.Middleware
{
await _next(httpContext);
}
catch (Exception ex)
catch (Exception e)
{
try
{
var msg = "";
logger.Error(e);
var message = e.Message;
if (e.InnerException != null)
message += ": " + e.InnerException.Message;
var msg = message;
var json = new JObject();
logger.Error(ex);
var message = ex.Message;
if (ex.InnerException != null)
{
message += ": " + ex.InnerException.Message;
}
msg = message;
if (ex is ExceptionWithConfigData)
{
json["config"] = ((ExceptionWithConfigData)ex).ConfigData.ToJson(null, false);
}
if (e is ExceptionWithConfigData)
json["config"] = ((ExceptionWithConfigData)e).ConfigData.ToJson(null, false);
json["result"] = "error";
json["error"] = msg;
json["stacktrace"] = ex.StackTrace;
if (ex.InnerException != null)
{
json["innerstacktrace"] = ex.InnerException.StackTrace;
}
json["stacktrace"] = e.StackTrace;
if (e.InnerException != null)
json["innerstacktrace"] = e.InnerException.StackTrace;
httpContext.Response.StatusCode = StatusCodes.Status500InternalServerError;
httpContext.Response.ContentType = "application/json";
await httpContext.Response.WriteAsync(json.ToString());
return;
}
catch (Exception ex2)
catch (Exception e2)
{
logger.Error(ex2, "An exception was thrown attempting to execute the custom exception error handler.");
logger.Error($"An exception was thrown attempting to execute the custom exception error handler.\n{e2}");
}
await _next(httpContext);

View File

@@ -40,7 +40,6 @@ namespace Jackett.Server
text.Heading = "Jackett v" + EnvironmentUtil.JackettVersion;
Console.WriteLine(text);
Environment.Exit(1);
return;
});
optionsResult.WithParsed(options =>
@@ -67,7 +66,7 @@ namespace Jackett.Server
}
catch (Exception e)
{
logger.Error(e, "Error while creating the PID file");
logger.Error($"Error while creating the PID file\n{e}");
}
}
@@ -89,7 +88,7 @@ namespace Jackett.Server
}
else
{
logger.Error($"ReserveUrls and service arguments only apply to Windows, please remove them from your start arguments");
logger.Error("ReserveUrls and service arguments only apply to Windows, please remove them from your start arguments");
Environment.Exit(1);
}
}
@@ -125,14 +124,14 @@ namespace Jackett.Server
CreateWebHostBuilder(args, url, applicationFolder).Build().Run();
}
catch (Exception ex)
catch (Exception e)
{
if (ex.InnerException is Microsoft.AspNetCore.Connections.AddressInUseException)
if (e.InnerException is Microsoft.AspNetCore.Connections.AddressInUseException)
{
logger.Error("Address already in use: Most likely Jackett is already running. " + ex.Message);
logger.Error($"Address already in use: Most likely Jackett is already running. {e.Message}");
Environment.Exit(1);
}
logger.Error(ex);
logger.Error(e);
throw;
}
} while (isWebHostRestart);
@@ -152,11 +151,11 @@ namespace Jackett.Server
{
if (Settings != null && !string.IsNullOrWhiteSpace(Settings.PIDFile))
{
var PIDFile = Settings.PIDFile;
if (File.Exists(PIDFile))
var pidFile = Settings.PIDFile;
if (File.Exists(pidFile))
{
Console.WriteLine("Deleting PID file " + PIDFile);
File.Delete(PIDFile);
Console.WriteLine("Deleting PID file " + pidFile);
File.Delete(pidFile);
}
LogManager.Shutdown();
}

View File

@@ -50,32 +50,26 @@ namespace Jackett.Server.Services
public Uri ConvertToProxyLink(Uri link, string serverUrl, string indexerId, string action = "dl", string file = "t")
{
if (link == null || (link.IsAbsoluteUri && link.Scheme == "magnet" && action != "bh")) // no need to convert a magnet link to a proxy link unless it's a blackhole link
// no need to convert a magnet link to a proxy link unless it's a blackhole link
if (link == null || (link.IsAbsoluteUri && link.Scheme == "magnet" && action != "bh"))
return link;
var encryptedLink = _protectionService.Protect(link.ToString());
var encodedLink = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(encryptedLink));
var urlEncodedFile = WebUtility.UrlEncode(file);
var proxyLink = string.Format("{0}{1}/{2}/?jackett_apikey={3}&path={4}&file={5}", serverUrl, action, indexerId, config.APIKey, encodedLink, urlEncodedFile);
var proxyLink = $"{serverUrl}{action}/{indexerId}/?jackett_apikey={config.APIKey}&path={encodedLink}&file={urlEncodedFile}";
return new Uri(proxyLink);
}
public string BasePath()
{
// Use string.IsNullOrEmpty
if (config.BasePathOverride == null || config.BasePathOverride == "")
{
if (string.IsNullOrEmpty(config.BasePathOverride))
return "";
}
var path = config.BasePathOverride;
if (path.EndsWith("/"))
{
path = path.TrimEnd('/');
}
if (!path.StartsWith("/"))
{
path = "/" + path;
}
return path;
}
@@ -85,14 +79,13 @@ namespace Jackett.Server.Services
{
var x = Environment.OSVersion;
var runtimedir = RuntimeEnvironment.GetRuntimeDirectory();
logger.Info("Environment version: " + Environment.Version.ToString() + " (" + runtimedir + ")");
logger.Info(
"OS version: " + Environment.OSVersion.ToString() +
logger.Info($"Environment version: {Environment.Version} ({runtimedir})");
logger.Info($"OS version: {Environment.OSVersion}" +
(Environment.Is64BitOperatingSystem ? " (64bit OS)" : "") +
(Environment.Is64BitProcess ? " (64bit process)" : ""));
var variants = new Variants();
var variant = variants.GetVariant();
logger.Info("Jackett variant: " + variant.ToString());
logger.Info($"Jackett variant: {variant}");
try
{
@@ -107,7 +100,7 @@ namespace Jackett.Server.Services
}
catch (Exception e)
{
logger.Error(e, "Error while reading the issue file");
logger.Error($"Error while reading the issue file\n{e}");
}
try
@@ -127,7 +120,7 @@ namespace Jackett.Server.Services
}
catch (Exception e)
{
logger.Error(e, "Error while reading the Docker cgroup file");
logger.Error($"Error while reading the Docker cgroup file.\n{e}");
}
try
@@ -168,7 +161,7 @@ namespace Jackett.Server.Services
if (monoVersionO.Major < 5 || (monoVersionO.Major == 5 && monoVersionO.Minor < 8))
{
var notice = "A minimum Mono version of 5.8 is required. Please update to the latest version from http://www.mono-project.com/download/";
const string notice = "A minimum Mono version of 5.8 is required. Please update to the latest version from http://www.mono-project.com/download/";
notices.Add(notice);
logger.Error(notice);
}
@@ -177,35 +170,33 @@ namespace Jackett.Server.Services
{
// Check for mono-devel
// Is there any better way which doesn't involve a hard cashes?
var mono_devel_file = Path.Combine(runtimedir, "mono-api-info.exe");
if (!File.Exists(mono_devel_file))
var monoDevelFile = Path.Combine(runtimedir, "mono-api-info.exe");
if (!File.Exists(monoDevelFile))
{
var notice =
"It looks like the mono-devel package is not installed, please make sure it's installed to avoid crashes.";
const string notice = "It looks like the mono-devel package is not installed, please make sure it's installed to avoid crashes.";
notices.Add(notice);
logger.Error(notice);
}
}
catch (Exception e)
{
logger.Error(e, "Error while checking for mono-devel");
logger.Error($"Error while checking for mono-devel.\n{e}");
}
try
{
// Check for ca-certificates-mono
var mono_cert_file = Path.Combine(runtimedir, "cert-sync.exe");
if (!File.Exists(mono_cert_file))
var monoCertFile = Path.Combine(runtimedir, "cert-sync.exe");
if (!File.Exists(monoCertFile))
{
var notice =
"The ca-certificates-mono package is not installed, HTTPS trackers won't work. Please install it.";
const string notice = "The ca-certificates-mono package is not installed, HTTPS trackers won't work. Please install it.";
notices.Add(notice);
logger.Error(notice);
}
}
catch (Exception e)
{
logger.Error(e, "Error while checking for ca-certificates-mono");
logger.Error($"Error while checking for ca-certificates-mono.\n{e}");
}
try
@@ -214,8 +205,7 @@ namespace Jackett.Server.Services
}
catch (NotSupportedException e)
{
logger.Debug(e);
logger.Error(e.Message + " Most likely the mono-locale-extras package is not installed.");
logger.Error($"Most likely the mono-locale-extras package is not installed.\n{e}");
Environment.Exit(2);
}
@@ -229,39 +219,37 @@ namespace Jackett.Server.Services
var monoX509StoreManager = monoSecurity.GetType("Mono.Security.X509.X509StoreManager");
if (monoX509StoreManager != null)
{
var TrustedRootCertificatesProperty =
monoX509StoreManager.GetProperty("TrustedRootCertificates");
var TrustedRootCertificates = (ICollection)TrustedRootCertificatesProperty.GetValue(null);
var trustedRootCertificatesProperty = monoX509StoreManager.GetProperty("TrustedRootCertificates");
var trustedRootCertificates = (ICollection)trustedRootCertificatesProperty.GetValue(null);
logger.Info("TrustedRootCertificates count: " + TrustedRootCertificates.Count);
logger.Info($"TrustedRootCertificates count: {trustedRootCertificates.Count}");
if (TrustedRootCertificates.Count == 0)
if (trustedRootCertificates.Count == 0)
{
var CACertificatesFiles = new string[]
var caCertificatesFiles = new[]
{
"/etc/ssl/certs/ca-certificates.crt", // Debian based
"/etc/pki/tls/certs/ca-bundle.c", // RedHat based
"/etc/ssl/ca-bundle.pem", // SUSE
};
const string logSpacer = " ";
var notice = "The mono certificate store is not initialized.<br/>\n";
var logSpacer = " ";
var CACertificatesFile = CACertificatesFiles.Where(File.Exists).FirstOrDefault();
var CommandRoot = "curl -sS https://curl.haxx.se/ca/cacert.pem | cert-sync /dev/stdin";
var CommandUser =
"curl -sS https://curl.haxx.se/ca/cacert.pem | cert-sync --user /dev/stdin";
if (CACertificatesFile != null)
var caCertificatesFile = caCertificatesFiles.Where(File.Exists).FirstOrDefault();
var commandRoot = "curl -sS https://curl.haxx.se/ca/cacert.pem | cert-sync /dev/stdin";
var commandUser = "curl -sS https://curl.haxx.se/ca/cacert.pem | cert-sync --user /dev/stdin";
if (caCertificatesFile != null)
{
CommandRoot = "cert-sync " + CACertificatesFile;
CommandUser = "cert-sync --user " + CACertificatesFile;
commandRoot = "cert-sync " + caCertificatesFile;
commandUser = "cert-sync --user " + caCertificatesFile;
}
notice += logSpacer + "Please run the following command as root:<br/>\n";
notice += logSpacer + "<pre>" + CommandRoot + "</pre><br/>\n";
notice += logSpacer + "<pre>" + commandRoot + "</pre><br/>\n";
notice += logSpacer +
"If you don't have root access or you're running MacOS, please run the following command as the jackett user (" +
Environment.UserName + "):<br/>\n";
notice += logSpacer + "<pre>" + CommandUser + "</pre>";
notice += logSpacer + "<pre>" + commandUser + "</pre>";
notices.Add(notice);
logger.Error(Regex.Replace(notice, "<.*?>", string.Empty));
}
@@ -269,7 +257,7 @@ namespace Jackett.Server.Services
}
catch (Exception e)
{
logger.Error(e, "Error while chekcing the mono certificate store");
logger.Error($"Error while chekcing the mono certificate store.\n{e}");
}
}
}
@@ -290,7 +278,7 @@ namespace Jackett.Server.Services
}
catch (Exception e)
{
logger.Error(e, "Error while checking the username");
logger.Error($"Error while checking the username.\n{e}");
}
//Warn user that they are using an old version of Jackett
@@ -308,7 +296,7 @@ namespace Jackett.Server.Services
}
catch (Exception e)
{
logger.Error(e, "Error while checking build date of Jackett.Common");
logger.Error($"Error while checking build date of Jackett.Common.\n{e}");
}
//Alert user that they no longer need to use Mono
@@ -319,11 +307,16 @@ namespace Jackett.Server.Services
if (variant == Variants.JackettVariant.Mono)
{
var process = new Process();
process.StartInfo.FileName = "uname";
process.StartInfo.Arguments = "-m";
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
var process = new Process
{
StartInfo =
{
FileName = "uname",
Arguments = "-m",
UseShellExecute = false,
RedirectStandardOutput = true
}
};
process.Start();
var output = process.StandardOutput.ReadToEnd();
process.WaitForExit();
@@ -331,14 +324,12 @@ namespace Jackett.Server.Services
output = output.ToLower();
if (output.Contains("armv7") || output.Contains("armv8") || output.Contains("x86_64"))
{
isDotNetCoreCapable = true;
}
}
}
catch (Exception e)
{
logger.Debug(e, "Unable to get architecture");
logger.Debug($"Unable to get architecture.\n{e}");
}
CultureInfo.DefaultThreadCurrentCulture = new CultureInfo("en-US");
@@ -356,12 +347,12 @@ namespace Jackett.Server.Services
public void ReserveUrls(bool doInstall = true)
{
logger.Debug("Unreserving Urls");
config.GetListenAddresses(false).ToList().ForEach(u => RunNetSh(string.Format("http delete urlacl {0}", u)));
config.GetListenAddresses(true).ToList().ForEach(u => RunNetSh(string.Format("http delete urlacl {0}", u)));
config.GetListenAddresses(false).ToList().ForEach(u => RunNetSh($"http delete urlacl {u}"));
config.GetListenAddresses(true).ToList().ForEach(u => RunNetSh($"http delete urlacl {u}"));
if (doInstall)
{
logger.Debug("Reserving Urls");
config.GetListenAddresses(true).ToList().ForEach(u => RunNetSh(string.Format("http add urlacl {0} sddl=D:(A;;GX;;;S-1-1-0)", u)));
config.GetListenAddresses(true).ToList().ForEach(u => RunNetSh($"http add urlacl {u} sddl=D:(A;;GX;;;S-1-1-0)"));
logger.Debug("Urls reserved");
}
}
@@ -375,33 +366,23 @@ namespace Jackett.Server.Services
public string GetServerUrl(HttpRequest request)
{
var serverUrl = "";
var scheme = request.Scheme;
var port = request.HttpContext.Request.Host.Port;
// Check for protocol headers added by reverse proxys
// X-Forwarded-Proto: A de facto standard for identifying the originating protocol of an HTTP request
var X_Forwarded_Proto = request.Headers.Where(x => x.Key == "X-Forwarded-Proto").Select(x => x.Value).FirstOrDefault();
if (X_Forwarded_Proto.Count > 0)
{
scheme = X_Forwarded_Proto.First();
}
var xForwardedProto = request.Headers.Where(x => x.Key == "X-Forwarded-Proto").Select(x => x.Value).FirstOrDefault();
if (xForwardedProto.Count > 0)
scheme = xForwardedProto.First();
// Front-End-Https: Non-standard header field used by Microsoft applications and load-balancers
else if (request.Headers.Where(x => x.Key == "Front-End-Https" && x.Value.FirstOrDefault() == "on").Any())
{
scheme = "https";
}
//default to 443 if the Host header doesn't contain the port (needed for reverse proxy setups)
if (scheme == "https" && !request.HttpContext.Request.Host.Value.Contains(":"))
{
port = 443;
}
serverUrl = string.Format("{0}://{1}:{2}{3}/", scheme, request.HttpContext.Request.Host.Host, port, BasePath());
return serverUrl;
return $"{scheme}://{request.HttpContext.Request.Host.Host}:{port}{BasePath()}/";
}
public string GetBlackholeDirectory() => config.BlackholeDir;