ArtistsValidator.cs 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  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 ILibraryManager _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(ILibraryManager 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. }
  128. /// <summary>
  129. /// Merges the images.
  130. /// </summary>
  131. /// <param name="source">The source.</param>
  132. /// <param name="target">The target.</param>
  133. private void MergeImages(Dictionary<ImageType, string> source, Dictionary<ImageType, string> target)
  134. {
  135. foreach (var key in source.Keys
  136. .ToList()
  137. .Where(k => !target.ContainsKey(k)))
  138. {
  139. string path;
  140. if (source.TryGetValue(key, out path))
  141. {
  142. target[key] = path;
  143. }
  144. }
  145. }
  146. /// <summary>
  147. /// Gets all artists.
  148. /// </summary>
  149. /// <param name="allSongs">All songs.</param>
  150. /// <param name="cancellationToken">The cancellation token.</param>
  151. /// <param name="progress">The progress.</param>
  152. /// <returns>Task{Artist[]}.</returns>
  153. private async Task<List<Artist>> GetAllArtists(IEnumerable<Audio> allSongs, CancellationToken cancellationToken, IProgress<double> progress)
  154. {
  155. var allArtists = allSongs
  156. .SelectMany(i =>
  157. {
  158. var list = new List<string>();
  159. if (!string.IsNullOrEmpty(i.AlbumArtist))
  160. {
  161. list.Add(i.AlbumArtist);
  162. }
  163. list.AddRange(i.Artists);
  164. return list;
  165. })
  166. .Distinct(StringComparer.OrdinalIgnoreCase)
  167. .ToList();
  168. const int maxTasks = 5;
  169. var tasks = new List<Task>();
  170. var returnArtists = new ConcurrentBag<Artist>();
  171. var numComplete = 0;
  172. foreach (var artist in allArtists)
  173. {
  174. if (tasks.Count > maxTasks)
  175. {
  176. await Task.WhenAll(tasks).ConfigureAwait(false);
  177. tasks.Clear();
  178. // Safe cancellation point, when there are no pending tasks
  179. cancellationToken.ThrowIfCancellationRequested();
  180. }
  181. // Avoid accessing the foreach variable within the closure
  182. var currentArtist = artist;
  183. tasks.Add(Task.Run(async () =>
  184. {
  185. cancellationToken.ThrowIfCancellationRequested();
  186. try
  187. {
  188. var artistItem = _libraryManager.GetArtist(currentArtist);
  189. await artistItem.RefreshMetadata(cancellationToken).ConfigureAwait(false);
  190. returnArtists.Add(artistItem);
  191. }
  192. catch (IOException ex)
  193. {
  194. _logger.ErrorException("Error validating Artist {0}", ex, currentArtist);
  195. }
  196. // Update progress
  197. lock (progress)
  198. {
  199. numComplete++;
  200. double percent = numComplete;
  201. percent /= allArtists.Count;
  202. progress.Report(100 * percent);
  203. }
  204. }));
  205. }
  206. await Task.WhenAll(tasks).ConfigureAwait(false);
  207. return returnArtists.ToList();
  208. }
  209. /// <summary>
  210. /// Finds the music artist.
  211. /// </summary>
  212. /// <param name="artist">The artist.</param>
  213. /// <param name="allMusicArtists">All music artists.</param>
  214. /// <returns>MusicArtist.</returns>
  215. private static MusicArtist FindMusicArtist(Artist artist, IEnumerable<MusicArtist> allMusicArtists)
  216. {
  217. var musicBrainzId = artist.GetProviderId(MetadataProviders.Musicbrainz);
  218. return allMusicArtists.FirstOrDefault(i =>
  219. {
  220. if (!string.IsNullOrWhiteSpace(musicBrainzId) && string.Equals(musicBrainzId, i.GetProviderId(MetadataProviders.Musicbrainz), StringComparison.OrdinalIgnoreCase))
  221. {
  222. return true;
  223. }
  224. return string.Compare(i.Name, artist.Name, CultureInfo.CurrentCulture, CompareOptions.IgnoreNonSpace | CompareOptions.IgnoreCase | CompareOptions.IgnoreSymbols) == 0;
  225. });
  226. }
  227. }
  228. }