jellyfin-server/MediaBrowser.Providers/Manager/MetadataService.cs

395 lines
16 KiB
C#
Raw Normal View History

2014-01-29 05:17:58 +00:00
using MediaBrowser.Common.Extensions;
2014-02-02 13:36:31 +00:00
using MediaBrowser.Common.IO;
2014-01-29 05:17:58 +00:00
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
2014-02-02 13:36:31 +00:00
using MediaBrowser.Model.Configuration;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace MediaBrowser.Providers.Manager
{
2014-01-31 19:55:21 +00:00
public abstract class MetadataService<TItemType, TIdType> : IMetadataService
2014-02-02 13:36:31 +00:00
where TItemType : IHasMetadata, new()
2014-01-31 19:55:21 +00:00
where TIdType : ItemId, new()
{
protected readonly IServerConfigurationManager ServerConfigurationManager;
protected readonly ILogger Logger;
protected readonly IProviderManager ProviderManager;
2014-02-02 13:36:31 +00:00
protected readonly IProviderRepository ProviderRepo;
protected readonly IFileSystem FileSystem;
2014-02-02 13:36:31 +00:00
protected MetadataService(IServerConfigurationManager serverConfigurationManager, ILogger logger, IProviderManager providerManager, IProviderRepository providerRepo, IFileSystem fileSystem)
{
ServerConfigurationManager = serverConfigurationManager;
Logger = logger;
ProviderManager = providerManager;
2014-02-02 13:36:31 +00:00
ProviderRepo = providerRepo;
FileSystem = fileSystem;
}
/// <summary>
/// Saves the provider result.
/// </summary>
/// <param name="result">The result.</param>
/// <returns>Task.</returns>
2014-01-29 05:17:58 +00:00
protected Task SaveProviderResult(MetadataStatus result)
{
2014-02-02 13:36:31 +00:00
return ProviderRepo.SaveMetadataStatus(result, CancellationToken.None);
}
/// <summary>
/// Gets the last result.
/// </summary>
/// <param name="itemId">The item identifier.</param>
/// <returns>ProviderResult.</returns>
2014-01-29 05:17:58 +00:00
protected MetadataStatus GetLastResult(Guid itemId)
{
2014-02-02 13:36:31 +00:00
return ProviderRepo.GetMetadataStatus(itemId) ?? new MetadataStatus { ItemId = itemId };
}
2014-02-02 13:36:31 +00:00
public async Task RefreshMetadata(IHasMetadata item, MetadataRefreshOptions refreshOptions, CancellationToken cancellationToken)
{
var itemOfType = (TItemType)item;
2014-02-02 13:36:31 +00:00
var config = GetMetadataOptions(itemOfType);
var updateType = ItemUpdateType.Unspecified;
2014-02-03 17:44:13 +00:00
var refreshResult = GetLastResult(item.Id);
2014-01-29 05:17:58 +00:00
refreshResult.LastErrorMessage = string.Empty;
refreshResult.LastStatus = ProviderRefreshStatus.Success;
2014-02-02 13:36:31 +00:00
var itemImageProvider = new ItemImageProvider(Logger, ProviderManager, ServerConfigurationManager, FileSystem);
var localImagesFailed = false;
2014-01-31 19:55:21 +00:00
var allImageProviders = ((ProviderManager)ProviderManager).GetImageProviders(item).ToList();
// Start by validating images
try
{
// Always validate images and check for new locally stored ones.
2014-01-31 19:55:21 +00:00
if (itemImageProvider.ValidateImages(item, allImageProviders.OfType<ILocalImageProvider>()))
{
updateType = updateType | ItemUpdateType.ImageUpdate;
}
}
catch (Exception ex)
{
localImagesFailed = true;
Logger.ErrorException("Error validating images for {0}", ex, item.Path ?? item.Name);
refreshResult.AddStatus(ProviderRefreshStatus.Failure, ex.Message);
}
// Next run metadata providers
2014-02-02 13:36:31 +00:00
if (refreshOptions.MetadataRefreshMode != MetadataRefreshMode.None)
{
2014-02-03 05:35:43 +00:00
updateType = updateType | BeforeMetadataRefresh(itemOfType);
2014-02-03 17:44:13 +00:00
var providers = GetProviders(item, refreshResult.DateLastMetadataRefresh.HasValue, refreshOptions).ToList();
if (providers.Count > 0)
{
2014-02-02 13:36:31 +00:00
var result = await RefreshWithProviders(itemOfType, refreshOptions, providers, cancellationToken).ConfigureAwait(false);
updateType = updateType | result.UpdateType;
refreshResult.AddStatus(result.Status, result.ErrorMessage);
2014-01-29 05:17:58 +00:00
refreshResult.SetDateLastMetadataRefresh(DateTime.UtcNow);
refreshResult.AddImageProvidersRefreshed(result.Providers);
}
}
// Next run remote image providers, but only if local image providers didn't throw an exception
2014-02-02 13:36:31 +00:00
if (!localImagesFailed && refreshOptions.ImageRefreshMode != ImageRefreshMode.ValidationOnly)
{
2014-02-03 17:44:13 +00:00
var providers = GetNonLocalImageProviders(item, allImageProviders, refreshResult.DateLastImagesRefresh, refreshOptions).ToList();
2014-01-29 17:23:38 +00:00
if (providers.Count > 0)
{
2014-02-02 13:36:31 +00:00
var result = await itemImageProvider.RefreshImages(itemOfType, providers, refreshOptions, config, cancellationToken).ConfigureAwait(false);
2014-01-29 05:17:58 +00:00
updateType = updateType | result.UpdateType;
refreshResult.AddStatus(result.Status, result.ErrorMessage);
refreshResult.SetDateLastImagesRefresh(DateTime.UtcNow);
refreshResult.AddImageProvidersRefreshed(result.Providers);
}
}
updateType = updateType | BeforeSave(itemOfType);
var providersHadChanges = updateType > ItemUpdateType.Unspecified;
2014-02-02 13:36:31 +00:00
if (refreshOptions.ForceSave || providersHadChanges)
{
if (string.IsNullOrEmpty(item.Name))
{
2014-01-31 19:55:21 +00:00
throw new InvalidOperationException(item.GetType().Name + " has no name: " + item.Path);
}
// Save to database
await SaveItem(itemOfType, updateType, cancellationToken);
}
2014-01-29 05:17:58 +00:00
if (providersHadChanges || refreshResult.IsDirty)
{
await SaveProviderResult(refreshResult).ConfigureAwait(false);
}
}
2014-02-02 13:36:31 +00:00
private readonly MetadataOptions _defaultOptions = new MetadataOptions();
protected MetadataOptions GetMetadataOptions(TItemType item)
{
var type = item.GetType().Name;
return ServerConfigurationManager.Configuration.MetadataOptions
.FirstOrDefault(i => string.Equals(i.ItemType, type, StringComparison.OrdinalIgnoreCase)) ??
_defaultOptions;
}
2014-01-31 04:50:09 +00:00
/// <summary>
/// Befores the metadata refresh.
2014-01-31 04:50:09 +00:00
/// </summary>
/// <param name="item">The item.</param>
/// <returns>ItemUpdateType.</returns>
protected virtual ItemUpdateType BeforeMetadataRefresh(TItemType item)
2014-01-31 04:50:09 +00:00
{
return ItemUpdateType.Unspecified;
}
2014-02-03 05:35:43 +00:00
/// <summary>
/// Befores the save.
2014-02-03 05:35:43 +00:00
/// </summary>
/// <param name="item">The item.</param>
/// <returns>ItemUpdateType.</returns>
protected virtual ItemUpdateType BeforeSave(TItemType item)
2014-02-03 05:35:43 +00:00
{
return ItemUpdateType.Unspecified;
}
/// <summary>
/// Gets the providers.
/// </summary>
/// <param name="item">The item.</param>
/// <param name="hasRefreshedMetadata">if set to <c>true</c> [has refreshed metadata].</param>
/// <param name="options">The options.</param>
/// <returns>IEnumerable{`0}.</returns>
protected virtual IEnumerable<IMetadataProvider> GetProviders(IHasMetadata item, bool hasRefreshedMetadata, MetadataRefreshOptions options)
{
// Get providers to refresh
2014-02-01 06:18:16 +00:00
var providers = ((ProviderManager)ProviderManager).GetMetadataProviders<TItemType>(item).ToList();
// Run all if either of these flags are true
var runAllProviders = options.ReplaceAllMetadata || options.MetadataRefreshMode == MetadataRefreshMode.FullRefresh || !hasRefreshedMetadata;
if (!runAllProviders)
{
// Avoid implicitly captured closure
var currentItem = item;
var providersWithChanges = providers.OfType<IHasChangeMonitor>()
2014-01-29 05:17:58 +00:00
.Where(i => i.HasChanged(currentItem, currentItem.DateLastSaved))
.ToList();
// If local providers are the only ones with changes, then just run those
if (providersWithChanges.All(i => i is ILocalMetadataProvider))
{
2014-01-29 17:23:38 +00:00
providers = providersWithChanges.Count == 0 ?
new List<IMetadataProvider<TItemType>>() :
providers.Where(i => i is ILocalMetadataProvider).ToList();
}
}
return providers;
}
2014-02-03 17:44:13 +00:00
protected virtual IEnumerable<IImageProvider> GetNonLocalImageProviders(IHasMetadata item, IEnumerable<IImageProvider> allImageProviders, DateTime? dateLastImageRefresh, ImageRefreshOptions options)
2014-01-29 17:23:38 +00:00
{
// Get providers to refresh
2014-01-31 19:55:21 +00:00
var providers = allImageProviders.Where(i => !(i is ILocalImageProvider)).ToList();
2014-01-29 17:23:38 +00:00
// Run all if either of these flags are true
2014-02-03 17:44:13 +00:00
var runAllProviders = options.ImageRefreshMode == ImageRefreshMode.FullRefresh || !dateLastImageRefresh.HasValue;
2014-01-29 17:23:38 +00:00
if (!runAllProviders)
{
// Avoid implicitly captured closure
var currentItem = item;
providers = providers.OfType<IHasChangeMonitor>()
2014-02-03 17:44:13 +00:00
.Where(i => i.HasChanged(currentItem, dateLastImageRefresh.Value))
2014-01-29 17:23:38 +00:00
.Cast<IImageProvider>()
.ToList();
}
return providers;
}
protected abstract Task SaveItem(TItemType item, ItemUpdateType reason, CancellationToken cancellationToken);
2014-01-31 19:55:21 +00:00
protected virtual TIdType GetId(TItemType item)
{
2014-01-31 19:55:21 +00:00
return new TIdType
{
MetadataCountryCode = item.GetPreferredMetadataCountryCode(),
MetadataLanguage = item.GetPreferredMetadataLanguage(),
Name = item.Name,
ProviderIds = item.ProviderIds
};
}
public bool CanRefresh(IHasMetadata item)
{
return item is TItemType;
}
protected virtual async Task<RefreshResult> RefreshWithProviders(TItemType item, MetadataRefreshOptions options, List<IMetadataProvider> providers, CancellationToken cancellationToken)
{
2014-01-29 05:17:58 +00:00
var refreshResult = new RefreshResult
{
UpdateType = ItemUpdateType.Unspecified,
Providers = providers.Select(i => i.GetType().FullName.GetMD5()).ToList()
};
2014-01-30 21:23:54 +00:00
var temp = CreateNew();
// If replacing all metadata, run internet providers first
if (options.ReplaceAllMetadata)
{
await ExecuteRemoteProviders(item, temp, providers.OfType<IRemoteMetadataProvider<TItemType>>(), refreshResult, cancellationToken).ConfigureAwait(false);
}
var hasLocalMetadata = false;
foreach (var provider in providers.OfType<ILocalMetadataProvider<TItemType>>())
{
Logger.Debug("Running {0} for {1}", provider.GetType().Name, item.Path ?? item.Name);
try
{
var localItem = await provider.GetMetadata(item.Path, cancellationToken).ConfigureAwait(false);
if (localItem.HasMetadata)
{
2014-02-03 05:35:43 +00:00
if (!string.IsNullOrEmpty(localItem.Item.Name))
{
MergeData(localItem.Item, temp, new List<MetadataFields>(), !options.ReplaceAllMetadata, true);
refreshResult.UpdateType = refreshResult.UpdateType | ItemUpdateType.MetadataImport;
// Only one local provider allowed per item
hasLocalMetadata = true;
break;
}
2014-02-03 05:35:43 +00:00
Logger.Error("Invalid local metadata found for: " + item.Path);
}
}
catch (OperationCanceledException)
{
throw;
}
catch (Exception ex)
{
// If a local provider fails, consider that a failure
refreshResult.Status = ProviderRefreshStatus.Failure;
refreshResult.ErrorMessage = ex.Message;
Logger.ErrorException("Error in {0}", ex, provider.Name);
// If the local provider fails don't continue with remote providers because the user's saved metadata could be lost
return refreshResult;
}
}
if (!options.ReplaceAllMetadata && !hasLocalMetadata)
{
await ExecuteRemoteProviders(item, temp, providers.OfType<IRemoteMetadataProvider<TItemType>>(), refreshResult, cancellationToken).ConfigureAwait(false);
}
2014-02-01 06:18:16 +00:00
if (refreshResult.UpdateType > ItemUpdateType.Unspecified)
{
MergeData(temp, item, item.LockedFields, true, true);
}
2014-02-02 13:36:31 +00:00
foreach (var provider in providers.OfType<ICustomMetadataProvider<TItemType>>())
{
Logger.Debug("Running {0} for {1}", provider.GetType().Name, item.Path ?? item.Name);
try
{
await provider.FetchAsync(item, cancellationToken).ConfigureAwait(false);
refreshResult.UpdateType = refreshResult.UpdateType | ItemUpdateType.MetadataDownload;
}
catch (OperationCanceledException)
{
throw;
}
catch (Exception ex)
{
refreshResult.Status = ProviderRefreshStatus.CompletedWithErrors;
refreshResult.ErrorMessage = ex.Message;
Logger.ErrorException("Error in {0}", ex, provider.Name);
}
}
return refreshResult;
}
2014-02-02 13:36:31 +00:00
protected virtual TItemType CreateNew()
{
return new TItemType();
}
2014-01-30 21:23:54 +00:00
private async Task ExecuteRemoteProviders(TItemType item, TItemType temp, IEnumerable<IRemoteMetadataProvider<TItemType>> providers, RefreshResult refreshResult, CancellationToken cancellationToken)
{
var id = GetId(item);
foreach (var provider in providers)
{
Logger.Debug("Running {0} for {1}", provider.GetType().Name, item.Path ?? item.Name);
try
{
var result = await provider.GetMetadata(id, cancellationToken).ConfigureAwait(false);
if (result.HasMetadata)
{
MergeData(result.Item, temp, new List<MetadataFields>(), false, false);
refreshResult.UpdateType = refreshResult.UpdateType | ItemUpdateType.MetadataDownload;
}
}
catch (OperationCanceledException)
{
throw;
}
catch (Exception ex)
{
refreshResult.Status = ProviderRefreshStatus.CompletedWithErrors;
refreshResult.ErrorMessage = ex.Message;
Logger.ErrorException("Error in {0}", ex, provider.Name);
}
}
}
protected abstract void MergeData(TItemType source, TItemType target, List<MetadataFields> lockedFields, bool replaceData, bool mergeMetadataSettings);
public virtual int Order
{
get
{
return 0;
}
}
}
public class RefreshResult
{
public ItemUpdateType UpdateType { get; set; }
public ProviderRefreshStatus Status { get; set; }
public string ErrorMessage { get; set; }
2014-01-29 05:17:58 +00:00
public List<Guid> Providers { get; set; }
}
}