using System; using System.Linq; using NLog; using NzbDrone.Common.Cache; using NzbDrone.Core.Lifecycle; using NzbDrone.Core.Messaging.Commands; using NzbDrone.Core.Messaging.Events; using NzbDrone.Core.Parser; using System.Collections.Generic; namespace NzbDrone.Core.DataAugmentation.Scene { public interface ISceneMappingService { string GetSceneName(int tvdbId); Nullable GetTvDbId(string cleanName); List FindByTvdbid(int tvdbId); } public class SceneMappingService : ISceneMappingService, IHandleAsync, IExecute { private readonly ISceneMappingRepository _repository; private readonly ISceneMappingProxy _sceneMappingProxy; private readonly Logger _logger; private readonly ICached _getSceneNameCache; private readonly ICached _gettvdbIdCache; private readonly ICached> _findbytvdbIdCache; public SceneMappingService(ISceneMappingRepository repository, ISceneMappingProxy sceneMappingProxy, ICacheManager cacheManager, Logger logger) { _repository = repository; _sceneMappingProxy = sceneMappingProxy; _getSceneNameCache = cacheManager.GetCache(GetType(), "scene_name"); _gettvdbIdCache = cacheManager.GetCache(GetType(), "tvdb_id"); _findbytvdbIdCache = cacheManager.GetCache>(GetType(), "find_tvdb_id"); _logger = logger; } public string GetSceneName(int tvdbId) { var mapping = _getSceneNameCache.Find(tvdbId.ToString()); if (mapping == null) return null; return mapping.SearchTerm; } public Nullable GetTvDbId(string cleanName) { var mapping = _gettvdbIdCache.Find(cleanName.CleanSeriesTitle()); if (mapping == null) return null; return mapping.TvdbId; } public List FindByTvdbid(int tvdbId) { return _findbytvdbIdCache.Find(tvdbId.ToString()); } 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.Title.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(); _findbytvdbIdCache.Clear(); foreach (var sceneMapping in mappings) { _getSceneNameCache.Set(sceneMapping.TvdbId.ToString(), sceneMapping); _gettvdbIdCache.Set(sceneMapping.ParseTerm.CleanSeriesTitle(), sceneMapping); } foreach (var sceneMapping in mappings.GroupBy(x => x.TvdbId)) { _findbytvdbIdCache.Set(sceneMapping.Key.ToString(), sceneMapping.ToList()); } } public void HandleAsync(ApplicationStartedEvent message) { UpdateMappings(); } public void Execute(UpdateSceneMappingCommand message) { UpdateMappings(); } } }