ArtistsValidator.cs 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. using MediaBrowser.Common.Progress;
  2. using MediaBrowser.Controller.Entities;
  3. using MediaBrowser.Controller.Entities.Audio;
  4. using MediaBrowser.Controller.Library;
  5. using MediaBrowser.Model.Dto;
  6. using MediaBrowser.Model.Entities;
  7. using MediaBrowser.Model.Logging;
  8. using System;
  9. using System.Collections.Concurrent;
  10. using System.Collections.Generic;
  11. using System.Globalization;
  12. using System.IO;
  13. using System.Linq;
  14. using System.Threading;
  15. using System.Threading.Tasks;
  16. namespace MediaBrowser.Server.Implementations.Library.Validators
  17. {
  18. /// <summary>
  19. /// Class ArtistsValidator
  20. /// </summary>
  21. public class ArtistsValidator
  22. {
  23. /// <summary>
  24. /// The _library manager
  25. /// </summary>
  26. private readonly LibraryManager _libraryManager;
  27. /// <summary>
  28. /// The _user manager
  29. /// </summary>
  30. private readonly IUserManager _userManager;
  31. /// <summary>
  32. /// The _logger
  33. /// </summary>
  34. private readonly ILogger _logger;
  35. /// <summary>
  36. /// Initializes a new instance of the <see cref="ArtistsPostScanTask" /> class.
  37. /// </summary>
  38. /// <param name="libraryManager">The library manager.</param>
  39. /// <param name="userManager">The user manager.</param>
  40. /// <param name="logger">The logger.</param>
  41. public ArtistsValidator(LibraryManager libraryManager, IUserManager userManager, ILogger logger)
  42. {
  43. _libraryManager = libraryManager;
  44. _userManager = userManager;
  45. _logger = logger;
  46. }
  47. /// <summary>
  48. /// Runs the specified progress.
  49. /// </summary>
  50. /// <param name="progress">The progress.</param>
  51. /// <param name="cancellationToken">The cancellation token.</param>
  52. /// <returns>Task.</returns>
  53. public async Task Run(IProgress<double> progress, CancellationToken cancellationToken)
  54. {
  55. var allItems = _libraryManager.RootFolder.RecursiveChildren.ToList();
  56. var allMusicArtists = allItems.OfType<MusicArtist>().ToList();
  57. var allSongs = allItems.OfType<Audio>().ToList();
  58. var innerProgress = new ActionableProgress<double>();
  59. innerProgress.RegisterAction(pct => progress.Report(pct * .8));
  60. var allArtists = await GetAllArtists(allSongs, cancellationToken, innerProgress).ConfigureAwait(false);
  61. progress.Report(80);
  62. var numComplete = 0;
  63. var userLibraries = _userManager.Users
  64. .Select(i => new Tuple<Guid, List<IHasArtist>>(i.Id, i.RootFolder.GetRecursiveChildren(i).OfType<IHasArtist>().ToList()))
  65. .ToList();
  66. foreach (var artist in allArtists)
  67. {
  68. cancellationToken.ThrowIfCancellationRequested();
  69. artist.ValidateImages();
  70. artist.ValidateBackdrops();
  71. var musicArtist = FindMusicArtist(artist, allMusicArtists);
  72. if (musicArtist != null)
  73. {
  74. MergeImages(musicArtist.Images, artist.Images);
  75. // Merge backdrops
  76. var backdrops = musicArtist.BackdropImagePaths.ToList();
  77. backdrops.InsertRange(0, artist.BackdropImagePaths);
  78. artist.BackdropImagePaths = backdrops.Distinct(StringComparer.OrdinalIgnoreCase)
  79. .ToList();
  80. }
  81. if (!artist.LockedFields.Contains(MetadataFields.Genres))
  82. {
  83. // Avoid implicitly captured closure
  84. var artist1 = artist;
  85. artist.Genres = allSongs.Where(i => i.HasArtist(artist1.Name))
  86. .SelectMany(i => i.Genres)
  87. .Distinct(StringComparer.OrdinalIgnoreCase)
  88. .ToList();
  89. }
  90. // Populate counts of items
  91. SetItemCounts(artist, null, allItems.OfType<IHasArtist>());
  92. foreach (var lib in userLibraries)
  93. {
  94. SetItemCounts(artist, lib.Item1, lib.Item2);
  95. }
  96. numComplete++;
  97. double percent = numComplete;
  98. percent /= allArtists.Count;
  99. percent *= 20;
  100. progress.Report(80 + percent);
  101. }
  102. progress.Report(100);
  103. }
  104. /// <summary>
  105. /// Sets the item counts.
  106. /// </summary>
  107. /// <param name="artist">The artist.</param>
  108. /// <param name="userId">The user id.</param>
  109. /// <param name="allItems">All items.</param>
  110. private void SetItemCounts(Artist artist, Guid? userId, IEnumerable<IHasArtist> allItems)
  111. {
  112. var name = artist.Name;
  113. var items = allItems
  114. .Where(i => i.HasArtist(name))
  115. .ToList();
  116. var counts = new ItemByNameCounts
  117. {
  118. TotalCount = items.Count,
  119. SongCount = items.OfType<Audio>().Count(),
  120. AlbumCount = items.OfType<MusicAlbum>().Count(),
  121. MusicVideoCount = items.OfType<MusicVideo>().Count()
  122. };
  123. if (userId.HasValue)
  124. {
  125. artist.UserItemCounts[userId.Value] = counts;
  126. }
  127. else
  128. {
  129. artist.ItemCounts = counts;
  130. }
  131. }
  132. /// <summary>
  133. /// Merges the images.
  134. /// </summary>
  135. /// <param name="source">The source.</param>
  136. /// <param name="target">The target.</param>
  137. private void MergeImages(Dictionary<ImageType, string> source, Dictionary<ImageType, string> target)
  138. {
  139. foreach (var key in source.Keys
  140. .ToList()
  141. .Where(k => !target.ContainsKey(k)))
  142. {
  143. string path;
  144. if (source.TryGetValue(key, out path))
  145. {
  146. target[key] = path;
  147. }
  148. }
  149. }
  150. /// <summary>
  151. /// Gets all artists.
  152. /// </summary>
  153. /// <param name="allSongs">All songs.</param>
  154. /// <param name="cancellationToken">The cancellation token.</param>
  155. /// <param name="progress">The progress.</param>
  156. /// <returns>Task{Artist[]}.</returns>
  157. private async Task<List<Artist>> GetAllArtists(IEnumerable<Audio> allSongs, CancellationToken cancellationToken, IProgress<double> progress)
  158. {
  159. var allArtists = allSongs
  160. .SelectMany(i =>
  161. {
  162. var list = new List<string>();
  163. if (!string.IsNullOrEmpty(i.AlbumArtist))
  164. {
  165. list.Add(i.AlbumArtist);
  166. }
  167. list.AddRange(i.Artists);
  168. return list;
  169. })
  170. .Distinct(StringComparer.OrdinalIgnoreCase)
  171. .ToList();
  172. const int maxTasks = 5;
  173. var tasks = new List<Task>();
  174. var returnArtists = new ConcurrentBag<Artist>();
  175. var numComplete = 0;
  176. foreach (var artist in allArtists)
  177. {
  178. if (tasks.Count > maxTasks)
  179. {
  180. await Task.WhenAll(tasks).ConfigureAwait(false);
  181. tasks.Clear();
  182. // Safe cancellation point, when there are no pending tasks
  183. cancellationToken.ThrowIfCancellationRequested();
  184. }
  185. // Avoid accessing the foreach variable within the closure
  186. var currentArtist = artist;
  187. tasks.Add(Task.Run(async () =>
  188. {
  189. cancellationToken.ThrowIfCancellationRequested();
  190. try
  191. {
  192. var artistItem = await _libraryManager.GetArtist(currentArtist, cancellationToken, true, true)
  193. .ConfigureAwait(false);
  194. returnArtists.Add(artistItem);
  195. }
  196. catch (IOException ex)
  197. {
  198. _logger.ErrorException("Error validating Artist {0}", ex, currentArtist);
  199. }
  200. // Update progress
  201. lock (progress)
  202. {
  203. numComplete++;
  204. double percent = numComplete;
  205. percent /= allArtists.Count;
  206. progress.Report(100 * percent);
  207. }
  208. }));
  209. }
  210. await Task.WhenAll(tasks).ConfigureAwait(false);
  211. return returnArtists.ToList();
  212. }
  213. /// <summary>
  214. /// Finds the music artist.
  215. /// </summary>
  216. /// <param name="artist">The artist.</param>
  217. /// <param name="allMusicArtists">All music artists.</param>
  218. /// <returns>MusicArtist.</returns>
  219. private static MusicArtist FindMusicArtist(Artist artist, IEnumerable<MusicArtist> allMusicArtists)
  220. {
  221. var musicBrainzId = artist.GetProviderId(MetadataProviders.Musicbrainz);
  222. return allMusicArtists.FirstOrDefault(i =>
  223. {
  224. if (!string.IsNullOrWhiteSpace(musicBrainzId) && string.Equals(musicBrainzId, i.GetProviderId(MetadataProviders.Musicbrainz), StringComparison.OrdinalIgnoreCase))
  225. {
  226. return true;
  227. }
  228. return string.Compare(i.Name, artist.Name, CultureInfo.CurrentCulture, CompareOptions.IgnoreNonSpace | CompareOptions.IgnoreCase | CompareOptions.IgnoreSymbols) == 0;
  229. });
  230. }
  231. }
  232. }