diff --git a/src/Jackett.Common/Services/ConfigurationService.cs b/src/Jackett.Common/Services/ConfigurationService.cs index ccb3068e1..d634d5405 100644 --- a/src/Jackett.Common/Services/ConfigurationService.cs +++ b/src/Jackett.Common/Services/ConfigurationService.cs @@ -87,9 +87,9 @@ namespace Jackett.Common.Services } } - catch (Exception ex) + catch (Exception e) { - logger.Error("ERROR could not migrate settings directory " + ex); + logger.Error($"ERROR could not migrate settings directory\n{e}"); } } } @@ -144,7 +144,7 @@ namespace Jackett.Common.Services } catch (Exception e) { - logger.Error(e, "Error reading config file " + fullPath); + logger.Error($"Error reading config file {fullPath}\n{e}"); return default; } } @@ -162,7 +162,7 @@ namespace Jackett.Common.Services } catch (Exception e) { - logger.Error(e, "Error writing config file " + fullPath); + logger.Error($"Error writing config file {fullPath}\n{e}"); } } diff --git a/src/Jackett.Common/Services/IndexerConfigurationService.cs b/src/Jackett.Common/Services/IndexerConfigurationService.cs index 9f0d2efcd..efec070ed 100644 --- a/src/Jackett.Common/Services/IndexerConfigurationService.cs +++ b/src/Jackett.Common/Services/IndexerConfigurationService.cs @@ -37,46 +37,39 @@ namespace Jackett.Common.Services File.Delete(configFilePath); var configFilePathBak = configFilePath + ".bak"; if (File.Exists(configFilePathBak)) - { File.Delete(configFilePathBak); - } } public void Load(IIndexer indexer) { var configFilePath = GetIndexerConfigFilePath(indexer.Id); - if (File.Exists(configFilePath)) + if (!File.Exists(configFilePath)) + return; + try { - try - { - var fileStr = File.ReadAllText(configFilePath); - var jsonString = JToken.Parse(fileStr); - indexer.LoadFromSavedConfiguration(jsonString); - } - catch (Exception ex) - { - logger.Error(ex, "Failed loading configuration for {0}, trying backup", indexer.DisplayName); - var configFilePathBak = configFilePath + ".bak"; - if (File.Exists(configFilePathBak)) + var fileStr = File.ReadAllText(configFilePath); + var jsonString = JToken.Parse(fileStr); + indexer.LoadFromSavedConfiguration(jsonString); + } + catch (Exception e) + { + logger.Error($"Failed loading configuration for {indexer.DisplayName}, trying backup\n{e}"); + var configFilePathBak = configFilePath + ".bak"; + if (File.Exists(configFilePathBak)) + try { - try - { - var fileStrBak = File.ReadAllText(configFilePathBak); - var jsonStringBak = JToken.Parse(fileStrBak); - indexer.LoadFromSavedConfiguration(jsonStringBak); - logger.Info("Successfully loaded backup config for {0}", indexer.DisplayName); - indexer.SaveConfig(); - } - catch (Exception exbak) - { - logger.Error(exbak, "Failed loading backup configuration for {0}, you must reconfigure this indexer", indexer.DisplayName); - } + var fileStrBak = File.ReadAllText(configFilePathBak); + var jsonStringBak = JToken.Parse(fileStrBak); + indexer.LoadFromSavedConfiguration(jsonStringBak); + logger.Info($"Successfully loaded backup config for {indexer.DisplayName}"); + indexer.SaveConfig(); } - else + catch (Exception e2) { - logger.Error(ex, "Failed loading backup configuration for {0} (no backup available), you must reconfigure this indexer", indexer.DisplayName); + logger.Error($"Failed loading backup configuration for {indexer.DisplayName}, you must reconfigure this indexer\n{e2}"); } - } + else + logger.Error($"Failed loading backup configuration for {indexer.DisplayName} (no backup available), you must reconfigure this indexer\n{e}"); } } @@ -84,23 +77,19 @@ namespace Jackett.Common.Services { lock (configWriteLock) { - var uID = Guid.NewGuid().ToString("N"); + var uId = Guid.NewGuid().ToString("N"); var configFilePath = GetIndexerConfigFilePath(indexer.Id); var configFilePathBak = configFilePath + ".bak"; - var configFilePathTmp = configFilePath + "." + uID + ".tmp"; + var configFilePathTmp = configFilePath + "." + uId + ".tmp"; var content = obj.ToString(); - logger.Debug(string.Format("Saving new config file: {0}", configFilePathTmp)); + logger.Debug($"Saving new config file: {configFilePathTmp}"); if (string.IsNullOrWhiteSpace(content)) - { - throw new Exception(string.Format("New config content for {0} is empty, please report this bug.", indexer.Id)); - } + throw new Exception($"New config content for {indexer.Id} is empty, please report this bug."); if (content.Contains("\x00")) - { - throw new Exception(string.Format("New config content for {0} contains 0x00, please report this bug. Content: {1}", indexer.Id, content)); - } + throw new Exception($"New config content for {indexer.Id} contains 0x00, please report this bug. Content: {content}"); // make sure the config directory exists if (!Directory.Exists(configService.GetIndexerConfigDir())) @@ -110,23 +99,19 @@ namespace Jackett.Common.Services File.WriteAllText(configFilePathTmp, content); var fileInfo = new FileInfo(configFilePathTmp); if (fileInfo.Length == 0) - { - throw new Exception(string.Format("New config file {0} is empty, please report this bug.", configFilePathTmp)); - } + throw new Exception($"New config file {configFilePathTmp} is empty, please report this bug."); // create backup file File.Delete(configFilePathBak); if (File.Exists(configFilePath)) - { try { File.Move(configFilePath, configFilePathBak); } - catch (IOException ex) + catch (IOException e) { - logger.Error(string.Format("Error while moving {0} to {1}: {2}", configFilePath, configFilePathBak, ex.ToString())); + logger.Error($"Error while moving {configFilePath} to {configFilePathBak}\n{e}"); } - } // replace the actual config file File.Delete(configFilePath); @@ -134,9 +119,9 @@ namespace Jackett.Common.Services { File.Move(configFilePathTmp, configFilePath); } - catch (IOException ex) + catch (IOException e) { - logger.Error(string.Format("Error while moving {0} to {1}: {2}", configFilePathTmp, configFilePath, ex.ToString())); + logger.Error($"Error while moving {configFilePathTmp} to {configFilePath}\n{e}"); } } } diff --git a/src/Jackett.Common/Services/IndexerManagerService.cs b/src/Jackett.Common/Services/IndexerManagerService.cs index 02820e602..ac493e3b2 100644 --- a/src/Jackett.Common/Services/IndexerManagerService.cs +++ b/src/Jackett.Common/Services/IndexerManagerService.cs @@ -97,7 +97,7 @@ namespace Jackett.Common.Services private void InitIndexers() { - logger.Info("Using HTTP Client: " + webClient.GetType().Name); + logger.Info($"Using HTTP Client: {webClient.GetType().Name}"); var allTypes = GetType().Assembly.GetTypes(); var allIndexerTypes = allTypes.Where(p => typeof(IIndexer).IsAssignableFrom(p)); @@ -106,7 +106,7 @@ namespace Jackett.Common.Services var indexerTypes = allNonMetaInstantiatableIndexerTypes.Where(p => p.Name != "CardigannIndexer"); var ixs = indexerTypes.Select(type => { - var constructorArgumentTypes = new Type[] { typeof(IIndexerConfigurationService), typeof(WebClient), typeof(Logger), typeof(IProtectionService) }; + var constructorArgumentTypes = new [] { typeof(IIndexerConfigurationService), typeof(WebClient), typeof(Logger), typeof(IProtectionService) }; var constructor = type.GetConstructor(constructorArgumentTypes); if (constructor != null) { @@ -117,10 +117,8 @@ namespace Jackett.Common.Services var indexer = (IIndexer)constructor.Invoke(arguments); return indexer; } - else - { - logger.Error("Cannot instantiate " + type.Name); - } + + logger.Error($"Cannot instantiate {type.Name}"); return null; }); @@ -139,7 +137,7 @@ namespace Jackett.Common.Services var deserializer = new DeserializerBuilder() .WithNamingConvention(CamelCaseNamingConvention.Instance) -// .IgnoreUnmatchedProperties() + //.IgnoreUnmatchedProperties() .Build(); try @@ -152,13 +150,13 @@ namespace Jackett.Common.Services logger.Debug("Loading Cardigann definition " + file.FullName); try { - var DefinitionString = File.ReadAllText(file.FullName); - var definition = deserializer.Deserialize(DefinitionString); + var definitionString = File.ReadAllText(file.FullName); + var definition = deserializer.Deserialize(definitionString); return definition; } - catch (Exception ex) + catch (Exception e) { - logger.Error(ex, "Error while parsing Cardigann definition " + file.FullName + ": " + ex.Message); + logger.Error($"Error while parsing Cardigann definition {file.FullName}\n{e}"); return null; } }).Where(definition => definition != null); @@ -174,9 +172,9 @@ namespace Jackett.Common.Services configService.Load(indexer); return indexer; } - catch (Exception ex) + catch (Exception e) { - logger.Error(ex, "Error while creating Cardigann instance from Definition: " + ex.Message); + logger.Error($"Error while creating Cardigann instance from Definition: {e}"); return null; } }).Where(cardigannIndexer => cardigannIndexer != null).ToList(); // Explicit conversion to list to avoid repeated resource loading @@ -185,7 +183,7 @@ namespace Jackett.Common.Services { if (indexers.ContainsKey(indexer.Id)) { - logger.Debug(string.Format("Ignoring definition ID={0}: Indexer already exists", indexer.Id)); + logger.Debug($"Ignoring definition ID={indexer.Id}: Indexer already exists"); continue; } @@ -193,17 +191,17 @@ namespace Jackett.Common.Services } logger.Info("Cardigann definitions loaded: " + string.Join(", ", indexers.Keys)); } - catch (Exception ex) + catch (Exception e) { - logger.Error(ex, "Error while loading Cardigann definitions: " + ex.Message); + logger.Error($"Error while loading Cardigann definitions: {e}"); } } public void InitAggregateIndexer() { var omdbApiKey = serverConfig.OmdbApiKey; - IFallbackStrategyProvider fallbackStrategyProvider = null; - IResultFilterProvider resultFilterProvider = null; + IFallbackStrategyProvider fallbackStrategyProvider; + IResultFilterProvider resultFilterProvider; if (!string.IsNullOrWhiteSpace(omdbApiKey)) { var imdbResolver = new OmdbResolver(webClient, omdbApiKey, serverConfig.OmdbApiUrl); @@ -231,8 +229,8 @@ namespace Jackett.Common.Services if (renamedIndexers.ContainsKey(name)) { realName = renamedIndexers[name]; - logger.Warn($"Indexer {name} has been renamed to {realName}. Please, update the URL of the feeds. " + - "This may stop working in the future."); + logger.Warn($@"Indexer {name} has been renamed to {realName}. Please, update the URL of the feeds. + This may stop working in the future."); } if (indexers.ContainsKey(realName)) @@ -241,23 +239,20 @@ namespace Jackett.Common.Services if (realName == "all") return aggregateIndexer; - logger.Error("Request for unknown indexer: " + realName); - throw new Exception("Unknown indexer: " + realName); + logger.Error($"Request for unknown indexer: {realName}"); + throw new Exception($"Unknown indexer: {realName}"); } public IWebIndexer GetWebIndexer(string name) { if (indexers.ContainsKey(name)) - { return indexers[name] as IWebIndexer; - } - else if (name == "all") - { - return aggregateIndexer as IWebIndexer; - } - logger.Error("Request for unknown indexer: " + name); - throw new Exception("Unknown indexer: " + name); + if (name == "all") + return aggregateIndexer; + + logger.Error($"Request for unknown indexer: {name}"); + throw new Exception($"Unknown indexer: {name}"); } public IEnumerable GetAllIndexers() => indexers.Values.OrderBy(_ => _.DisplayName); @@ -272,8 +267,8 @@ namespace Jackett.Common.Services IsTest = true }; var result = await indexer.ResultsForQuery(browseQuery); - logger.Info(string.Format("Found {0} releases from {1}", result.Releases.Count(), indexer.DisplayName)); - if (result.Releases.Count() == 0) + logger.Info($"Found {result.Releases.Count()} releases from {indexer.DisplayName}"); + if (!result.Releases.Any()) throw new Exception("Found no results while trying to browse this tracker"); cacheService.CacheRssResults(indexer, result.Releases); } diff --git a/src/Jackett.Common/Services/UpdateService.cs b/src/Jackett.Common/Services/UpdateService.cs index 01cb46fcd..7e33816af 100644 --- a/src/Jackett.Common/Services/UpdateService.cs +++ b/src/Jackett.Common/Services/UpdateService.cs @@ -79,7 +79,7 @@ namespace Jackett.Common.Services private async Task CheckForUpdates() { - logger.Info("Checking for updates... Jackett variant: " + variant); + logger.Info($"Checking for updates... Jackett variant: {variant}"); if (serverConfig.RuntimeSettings.NoUpdates) { @@ -108,9 +108,7 @@ namespace Jackett.Common.Services var trayIsRunning = false; if (isWindows) - { trayIsRunning = Process.GetProcessesByName("JackettTray").Length > 0; - } try { @@ -122,16 +120,12 @@ namespace Jackett.Common.Services }); if (response.Status != System.Net.HttpStatusCode.OK) - { - logger.Error("Failed to get the release list: " + response.Status); - } + logger.Error($"Failed to get the release list: {response.Status}"); var releases = JsonConvert.DeserializeObject>(response.ContentString); if (!serverConfig.UpdatePrerelease) - { releases = releases.Where(r => !r.Prerelease).ToList(); - } if (releases.Count > 0) { @@ -147,31 +141,25 @@ namespace Jackett.Common.Services var installDir = Path.GetDirectoryName(ExePath()); var updaterPath = GetUpdaterPath(tempDir); if (updaterPath != null) - { StartUpdate(updaterPath, installDir, isWindows, serverConfig.RuntimeSettings.NoRestart, trayIsRunning); - } } catch (Exception e) { - logger.Error(e, "Error performing update."); + logger.Error($"Error performing update.\n{e}"); } } else - { logger.Info($"Jackett is already updated. Current version: {currentVersion}"); - } } } catch (Exception e) { - logger.Error(e, "Error checking for updates."); + logger.Error($"Error checking for updates.\n{e}"); } finally { if (!isWindows) - { System.Net.ServicePointManager.ServerCertificateValidationCallback -= AcceptCert; - } } } @@ -203,7 +191,7 @@ namespace Jackett.Common.Services if (!Directory.Exists(tempDir)) { - logger.Error("Temp dir doesn't exist: " + tempDir); + logger.Error($"Temp dir doesn't exist: {tempDir}"); return; } @@ -211,7 +199,6 @@ namespace Jackett.Common.Services { var d = new DirectoryInfo(tempDir); foreach (var dir in d.GetDirectories("JackettUpdate-*")) - { try { logger.Info("Deleting JackettUpdate temp files from " + dir.FullName); @@ -219,15 +206,12 @@ namespace Jackett.Common.Services } catch (Exception e) { - logger.Error("Error while deleting temp files from " + dir.FullName); - logger.Error(e); + logger.Error($"Error while deleting temp files from: {dir.FullName}\n{e}"); } - } } catch (Exception e) { - logger.Error("Unexpected error while deleting temp files from " + tempDir); - logger.Error(e); + logger.Error($"Unexpected error while deleting temp files from: {tempDir}\n{e}"); } } @@ -261,16 +245,12 @@ namespace Jackett.Common.Services var data = await client.GetResultAsync(SetDownloadHeaders(new WebRequest() { Url = url, EmulateBrowser = true, Type = RequestType.GET })); while (data.IsRedirect) - { data = await client.GetResultAsync(new WebRequest() { Url = data.RedirectingTo, EmulateBrowser = true, Type = RequestType.GET }); - } var tempDir = Path.Combine(Path.GetTempPath(), "JackettUpdate-" + version + "-" + DateTime.Now.Ticks); if (Directory.Exists(tempDir)) - { Directory.Delete(tempDir, true); - } Directory.CreateDirectory(tempDir); @@ -338,9 +318,7 @@ namespace Jackett.Common.Services var appType = "Console"; if (isWindows && windowsService.ServiceExists() && windowsService.ServiceRunning()) - { appType = "WindowsService"; - } var exe = Path.GetFileName(ExePath()); var args = string.Join(" ", Environment.GetCommandLineArgs().Skip(1).Select(a => a.Contains(" ") ? "\"" + a + "\"" : a)).Replace("\"", "\\\""); @@ -373,19 +351,14 @@ namespace Jackett.Common.Services } catch (Exception e) { - logger.Error("Unexpected error while retriving the PID"); - logger.Error(e); + logger.Error($"Unexpected error while retriving the PID.\n{e}"); } if (noRestart) - { startInfo.Arguments += " --NoRestart"; - } if (trayIsRunning && appType == "Console") - { startInfo.Arguments += " --StartTray"; - } // create .lock file to detect errors in the update process var lockFilePath = Path.Combine(installLocation, ".lock"); diff --git a/src/Jackett.Server/Controllers/BlackholeController.cs b/src/Jackett.Server/Controllers/BlackholeController.cs index 8b07b3432..ab0c15b55 100644 --- a/src/Jackett.Server/Controllers/BlackholeController.cs +++ b/src/Jackett.Server/Controllers/BlackholeController.cs @@ -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); diff --git a/src/Jackett.Server/Controllers/DownloadController.cs b/src/Jackett.Server/Controllers/DownloadController.cs index 3422eb62d..f90fe4dad 100644 --- a/src/Jackett.Server/Controllers/DownloadController.cs +++ b/src/Jackett.Server/Controllers/DownloadController.cs @@ -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(); } } diff --git a/src/Jackett.Server/Controllers/ResultsController.cs b/src/Jackett.Server/Controllers/ResultsController.cs index fa54306d1..0b018e1be 100644 --- a/src/Jackett.Server/Controllers/ResultsController.cs +++ b/src/Jackett.Server/Controllers/ResultsController.cs @@ -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()); } } diff --git a/src/Jackett.Server/Middleware/CustomExceptionHandler.cs b/src/Jackett.Server/Middleware/CustomExceptionHandler.cs index 2c146b0d0..37cdb21f5 100644 --- a/src/Jackett.Server/Middleware/CustomExceptionHandler.cs +++ b/src/Jackett.Server/Middleware/CustomExceptionHandler.cs @@ -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); diff --git a/src/Jackett.Server/Program.cs b/src/Jackett.Server/Program.cs index 4e44e7282..dceaa2855 100644 --- a/src/Jackett.Server/Program.cs +++ b/src/Jackett.Server/Program.cs @@ -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(); } diff --git a/src/Jackett.Server/Services/ServerService.cs b/src/Jackett.Server/Services/ServerService.cs index 2e772e604..8095e4bb0 100644 --- a/src/Jackett.Server/Services/ServerService.cs +++ b/src/Jackett.Server/Services/ServerService.cs @@ -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.
\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:
\n"; - notice += logSpacer + "
" + CommandRoot + "

\n"; + notice += logSpacer + "
" + commandRoot + "

\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 + "):
\n"; - notice += logSpacer + "
" + CommandUser + "
"; + notice += logSpacer + "
" + commandUser + "
"; 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; diff --git a/src/Jackett.Updater/Program.cs b/src/Jackett.Updater/Program.cs index 735823f44..43b4811ee 100644 --- a/src/Jackett.Updater/Program.cs +++ b/src/Jackett.Updater/Program.cs @@ -74,7 +74,7 @@ namespace Jackett.Updater } catch (Exception e) { - logger.Error(e, "Exception applying update!"); + logger.Error($"Exception applying update!\n{e}"); } } @@ -111,27 +111,24 @@ namespace Jackett.Updater } catch (Exception e) { - logger.Error(e, "Error while sending SIGTERM to " + pid.ToString()); + logger.Error($"Error while sending SIGTERM to {pid}\n{e}"); } if (!exited) - logger.Info("Process " + pid.ToString() + " didn't exit within 2 seconds after a SIGTERM"); + logger.Info($"Process {pid} didn't exit within 2 seconds after a SIGTERM"); } if (!exited) - { proc.Kill(); // send SIGKILL - } exited = proc.WaitForExit(5000); if (!exited) - logger.Info("Process " + pid.ToString() + " didn't exit within 5 seconds after a SIGKILL"); + logger.Info($"Process {pid} didn't exit within 5 seconds after a SIGKILL"); } catch (ArgumentException) { - logger.Info("Process " + pid.ToString() + " is already dead"); + logger.Info($"Process {pid} is already dead"); } catch (Exception e) { - logger.Info("Error killing process " + pid.ToString()); - logger.Info(e); + logger.Error($"Error killing process {pid}\n{e}"); } } } @@ -140,9 +137,7 @@ namespace Jackett.Updater { var updateLocation = GetUpdateLocation(); if (!(updateLocation.EndsWith("\\") || updateLocation.EndsWith("/"))) - { updateLocation += Path.DirectorySeparatorChar; - } var pids = new int[] { }; if (options.KillPids != null) @@ -157,18 +152,17 @@ namespace Jackett.Updater if (isWindows) { if (trayProcesses.Length > 0) - { foreach (var proc in trayProcesses) - { try { - logger.Info("Killing tray process " + proc.Id); + logger.Info($"Killing tray process {proc.Id}"); proc.Kill(); trayRunning = true; } - catch { } - } - } + catch (Exception e) + { + logger.Error(e); + } // on unix we don't have to wait (we can overwrite files which are in use) // On unix we kill the PIDs after the update so e.g. systemd can automatically restart the process @@ -201,9 +195,7 @@ namespace Jackett.Updater logger.Info("Deleted " + fileForDelete); } else - { logger.Info("File for deleting not found: " + fileForDelete); - } } catch (Exception e) { @@ -214,7 +206,7 @@ namespace Jackett.Updater logger.Info("Finding files in: " + updateLocation); var files = Directory.GetFiles(updateLocation, "*.*", SearchOption.AllDirectories).OrderBy(x => x).ToList(); - logger.Info($"{files.Count()} update files found"); + logger.Info($"{files.Count} update files found"); try { @@ -223,22 +215,17 @@ namespace Jackett.Updater var fileName = Path.GetFileName(file).ToLowerInvariant(); if (fileName.EndsWith(".zip") || fileName.EndsWith(".tar") || fileName.EndsWith(".gz")) - { continue; - } var fileCopySuccess = CopyUpdateFile(options.Path, file, updateLocation, false); - if (!fileCopySuccess) - { - //Perform second attempt, this time removing the target file first + if (!fileCopySuccess) //Perform second attempt, this time removing the target file first CopyUpdateFile(options.Path, file, updateLocation, true); - } } } - catch (Exception ex) + catch (Exception e) { - logger.Error(ex); + logger.Error(e); } logger.Info("File copying complete"); @@ -622,14 +609,7 @@ namespace Jackett.Updater private string GetJackettConsolePath(string directoryPath) { var variants = new Variants(); - if (variants.IsNonWindowsDotNetCoreVariant(variant)) - { - return Path.Combine(directoryPath, "jackett"); - } - else - { - return Path.Combine(directoryPath, "JackettConsole.exe"); - } + return Path.Combine(directoryPath, variants.IsNonWindowsDotNetCoreVariant(variant) ? "jackett" : "JackettConsole.exe"); } private static void UnhandledExceptionTrapper(object sender, UnhandledExceptionEventArgs e)