using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Common.Net;
using MediaBrowser.Common.Progress;
using MediaBrowser.Controller;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Dto;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.Audio;
using MediaBrowser.Controller.Entities.Movies;
using MediaBrowser.Controller.Entities.TV;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Controller.Subtitles;
using MediaBrowser.Model.Configuration;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Events;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.Providers;
using MediaBrowser.Model.Serialization;
using Microsoft.Extensions.Logging;
using Priority_Queue;
namespace MediaBrowser.Providers.Manager
{
///
/// Class ProviderManager
///
public class ProviderManager : IProviderManager, IDisposable
{
///
/// The _logger
///
private readonly ILogger _logger;
///
/// The _HTTP client
///
private readonly IHttpClient _httpClient;
///
/// The _directory watchers
///
private readonly ILibraryMonitor _libraryMonitor;
///
/// Gets or sets the configuration manager.
///
/// The configuration manager.
private IServerConfigurationManager ConfigurationManager { get; set; }
private IImageProvider[] ImageProviders { get; set; }
private readonly IFileSystem _fileSystem;
private IMetadataService[] _metadataServices = { };
private IMetadataProvider[] _metadataProviders = { };
private IEnumerable _savers;
private readonly IServerApplicationPaths _appPaths;
private readonly IJsonSerializer _json;
private IExternalId[] _externalIds;
private readonly Func _libraryManagerFactory;
private CancellationTokenSource _disposeCancellationTokenSource = new CancellationTokenSource();
public event EventHandler> RefreshStarted;
public event EventHandler> RefreshCompleted;
public event EventHandler>> RefreshProgress;
private ISubtitleManager _subtitleManager;
///
/// Initializes a new instance of the class.
///
public ProviderManager(IHttpClient httpClient, ISubtitleManager subtitleManager, IServerConfigurationManager configurationManager, ILibraryMonitor libraryMonitor, ILoggerFactory loggerFactory, IFileSystem fileSystem, IServerApplicationPaths appPaths, Func libraryManagerFactory, IJsonSerializer json)
{
_logger = loggerFactory.CreateLogger("ProviderManager");
_httpClient = httpClient;
ConfigurationManager = configurationManager;
_libraryMonitor = libraryMonitor;
_fileSystem = fileSystem;
_appPaths = appPaths;
_libraryManagerFactory = libraryManagerFactory;
_json = json;
_subtitleManager = subtitleManager;
}
///
/// Adds the metadata providers.
///
public void AddParts(IEnumerable imageProviders, IEnumerable metadataServices,
IEnumerable metadataProviders, IEnumerable metadataSavers,
IEnumerable externalIds)
{
ImageProviders = imageProviders.ToArray();
_metadataServices = metadataServices.OrderBy(i => i.Order).ToArray();
_metadataProviders = metadataProviders.ToArray();
_externalIds = externalIds.OrderBy(i => i.Name).ToArray();
_savers = metadataSavers.Where(i =>
{
var configurable = i as IConfigurableProvider;
return configurable == null || configurable.IsEnabled;
}).ToArray();
}
public Task RefreshSingleItem(BaseItem item, MetadataRefreshOptions options, CancellationToken cancellationToken)
{
IMetadataService service = null;
var type = item.GetType();
foreach (var current in _metadataServices)
{
if (current.CanRefreshPrimary(type))
{
service = current;
break;
}
}
if (service == null)
{
foreach (var current in _metadataServices)
{
if (current.CanRefresh(item))
{
service = current;
break;
}
}
}
if (service != null)
{
return service.RefreshMetadata(item, options, cancellationToken);
}
_logger.LogError("Unable to find a metadata service for item of type {TypeName}", item.GetType().Name);
return Task.FromResult(ItemUpdateType.None);
}
public async Task SaveImage(BaseItem item, string url, ImageType type, int? imageIndex, CancellationToken cancellationToken)
{
using (var response = await _httpClient.GetResponse(new HttpRequestOptions
{
CancellationToken = cancellationToken,
Url = url,
BufferContent = false
}).ConfigureAwait(false))
{
// Workaround for tvheadend channel icons
// TODO: Isolate this hack into the tvh plugin
if (string.IsNullOrEmpty(response.ContentType))
{
if (url.IndexOf("/imagecache/", StringComparison.OrdinalIgnoreCase) != -1)
{
response.ContentType = "image/png";
}
}
await SaveImage(item, response.Content, response.ContentType, type, imageIndex, cancellationToken).ConfigureAwait(false);
}
}
public Task SaveImage(BaseItem item, Stream source, string mimeType, ImageType type, int? imageIndex, CancellationToken cancellationToken)
{
return new ImageSaver(ConfigurationManager, _libraryMonitor, _fileSystem, _logger).SaveImage(item, source, mimeType, type, imageIndex, cancellationToken);
}
public Task SaveImage(BaseItem item, string source, string mimeType, ImageType type, int? imageIndex, bool? saveLocallyWithMedia, CancellationToken cancellationToken)
{
if (string.IsNullOrWhiteSpace(source))
{
throw new ArgumentNullException(nameof(source));
}
var fileStream = new FileStream(source, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, IODefaults.FileStreamBufferSize, true);
return new ImageSaver(ConfigurationManager, _libraryMonitor, _fileSystem, _logger).SaveImage(item, fileStream, mimeType, type, imageIndex, saveLocallyWithMedia, cancellationToken);
}
public async Task> GetAvailableRemoteImages(BaseItem item, RemoteImageQuery query, CancellationToken cancellationToken)
{
var providers = GetRemoteImageProviders(item, query.IncludeDisabledProviders);
if (!string.IsNullOrEmpty(query.ProviderName))
{
var providerName = query.ProviderName;
providers = providers.Where(i => string.Equals(i.Name, providerName, StringComparison.OrdinalIgnoreCase));
}
var preferredLanguage = item.GetPreferredMetadataLanguage();
var languages = new List();
if (!query.IncludeAllLanguages && !string.IsNullOrWhiteSpace(preferredLanguage))
{
languages.Add(preferredLanguage);
}
var tasks = providers.Select(i => GetImages(item, cancellationToken, i, languages, query.ImageType));
var results = await Task.WhenAll(tasks).ConfigureAwait(false);
return results.SelectMany(i => i.ToList());
}
///
/// Gets the images.
///
/// The item.
/// The cancellation token.
/// The provider.
/// The preferred languages.
/// The type.
/// Task{IEnumerable{RemoteImageInfo}}.
private async Task> GetImages(BaseItem item, CancellationToken cancellationToken, IRemoteImageProvider provider, List preferredLanguages, ImageType? type = null)
{
try
{
var result = await provider.GetImages(item, cancellationToken).ConfigureAwait(false);
if (type.HasValue)
{
result = result.Where(i => i.Type == type.Value);
}
if (preferredLanguages.Count > 0)
{
result = result.Where(i => string.IsNullOrEmpty(i.Language) ||
preferredLanguages.Contains(i.Language, StringComparer.OrdinalIgnoreCase) ||
string.Equals(i.Language, "en", StringComparison.OrdinalIgnoreCase));
}
return result;
}
catch (OperationCanceledException)
{
return new List();
}
catch (Exception ex)
{
_logger.LogError(ex, "{0} failed in GetImageInfos for type {1}", provider.GetType().Name, item.GetType().Name);
return new List();
}
}
///
/// Gets the supported image providers.
///
/// The item.
/// IEnumerable{IImageProvider}.
public IEnumerable GetRemoteImageProviderInfo(BaseItem item)
{
return GetRemoteImageProviders(item, true).Select(i => new ImageProviderInfo
{
Name = i.Name,
SupportedImages = i.GetSupportedImages(item).ToArray()
});
}
public IEnumerable GetImageProviders(BaseItem item, ImageRefreshOptions refreshOptions)
{
return GetImageProviders(item, _libraryManagerFactory().GetLibraryOptions(item), GetMetadataOptions(item), refreshOptions, false);
}
private IEnumerable GetImageProviders(BaseItem item, LibraryOptions libraryOptions, MetadataOptions options, ImageRefreshOptions refreshOptions, bool includeDisabled)
{
// Avoid implicitly captured closure
var currentOptions = options;
var typeOptions = libraryOptions.GetTypeOptions(item.GetType().Name);
var typeFetcherOrder = typeOptions?.ImageFetcherOrder;
return ImageProviders.Where(i => CanRefresh(i, item, libraryOptions, options, refreshOptions, includeDisabled))
.OrderBy(i =>
{
// See if there's a user-defined order
if (!(i is ILocalImageProvider))
{
var fetcherOrder = typeFetcherOrder ?? currentOptions.ImageFetcherOrder;
var index = Array.IndexOf(fetcherOrder, i.Name);
if (index != -1)
{
return index;
}
}
// Not configured. Just return some high number to put it at the end.
return 100;
})
.ThenBy(GetOrder);
}
public IEnumerable> GetMetadataProviders(BaseItem item, LibraryOptions libraryOptions)
where T : BaseItem
{
var globalMetadataOptions = GetMetadataOptions(item);
return GetMetadataProvidersInternal(item, libraryOptions, globalMetadataOptions, false, false);
}
private IEnumerable> GetMetadataProvidersInternal(BaseItem item, LibraryOptions libraryOptions, MetadataOptions globalMetadataOptions, bool includeDisabled, bool forceEnableInternetMetadata)
where T : BaseItem
{
// Avoid implicitly captured closure
var currentOptions = globalMetadataOptions;
return _metadataProviders.OfType>()
.Where(i => CanRefresh(i, item, libraryOptions, currentOptions, includeDisabled, forceEnableInternetMetadata))
.OrderBy(i => GetConfiguredOrder(item, i, libraryOptions, globalMetadataOptions))
.ThenBy(GetDefaultOrder);
}
private IEnumerable GetRemoteImageProviders(BaseItem item, bool includeDisabled)
{
var options = GetMetadataOptions(item);
var libraryOptions = _libraryManagerFactory().GetLibraryOptions(item);
return GetImageProviders(item, libraryOptions, options,
new ImageRefreshOptions(
new DirectoryService(_fileSystem)),
includeDisabled)
.OfType();
}
private bool CanRefresh(IMetadataProvider provider, BaseItem item, LibraryOptions libraryOptions, MetadataOptions options, bool includeDisabled, bool forceEnableInternetMetadata)
{
if (!includeDisabled)
{
// If locked only allow local providers
if (item.IsLocked && !(provider is ILocalMetadataProvider) && !(provider is IForcedProvider))
{
return false;
}
if (provider is IRemoteMetadataProvider)
{
if (!forceEnableInternetMetadata && !item.IsMetadataFetcherEnabled(libraryOptions, provider.Name))
{
return false;
}
}
}
if (!item.SupportsLocalMetadata && provider is ILocalMetadataProvider)
{
return false;
}
// If this restriction is ever lifted, movie xml providers will have to be updated to prevent owned items like trailers from reading those files
if (!item.OwnerId.Equals(Guid.Empty))
{
if (provider is ILocalMetadataProvider || provider is IRemoteMetadataProvider)
{
return false;
}
}
return true;
}
private bool CanRefresh(IImageProvider provider, BaseItem item, LibraryOptions libraryOptions, MetadataOptions options, ImageRefreshOptions refreshOptions, bool includeDisabled)
{
if (!includeDisabled)
{
// If locked only allow local providers
if (item.IsLocked && !(provider is ILocalImageProvider))
{
if (refreshOptions.ImageRefreshMode != MetadataRefreshMode.FullRefresh)
{
return false;
}
}
if (provider is IRemoteImageProvider || provider is IDynamicImageProvider)
{
if (!item.IsImageFetcherEnabled(libraryOptions, provider.Name))
{
return false;
}
}
}
try
{
return provider.Supports(item);
}
catch (Exception ex)
{
_logger.LogError(ex, "{0} failed in Supports for type {1}", provider.GetType().Name, item.GetType().Name);
return false;
}
}
///
/// Gets the order.
///
/// The provider.
/// System.Int32.
private int GetOrder(IImageProvider provider)
{
var hasOrder = provider as IHasOrder;
if (hasOrder == null)
{
return 0;
}
return hasOrder.Order;
}
private int GetConfiguredOrder(BaseItem item, IMetadataProvider provider, LibraryOptions libraryOptions, MetadataOptions globalMetadataOptions)
{
// See if there's a user-defined order
if (provider is ILocalMetadataProvider)
{
var configuredOrder = libraryOptions.LocalMetadataReaderOrder ?? globalMetadataOptions.LocalMetadataReaderOrder;
var index = Array.IndexOf(configuredOrder, provider.Name);
if (index != -1)
{
return index;
}
}
// See if there's a user-defined order
if (provider is IRemoteMetadataProvider)
{
var typeOptions = libraryOptions.GetTypeOptions(item.GetType().Name);
var typeFetcherOrder = typeOptions == null ? null : typeOptions.MetadataFetcherOrder;
var fetcherOrder = typeFetcherOrder ?? globalMetadataOptions.MetadataFetcherOrder;
var index = Array.IndexOf(fetcherOrder, provider.Name);
if (index != -1)
{
return index;
}
}
// Not configured. Just return some high number to put it at the end.
return 100;
}
private int GetDefaultOrder(IMetadataProvider provider)
{
var hasOrder = provider as IHasOrder;
if (hasOrder != null)
{
return hasOrder.Order;
}
return 0;
}
public MetadataPluginSummary[] GetAllMetadataPlugins()
{
return new MetadataPluginSummary[]
{
GetPluginSummary(),
GetPluginSummary(),
GetPluginSummary(),
GetPluginSummary(),
GetPluginSummary(),
GetPluginSummary(),
GetPluginSummary(),
GetPluginSummary(),
GetPluginSummary