using MediaBrowser.Common.Progress;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.Audio;
using MediaBrowser.Controller.Library;
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Logging;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace MediaBrowser.Server.Implementations.Library.Validators
{
///
/// Class ArtistsValidator
///
public class ArtistsValidator
{
///
/// The _library manager
///
private readonly ILibraryManager _libraryManager;
///
/// The _user manager
///
private readonly IUserManager _userManager;
///
/// The _logger
///
private readonly ILogger _logger;
///
/// Initializes a new instance of the class.
///
/// The library manager.
/// The user manager.
/// The logger.
public ArtistsValidator(ILibraryManager libraryManager, IUserManager userManager, ILogger logger)
{
_libraryManager = libraryManager;
_userManager = userManager;
_logger = logger;
}
///
/// Runs the specified progress.
///
/// The progress.
/// The cancellation token.
/// Task.
public async Task Run(IProgress progress, CancellationToken cancellationToken)
{
var allItems = _libraryManager.RootFolder.RecursiveChildren.ToList();
var allMusicArtists = allItems.OfType().ToList();
var allSongs = allItems.OfType().ToList();
var innerProgress = new ActionableProgress();
innerProgress.RegisterAction(pct => progress.Report(pct * .8));
var allArtists = await GetAllArtists(allSongs, cancellationToken, innerProgress).ConfigureAwait(false);
progress.Report(80);
var numComplete = 0;
var userLibraries = _userManager.Users
.Select(i => new Tuple>(i.Id, i.RootFolder.GetRecursiveChildren(i).OfType().ToList()))
.ToList();
var numArtists = allArtists.Count;
foreach (var artist in allArtists)
{
cancellationToken.ThrowIfCancellationRequested();
artist.ValidateImages();
artist.ValidateBackdrops();
var musicArtist = FindMusicArtist(artist, allMusicArtists);
if (musicArtist != null)
{
MergeImages(musicArtist.Images, artist.Images);
// Merge backdrops
var backdrops = musicArtist.BackdropImagePaths.ToList();
backdrops.InsertRange(0, artist.BackdropImagePaths);
artist.BackdropImagePaths = backdrops.Distinct(StringComparer.OrdinalIgnoreCase)
.ToList();
}
if (!artist.LockedFields.Contains(MetadataFields.Genres))
{
// Avoid implicitly captured closure
var artist1 = artist;
artist.Genres = allSongs.Where(i => i.HasArtist(artist1.Name))
.SelectMany(i => i.Genres)
.Distinct(StringComparer.OrdinalIgnoreCase)
.ToList();
}
// Populate counts of items
//SetItemCounts(artist, null, allItems.OfType());
foreach (var lib in userLibraries)
{
SetItemCounts(artist, lib.Item1, lib.Item2);
}
numComplete++;
double percent = numComplete;
percent /= numArtists;
percent *= 20;
progress.Report(80 + percent);
}
progress.Report(100);
}
///
/// Sets the item counts.
///
/// The artist.
/// The user id.
/// All items.
private void SetItemCounts(Artist artist, Guid? userId, IEnumerable allItems)
{
var name = artist.Name;
var items = allItems
.Where(i => i.HasArtist(name))
.ToList();
var counts = new ItemByNameCounts
{
TotalCount = items.Count,
SongCount = items.OfType().Count(),
AlbumCount = items.OfType().Count(),
MusicVideoCount = items.OfType().Count()
};
if (userId.HasValue)
{
artist.UserItemCounts[userId.Value] = counts;
}
}
///
/// Merges the images.
///
/// The source.
/// The target.
private void MergeImages(Dictionary source, Dictionary target)
{
foreach (var key in source.Keys
.Where(k => !target.ContainsKey(k)))
{
string path;
if (source.TryGetValue(key, out path))
{
target[key] = path;
}
}
}
///
/// Gets all artists.
///
/// All songs.
/// The cancellation token.
/// The progress.
/// Task{Artist[]}.
private async Task> GetAllArtists(IEnumerable allSongs, CancellationToken cancellationToken, IProgress progress)
{
var allArtists = allSongs
.SelectMany(i =>
{
var list = new List();
if (!string.IsNullOrEmpty(i.AlbumArtist))
{
list.Add(i.AlbumArtist);
}
list.AddRange(i.Artists);
return list;
})
.Distinct(StringComparer.OrdinalIgnoreCase)
.ToList();
const int maxTasks = 3;
var tasks = new List();
var returnArtists = new ConcurrentBag();
var numComplete = 0;
var numArtists = allArtists.Count;
foreach (var artist in allArtists)
{
if (tasks.Count > maxTasks)
{
await Task.WhenAll(tasks).ConfigureAwait(false);
tasks.Clear();
// Safe cancellation point, when there are no pending tasks
cancellationToken.ThrowIfCancellationRequested();
}
// Avoid accessing the foreach variable within the closure
var currentArtist = artist;
tasks.Add(Task.Run(async () =>
{
cancellationToken.ThrowIfCancellationRequested();
try
{
var artistItem = _libraryManager.GetArtist(currentArtist);
await artistItem.RefreshMetadata(cancellationToken).ConfigureAwait(false);
returnArtists.Add(artistItem);
}
catch (IOException ex)
{
_logger.ErrorException("Error validating Artist {0}", ex, currentArtist);
}
// Update progress
lock (progress)
{
numComplete++;
double percent = numComplete;
percent /= numArtists;
progress.Report(100 * percent);
}
}));
}
await Task.WhenAll(tasks).ConfigureAwait(false);
return returnArtists;
}
///
/// Finds the music artist.
///
/// The artist.
/// All music artists.
/// MusicArtist.
private static MusicArtist FindMusicArtist(Artist artist, IEnumerable allMusicArtists)
{
var musicBrainzId = artist.GetProviderId(MetadataProviders.Musicbrainz);
return allMusicArtists.FirstOrDefault(i =>
{
if (!string.IsNullOrWhiteSpace(musicBrainzId) && string.Equals(musicBrainzId, i.GetProviderId(MetadataProviders.Musicbrainz), StringComparison.OrdinalIgnoreCase))
{
return true;
}
return string.Compare(i.Name, artist.Name, CultureInfo.CurrentCulture, CompareOptions.IgnoreNonSpace | CompareOptions.IgnoreCase | CompareOptions.IgnoreSymbols) == 0;
});
}
}
}