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

@@ -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) catch (Exception e)
{ {
logger.Error(e, "Error reading config file " + fullPath); logger.Error($"Error reading config file {fullPath}\n{e}");
return default; return default;
} }
} }
@@ -162,7 +162,7 @@ namespace Jackett.Common.Services
} }
catch (Exception e) catch (Exception e)
{ {
logger.Error(e, "Error writing config file " + fullPath); logger.Error($"Error writing config file {fullPath}\n{e}");
} }
} }

View File

@@ -37,46 +37,39 @@ namespace Jackett.Common.Services
File.Delete(configFilePath); File.Delete(configFilePath);
var configFilePathBak = configFilePath + ".bak"; var configFilePathBak = configFilePath + ".bak";
if (File.Exists(configFilePathBak)) if (File.Exists(configFilePathBak))
{
File.Delete(configFilePathBak); File.Delete(configFilePathBak);
} }
}
public void Load(IIndexer indexer) public void Load(IIndexer indexer)
{ {
var configFilePath = GetIndexerConfigFilePath(indexer.Id); var configFilePath = GetIndexerConfigFilePath(indexer.Id);
if (File.Exists(configFilePath)) if (!File.Exists(configFilePath))
{ return;
try try
{ {
var fileStr = File.ReadAllText(configFilePath); var fileStr = File.ReadAllText(configFilePath);
var jsonString = JToken.Parse(fileStr); var jsonString = JToken.Parse(fileStr);
indexer.LoadFromSavedConfiguration(jsonString); indexer.LoadFromSavedConfiguration(jsonString);
} }
catch (Exception ex) catch (Exception e)
{ {
logger.Error(ex, "Failed loading configuration for {0}, trying backup", indexer.DisplayName); logger.Error($"Failed loading configuration for {indexer.DisplayName}, trying backup\n{e}");
var configFilePathBak = configFilePath + ".bak"; var configFilePathBak = configFilePath + ".bak";
if (File.Exists(configFilePathBak)) if (File.Exists(configFilePathBak))
{
try try
{ {
var fileStrBak = File.ReadAllText(configFilePathBak); var fileStrBak = File.ReadAllText(configFilePathBak);
var jsonStringBak = JToken.Parse(fileStrBak); var jsonStringBak = JToken.Parse(fileStrBak);
indexer.LoadFromSavedConfiguration(jsonStringBak); indexer.LoadFromSavedConfiguration(jsonStringBak);
logger.Info("Successfully loaded backup config for {0}", indexer.DisplayName); logger.Info($"Successfully loaded backup config for {indexer.DisplayName}");
indexer.SaveConfig(); indexer.SaveConfig();
} }
catch (Exception exbak) catch (Exception e2)
{ {
logger.Error(exbak, "Failed loading backup configuration for {0}, you must reconfigure this indexer", indexer.DisplayName); logger.Error($"Failed loading backup configuration for {indexer.DisplayName}, you must reconfigure this indexer\n{e2}");
}
} }
else else
{ logger.Error($"Failed loading backup configuration for {indexer.DisplayName} (no backup available), you must reconfigure this indexer\n{e}");
logger.Error(ex, "Failed loading backup configuration for {0} (no backup available), you must reconfigure this indexer", indexer.DisplayName);
}
}
} }
} }
@@ -84,23 +77,19 @@ namespace Jackett.Common.Services
{ {
lock (configWriteLock) lock (configWriteLock)
{ {
var uID = Guid.NewGuid().ToString("N"); var uId = Guid.NewGuid().ToString("N");
var configFilePath = GetIndexerConfigFilePath(indexer.Id); var configFilePath = GetIndexerConfigFilePath(indexer.Id);
var configFilePathBak = configFilePath + ".bak"; var configFilePathBak = configFilePath + ".bak";
var configFilePathTmp = configFilePath + "." + uID + ".tmp"; var configFilePathTmp = configFilePath + "." + uId + ".tmp";
var content = obj.ToString(); 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)) if (string.IsNullOrWhiteSpace(content))
{ throw new Exception($"New config content for {indexer.Id} is empty, please report this bug.");
throw new Exception(string.Format("New config content for {0} is empty, please report this bug.", indexer.Id));
}
if (content.Contains("\x00")) if (content.Contains("\x00"))
{ throw new Exception($"New config content for {indexer.Id} contains 0x00, please report this bug. Content: {content}");
throw new Exception(string.Format("New config content for {0} contains 0x00, please report this bug. Content: {1}", indexer.Id, content));
}
// make sure the config directory exists // make sure the config directory exists
if (!Directory.Exists(configService.GetIndexerConfigDir())) if (!Directory.Exists(configService.GetIndexerConfigDir()))
@@ -110,22 +99,18 @@ namespace Jackett.Common.Services
File.WriteAllText(configFilePathTmp, content); File.WriteAllText(configFilePathTmp, content);
var fileInfo = new FileInfo(configFilePathTmp); var fileInfo = new FileInfo(configFilePathTmp);
if (fileInfo.Length == 0) if (fileInfo.Length == 0)
{ throw new Exception($"New config file {configFilePathTmp} is empty, please report this bug.");
throw new Exception(string.Format("New config file {0} is empty, please report this bug.", configFilePathTmp));
}
// create backup file // create backup file
File.Delete(configFilePathBak); File.Delete(configFilePathBak);
if (File.Exists(configFilePath)) if (File.Exists(configFilePath))
{
try try
{ {
File.Move(configFilePath, configFilePathBak); 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 // replace the actual config file
@@ -134,9 +119,9 @@ namespace Jackett.Common.Services
{ {
File.Move(configFilePathTmp, configFilePath); 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}");
} }
} }
} }

View File

@@ -97,7 +97,7 @@ namespace Jackett.Common.Services
private void InitIndexers() 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 allTypes = GetType().Assembly.GetTypes();
var allIndexerTypes = allTypes.Where(p => typeof(IIndexer).IsAssignableFrom(p)); 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 indexerTypes = allNonMetaInstantiatableIndexerTypes.Where(p => p.Name != "CardigannIndexer");
var ixs = indexerTypes.Select(type => 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); var constructor = type.GetConstructor(constructorArgumentTypes);
if (constructor != null) if (constructor != null)
{ {
@@ -117,10 +117,8 @@ namespace Jackett.Common.Services
var indexer = (IIndexer)constructor.Invoke(arguments); var indexer = (IIndexer)constructor.Invoke(arguments);
return indexer; return indexer;
} }
else
{ logger.Error($"Cannot instantiate {type.Name}");
logger.Error("Cannot instantiate " + type.Name);
}
return null; return null;
}); });
@@ -139,7 +137,7 @@ namespace Jackett.Common.Services
var deserializer = new DeserializerBuilder() var deserializer = new DeserializerBuilder()
.WithNamingConvention(CamelCaseNamingConvention.Instance) .WithNamingConvention(CamelCaseNamingConvention.Instance)
// .IgnoreUnmatchedProperties() //.IgnoreUnmatchedProperties()
.Build(); .Build();
try try
@@ -152,13 +150,13 @@ namespace Jackett.Common.Services
logger.Debug("Loading Cardigann definition " + file.FullName); logger.Debug("Loading Cardigann definition " + file.FullName);
try try
{ {
var DefinitionString = File.ReadAllText(file.FullName); var definitionString = File.ReadAllText(file.FullName);
var definition = deserializer.Deserialize<IndexerDefinition>(DefinitionString); var definition = deserializer.Deserialize<IndexerDefinition>(definitionString);
return definition; 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; return null;
} }
}).Where(definition => definition != null); }).Where(definition => definition != null);
@@ -174,9 +172,9 @@ namespace Jackett.Common.Services
configService.Load(indexer); configService.Load(indexer);
return 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; return null;
} }
}).Where(cardigannIndexer => cardigannIndexer != null).ToList(); // Explicit conversion to list to avoid repeated resource loading }).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)) 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; continue;
} }
@@ -193,17 +191,17 @@ namespace Jackett.Common.Services
} }
logger.Info("Cardigann definitions loaded: " + string.Join(", ", indexers.Keys)); 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() public void InitAggregateIndexer()
{ {
var omdbApiKey = serverConfig.OmdbApiKey; var omdbApiKey = serverConfig.OmdbApiKey;
IFallbackStrategyProvider fallbackStrategyProvider = null; IFallbackStrategyProvider fallbackStrategyProvider;
IResultFilterProvider resultFilterProvider = null; IResultFilterProvider resultFilterProvider;
if (!string.IsNullOrWhiteSpace(omdbApiKey)) if (!string.IsNullOrWhiteSpace(omdbApiKey))
{ {
var imdbResolver = new OmdbResolver(webClient, omdbApiKey, serverConfig.OmdbApiUrl); var imdbResolver = new OmdbResolver(webClient, omdbApiKey, serverConfig.OmdbApiUrl);
@@ -231,8 +229,8 @@ namespace Jackett.Common.Services
if (renamedIndexers.ContainsKey(name)) if (renamedIndexers.ContainsKey(name))
{ {
realName = renamedIndexers[name]; realName = renamedIndexers[name];
logger.Warn($"Indexer {name} has been renamed to {realName}. Please, update the URL of the feeds. " + logger.Warn($@"Indexer {name} has been renamed to {realName}. Please, update the URL of the feeds.
"This may stop working in the future."); This may stop working in the future.");
} }
if (indexers.ContainsKey(realName)) if (indexers.ContainsKey(realName))
@@ -241,23 +239,20 @@ namespace Jackett.Common.Services
if (realName == "all") if (realName == "all")
return aggregateIndexer; return aggregateIndexer;
logger.Error("Request for unknown indexer: " + realName); logger.Error($"Request for unknown indexer: {realName}");
throw new Exception("Unknown indexer: " + realName); throw new Exception($"Unknown indexer: {realName}");
} }
public IWebIndexer GetWebIndexer(string name) public IWebIndexer GetWebIndexer(string name)
{ {
if (indexers.ContainsKey(name)) if (indexers.ContainsKey(name))
{
return indexers[name] as IWebIndexer; return indexers[name] as IWebIndexer;
}
else if (name == "all")
{
return aggregateIndexer as IWebIndexer;
}
logger.Error("Request for unknown indexer: " + name); if (name == "all")
throw new Exception("Unknown indexer: " + name); return aggregateIndexer;
logger.Error($"Request for unknown indexer: {name}");
throw new Exception($"Unknown indexer: {name}");
} }
public IEnumerable<IIndexer> GetAllIndexers() => indexers.Values.OrderBy(_ => _.DisplayName); public IEnumerable<IIndexer> GetAllIndexers() => indexers.Values.OrderBy(_ => _.DisplayName);
@@ -272,8 +267,8 @@ namespace Jackett.Common.Services
IsTest = true IsTest = true
}; };
var result = await indexer.ResultsForQuery(browseQuery); var result = await indexer.ResultsForQuery(browseQuery);
logger.Info(string.Format("Found {0} releases from {1}", result.Releases.Count(), indexer.DisplayName)); logger.Info($"Found {result.Releases.Count()} releases from {indexer.DisplayName}");
if (result.Releases.Count() == 0) if (!result.Releases.Any())
throw new Exception("Found no results while trying to browse this tracker"); throw new Exception("Found no results while trying to browse this tracker");
cacheService.CacheRssResults(indexer, result.Releases); cacheService.CacheRssResults(indexer, result.Releases);
} }

View File

@@ -79,7 +79,7 @@ namespace Jackett.Common.Services
private async Task CheckForUpdates() private async Task CheckForUpdates()
{ {
logger.Info("Checking for updates... Jackett variant: " + variant); logger.Info($"Checking for updates... Jackett variant: {variant}");
if (serverConfig.RuntimeSettings.NoUpdates) if (serverConfig.RuntimeSettings.NoUpdates)
{ {
@@ -108,9 +108,7 @@ namespace Jackett.Common.Services
var trayIsRunning = false; var trayIsRunning = false;
if (isWindows) if (isWindows)
{
trayIsRunning = Process.GetProcessesByName("JackettTray").Length > 0; trayIsRunning = Process.GetProcessesByName("JackettTray").Length > 0;
}
try try
{ {
@@ -122,16 +120,12 @@ namespace Jackett.Common.Services
}); });
if (response.Status != System.Net.HttpStatusCode.OK) 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<List<Release>>(response.ContentString); var releases = JsonConvert.DeserializeObject<List<Release>>(response.ContentString);
if (!serverConfig.UpdatePrerelease) if (!serverConfig.UpdatePrerelease)
{
releases = releases.Where(r => !r.Prerelease).ToList(); releases = releases.Where(r => !r.Prerelease).ToList();
}
if (releases.Count > 0) if (releases.Count > 0)
{ {
@@ -147,33 +141,27 @@ namespace Jackett.Common.Services
var installDir = Path.GetDirectoryName(ExePath()); var installDir = Path.GetDirectoryName(ExePath());
var updaterPath = GetUpdaterPath(tempDir); var updaterPath = GetUpdaterPath(tempDir);
if (updaterPath != null) if (updaterPath != null)
{
StartUpdate(updaterPath, installDir, isWindows, serverConfig.RuntimeSettings.NoRestart, trayIsRunning); StartUpdate(updaterPath, installDir, isWindows, serverConfig.RuntimeSettings.NoRestart, trayIsRunning);
} }
}
catch (Exception e) catch (Exception e)
{ {
logger.Error(e, "Error performing update."); logger.Error($"Error performing update.\n{e}");
} }
} }
else else
{
logger.Info($"Jackett is already updated. Current version: {currentVersion}"); logger.Info($"Jackett is already updated. Current version: {currentVersion}");
} }
} }
}
catch (Exception e) catch (Exception e)
{ {
logger.Error(e, "Error checking for updates."); logger.Error($"Error checking for updates.\n{e}");
} }
finally finally
{ {
if (!isWindows) if (!isWindows)
{
System.Net.ServicePointManager.ServerCertificateValidationCallback -= AcceptCert; System.Net.ServicePointManager.ServerCertificateValidationCallback -= AcceptCert;
} }
} }
}
private string GetUpdaterPath(string tempDirectory) => private string GetUpdaterPath(string tempDirectory) =>
variant == Variants.JackettVariant.CoreMacOs || variant == Variants.JackettVariant.CoreLinuxAmdx64 || variant == Variants.JackettVariant.CoreMacOs || variant == Variants.JackettVariant.CoreLinuxAmdx64 ||
@@ -203,7 +191,7 @@ namespace Jackett.Common.Services
if (!Directory.Exists(tempDir)) if (!Directory.Exists(tempDir))
{ {
logger.Error("Temp dir doesn't exist: " + tempDir); logger.Error($"Temp dir doesn't exist: {tempDir}");
return; return;
} }
@@ -211,7 +199,6 @@ namespace Jackett.Common.Services
{ {
var d = new DirectoryInfo(tempDir); var d = new DirectoryInfo(tempDir);
foreach (var dir in d.GetDirectories("JackettUpdate-*")) foreach (var dir in d.GetDirectories("JackettUpdate-*"))
{
try try
{ {
logger.Info("Deleting JackettUpdate temp files from " + dir.FullName); logger.Info("Deleting JackettUpdate temp files from " + dir.FullName);
@@ -219,15 +206,12 @@ namespace Jackett.Common.Services
} }
catch (Exception e) catch (Exception e)
{ {
logger.Error("Error while deleting temp files from " + dir.FullName); logger.Error($"Error while deleting temp files from: {dir.FullName}\n{e}");
logger.Error(e);
}
} }
} }
catch (Exception e) catch (Exception e)
{ {
logger.Error("Unexpected error while deleting temp files from " + tempDir); logger.Error($"Unexpected error while deleting temp files from: {tempDir}\n{e}");
logger.Error(e);
} }
} }
@@ -261,16 +245,12 @@ namespace Jackett.Common.Services
var data = await client.GetResultAsync(SetDownloadHeaders(new WebRequest() { Url = url, EmulateBrowser = true, Type = RequestType.GET })); var data = await client.GetResultAsync(SetDownloadHeaders(new WebRequest() { Url = url, EmulateBrowser = true, Type = RequestType.GET }));
while (data.IsRedirect) while (data.IsRedirect)
{
data = await client.GetResultAsync(new WebRequest() { Url = data.RedirectingTo, EmulateBrowser = true, Type = RequestType.GET }); 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); var tempDir = Path.Combine(Path.GetTempPath(), "JackettUpdate-" + version + "-" + DateTime.Now.Ticks);
if (Directory.Exists(tempDir)) if (Directory.Exists(tempDir))
{
Directory.Delete(tempDir, true); Directory.Delete(tempDir, true);
}
Directory.CreateDirectory(tempDir); Directory.CreateDirectory(tempDir);
@@ -338,9 +318,7 @@ namespace Jackett.Common.Services
var appType = "Console"; var appType = "Console";
if (isWindows && windowsService.ServiceExists() && windowsService.ServiceRunning()) if (isWindows && windowsService.ServiceExists() && windowsService.ServiceRunning())
{
appType = "WindowsService"; appType = "WindowsService";
}
var exe = Path.GetFileName(ExePath()); var exe = Path.GetFileName(ExePath());
var args = string.Join(" ", Environment.GetCommandLineArgs().Skip(1).Select(a => a.Contains(" ") ? "\"" + a + "\"" : a)).Replace("\"", "\\\""); 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) catch (Exception e)
{ {
logger.Error("Unexpected error while retriving the PID"); logger.Error($"Unexpected error while retriving the PID.\n{e}");
logger.Error(e);
} }
if (noRestart) if (noRestart)
{
startInfo.Arguments += " --NoRestart"; startInfo.Arguments += " --NoRestart";
}
if (trayIsRunning && appType == "Console") if (trayIsRunning && appType == "Console")
{
startInfo.Arguments += " --StartTray"; startInfo.Arguments += " --StartTray";
}
// create .lock file to detect errors in the update process // create .lock file to detect errors in the update process
var lockFilePath = Path.Combine(installLocation, ".lock"); var lockFilePath = Path.Combine(installLocation, ".lock");

View File

@@ -43,7 +43,7 @@ namespace Jackett.Server.Controllers
var indexer = indexerService.GetWebIndexer(indexerID); var indexer = indexerService.GetWebIndexer(indexerID);
if (!indexer.IsConfigured) 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."); throw new Exception("This indexer is not configured.");
} }
@@ -79,7 +79,7 @@ namespace Jackett.Server.Controllers
if (!Directory.Exists(serverConfig.BlackholeDir)) 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); 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); System.IO.File.WriteAllBytes(Path.Combine(serverConfig.BlackholeDir, fileName), downloadBytes);
jsonReply["result"] = "success"; 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["result"] = "error";
jsonReply["error"] = ex.Message; jsonReply["error"] = e.Message;
} }
return Json(jsonReply); return Json(jsonReply);

View File

@@ -45,7 +45,7 @@ namespace Jackett.Server.Controllers
if (!indexer.IsConfigured) 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."); return Forbid("This indexer is not configured.");
} }
@@ -91,7 +91,7 @@ namespace Jackett.Server.Controllers
} }
catch (Exception e) catch (Exception e)
{ {
logger.Error(e, "Error downloading " + indexerID + " " + path); logger.Error($"Error downloading. indexer: {indexerID} path: {path}\n{e}");
return NotFound(); return NotFound();
} }
} }

View File

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

View File

@@ -25,44 +25,35 @@ namespace Jackett.Server.Middleware
{ {
await _next(httpContext); await _next(httpContext);
} }
catch (Exception ex) catch (Exception e)
{ {
try 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(); var json = new JObject();
if (e is ExceptionWithConfigData)
logger.Error(ex); json["config"] = ((ExceptionWithConfigData)e).ConfigData.ToJson(null, false);
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);
}
json["result"] = "error"; json["result"] = "error";
json["error"] = msg; json["error"] = msg;
json["stacktrace"] = ex.StackTrace; json["stacktrace"] = e.StackTrace;
if (ex.InnerException != null) if (e.InnerException != null)
{ json["innerstacktrace"] = e.InnerException.StackTrace;
json["innerstacktrace"] = ex.InnerException.StackTrace;
}
httpContext.Response.StatusCode = StatusCodes.Status500InternalServerError; httpContext.Response.StatusCode = StatusCodes.Status500InternalServerError;
httpContext.Response.ContentType = "application/json"; httpContext.Response.ContentType = "application/json";
await httpContext.Response.WriteAsync(json.ToString()); await httpContext.Response.WriteAsync(json.ToString());
return; 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); await _next(httpContext);

View File

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

View File

@@ -74,7 +74,7 @@ namespace Jackett.Updater
} }
catch (Exception e) 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) 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) 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) if (!exited)
{
proc.Kill(); // send SIGKILL proc.Kill(); // send SIGKILL
}
exited = proc.WaitForExit(5000); exited = proc.WaitForExit(5000);
if (!exited) 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) catch (ArgumentException)
{ {
logger.Info("Process " + pid.ToString() + " is already dead"); logger.Info($"Process {pid} is already dead");
} }
catch (Exception e) catch (Exception e)
{ {
logger.Info("Error killing process " + pid.ToString()); logger.Error($"Error killing process {pid}\n{e}");
logger.Info(e);
} }
} }
} }
@@ -140,9 +137,7 @@ namespace Jackett.Updater
{ {
var updateLocation = GetUpdateLocation(); var updateLocation = GetUpdateLocation();
if (!(updateLocation.EndsWith("\\") || updateLocation.EndsWith("/"))) if (!(updateLocation.EndsWith("\\") || updateLocation.EndsWith("/")))
{
updateLocation += Path.DirectorySeparatorChar; updateLocation += Path.DirectorySeparatorChar;
}
var pids = new int[] { }; var pids = new int[] { };
if (options.KillPids != null) if (options.KillPids != null)
@@ -157,17 +152,16 @@ namespace Jackett.Updater
if (isWindows) if (isWindows)
{ {
if (trayProcesses.Length > 0) if (trayProcesses.Length > 0)
{
foreach (var proc in trayProcesses) foreach (var proc in trayProcesses)
{
try try
{ {
logger.Info("Killing tray process " + proc.Id); logger.Info($"Killing tray process {proc.Id}");
proc.Kill(); proc.Kill();
trayRunning = true; 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 don't have to wait (we can overwrite files which are in use)
@@ -201,10 +195,8 @@ namespace Jackett.Updater
logger.Info("Deleted " + fileForDelete); logger.Info("Deleted " + fileForDelete);
} }
else else
{
logger.Info("File for deleting not found: " + fileForDelete); logger.Info("File for deleting not found: " + fileForDelete);
} }
}
catch (Exception e) catch (Exception e)
{ {
logger.Error(e); logger.Error(e);
@@ -214,7 +206,7 @@ namespace Jackett.Updater
logger.Info("Finding files in: " + updateLocation); logger.Info("Finding files in: " + updateLocation);
var files = Directory.GetFiles(updateLocation, "*.*", SearchOption.AllDirectories).OrderBy(x => x).ToList(); 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 try
{ {
@@ -223,22 +215,17 @@ namespace Jackett.Updater
var fileName = Path.GetFileName(file).ToLowerInvariant(); var fileName = Path.GetFileName(file).ToLowerInvariant();
if (fileName.EndsWith(".zip") || fileName.EndsWith(".tar") || fileName.EndsWith(".gz")) if (fileName.EndsWith(".zip") || fileName.EndsWith(".tar") || fileName.EndsWith(".gz"))
{
continue; continue;
}
var fileCopySuccess = CopyUpdateFile(options.Path, file, updateLocation, false); var fileCopySuccess = CopyUpdateFile(options.Path, file, updateLocation, false);
if (!fileCopySuccess) if (!fileCopySuccess) //Perform second attempt, this time removing the target file first
{
//Perform second attempt, this time removing the target file first
CopyUpdateFile(options.Path, file, updateLocation, true); CopyUpdateFile(options.Path, file, updateLocation, true);
} }
} }
} catch (Exception e)
catch (Exception ex)
{ {
logger.Error(ex); logger.Error(e);
} }
logger.Info("File copying complete"); logger.Info("File copying complete");
@@ -622,14 +609,7 @@ namespace Jackett.Updater
private string GetJackettConsolePath(string directoryPath) private string GetJackettConsolePath(string directoryPath)
{ {
var variants = new Variants(); var variants = new Variants();
if (variants.IsNonWindowsDotNetCoreVariant(variant)) return Path.Combine(directoryPath, variants.IsNonWindowsDotNetCoreVariant(variant) ? "jackett" : "JackettConsole.exe");
{
return Path.Combine(directoryPath, "jackett");
}
else
{
return Path.Combine(directoryPath, "JackettConsole.exe");
}
} }
private static void UnhandledExceptionTrapper(object sender, UnhandledExceptionEventArgs e) private static void UnhandledExceptionTrapper(object sender, UnhandledExceptionEventArgs e)