Make the config saving process more robust (#670)

This commit is contained in:
kaso17 2016-11-10 09:06:35 +01:00 committed by GitHub
parent 7cfdaf4b41
commit 037d907028
1 changed files with 51 additions and 1 deletions

View File

@ -148,10 +148,60 @@ namespace Jackett.Services
public void SaveConfig(IIndexer indexer, JToken obj) public void SaveConfig(IIndexer indexer, JToken obj)
{ {
var uID = Guid.NewGuid().ToString("N");
var configFilePath = GetIndexerConfigFilePath(indexer); var configFilePath = GetIndexerConfigFilePath(indexer);
var configFilePathBak = configFilePath + ".bak";
var configFilePathTmp = configFilePath + "." + uID + ".tmp";
var content = obj.ToString();
logger.Debug(string.Format("Saving new config file: {0}", configFilePathTmp));
if (string.IsNullOrWhiteSpace(content))
{
throw new Exception(string.Format("New config content for {0} is empty, please report this bug.", indexer.ID));
}
if (content.Contains("NULL"))
{
throw new Exception(string.Format("New config content for {0} contains NULL, please report this bug. Content: {1}", indexer.ID, content));
}
// make sure the config directory exists
if (!Directory.Exists(configService.GetIndexerConfigDir())) if (!Directory.Exists(configService.GetIndexerConfigDir()))
Directory.CreateDirectory(configService.GetIndexerConfigDir()); Directory.CreateDirectory(configService.GetIndexerConfigDir());
File.WriteAllText(configFilePath, obj.ToString());
// create new temporary config file
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));
}
// create backup file
File.Delete(configFilePathBak);
if (File.Exists(configFilePath))
{
try
{
File.Move(configFilePath, configFilePathBak);
}
catch (IOException ex)
{
logger.Error(string.Format("Error while moving {0} to {1}: {2}", configFilePath, configFilePathBak, ex.ToString()));
}
}
// replace the actual config file
File.Delete(configFilePath);
try
{
File.Move(configFilePathTmp, configFilePath);
}
catch (IOException ex)
{
logger.Error(string.Format("Error while moving {0} to {1}: {2}", configFilePath, configFilePathBak, ex.ToString()));
}
} }
} }
} }