You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
Readarr/NzbDrone.Core/DataAugmentation/Scene/SceneMappingService.cs

118 lines
3.3 KiB

12 years ago
using System;
using System.Linq;
12 years ago
using NLog;
using NzbDrone.Common.Cache;
using NzbDrone.Common.Messaging;
12 years ago
using NzbDrone.Core.Lifecycle;
using NzbDrone.Core.Parser;
12 years ago
namespace NzbDrone.Core.DataAugmentation.Scene
12 years ago
{
public interface ISceneMappingService
{
string GetSceneName(int tvdbId, int seasonNumber = -1);
Nullable<int> GetTvDbId(string cleanName);
}
public class SceneMappingService : ISceneMappingService,
IHandleAsync<ApplicationStartedEvent>,
IExecute<UpdateSceneMappingCommand>
12 years ago
{
12 years ago
private readonly ISceneMappingRepository _repository;
private readonly ISceneMappingProxy _sceneMappingProxy;
private readonly Logger _logger;
private readonly ICached<SceneMapping> _getSceneNameCache;
private readonly ICached<SceneMapping> _gettvdbIdCache;
12 years ago
public SceneMappingService(ISceneMappingRepository repository, ISceneMappingProxy sceneMappingProxy, ICacheManger cacheManger, Logger logger)
12 years ago
{
_repository = repository;
_sceneMappingProxy = sceneMappingProxy;
_getSceneNameCache = cacheManger.GetCache<SceneMapping>(GetType(), "scene_name");
_gettvdbIdCache = cacheManger.GetCache<SceneMapping>(GetType(), "tvdb_id");
12 years ago
_logger = logger;
}
public string GetSceneName(int tvdbId, int seasonNumber = -1)
12 years ago
{
var mapping = _getSceneNameCache.Find(tvdbId.ToString());
12 years ago
if (mapping == null) return null;
12 years ago
return mapping.SearchTerm;
12 years ago
}
public Nullable<Int32> GetTvDbId(string cleanName)
12 years ago
{
var mapping = _gettvdbIdCache.Find(cleanName.CleanSeriesTitle());
12 years ago
if (mapping == null)
return null;
12 years ago
return mapping.TvdbId;
12 years ago
}
private void UpdateMappings()
{
_logger.Info("Updating Scene mapping");
try
{
var mappings = _sceneMappingProxy.Fetch();
if (mappings.Any())
{
_repository.Purge();
foreach (var sceneMapping in mappings)
{
sceneMapping.ParseTerm = sceneMapping.ParseTerm.CleanSeriesTitle();
}
_repository.InsertMany(mappings);
}
else
{
_logger.Warn("Received empty list of mapping. will not update.");
}
}
catch (Exception ex)
{
_logger.ErrorException("Failed to Update Scene Mappings:", ex);
}
RefreshCache();
}
private void RefreshCache()
{
var mappings = _repository.All();
_gettvdbIdCache.Clear();
_getSceneNameCache.Clear();
foreach (var sceneMapping in mappings)
{
_getSceneNameCache.Set(sceneMapping.TvdbId.ToString(), sceneMapping);
_gettvdbIdCache.Set(sceneMapping.ParseTerm.CleanSeriesTitle(), sceneMapping);
}
}
public void HandleAsync(ApplicationStartedEvent message)
{
UpdateMappings();
}
public void Execute(UpdateSceneMappingCommand message)
{
UpdateMappings();
}
12 years ago
}
}