ArtistsValidator.cs 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  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.Generic;
  10. using System.IO;
  11. using System.Linq;
  12. using System.Threading;
  13. using System.Threading.Tasks;
  14. namespace MediaBrowser.Server.Implementations.Library.Validators
  15. {
  16. /// <summary>
  17. /// Class ArtistsValidator
  18. /// </summary>
  19. public class ArtistsValidator
  20. {
  21. /// <summary>
  22. /// The _library manager
  23. /// </summary>
  24. private readonly ILibraryManager _libraryManager;
  25. /// <summary>
  26. /// The _user manager
  27. /// </summary>
  28. private readonly IUserManager _userManager;
  29. /// <summary>
  30. /// The _logger
  31. /// </summary>
  32. private readonly ILogger _logger;
  33. /// <summary>
  34. /// Initializes a new instance of the <see cref="ArtistsPostScanTask" /> class.
  35. /// </summary>
  36. /// <param name="libraryManager">The library manager.</param>
  37. /// <param name="userManager">The user manager.</param>
  38. /// <param name="logger">The logger.</param>
  39. public ArtistsValidator(ILibraryManager libraryManager, IUserManager userManager, ILogger logger)
  40. {
  41. _libraryManager = libraryManager;
  42. _userManager = userManager;
  43. _logger = logger;
  44. }
  45. /// <summary>
  46. /// Runs the specified progress.
  47. /// </summary>
  48. /// <param name="progress">The progress.</param>
  49. /// <param name="cancellationToken">The cancellation token.</param>
  50. /// <returns>Task.</returns>
  51. public async Task Run(IProgress<double> progress, CancellationToken cancellationToken)
  52. {
  53. var allItems = _libraryManager.RootFolder.GetRecursiveChildren();
  54. var allMusicArtists = allItems.OfType<MusicArtist>().ToList();
  55. var allSongs = allItems.OfType<Audio>().ToList();
  56. var innerProgress = new ActionableProgress<double>();
  57. innerProgress.RegisterAction(pct => progress.Report(pct * .8));
  58. var allArtists = await GetAllArtists(allSongs, cancellationToken, innerProgress).ConfigureAwait(false);
  59. progress.Report(80);
  60. var numComplete = 0;
  61. var userLibraries = _userManager.Users
  62. .Select(i => new Tuple<Guid, List<IHasArtist>>(i.Id, i.RootFolder.GetRecursiveChildren(i).OfType<IHasArtist>().ToList()))
  63. .ToList();
  64. var numArtists = allArtists.Count;
  65. foreach (var artist in allArtists)
  66. {
  67. cancellationToken.ThrowIfCancellationRequested();
  68. artist.ValidateImages();
  69. artist.ValidateBackdrops();
  70. var musicArtist = Artist.FindMusicArtist(artist, allMusicArtists);
  71. if (musicArtist != null)
  72. {
  73. MergeImages(musicArtist.Images, artist.Images);
  74. // Merge backdrops
  75. var backdrops = musicArtist.BackdropImagePaths.ToList();
  76. backdrops.InsertRange(0, artist.BackdropImagePaths);
  77. artist.BackdropImagePaths = backdrops.Distinct(StringComparer.OrdinalIgnoreCase)
  78. .ToList();
  79. }
  80. if (!artist.LockedFields.Contains(MetadataFields.Genres))
  81. {
  82. // Avoid implicitly captured closure
  83. var artist1 = artist;
  84. artist.Genres = allSongs.Where(i => i.HasArtist(artist1.Name))
  85. .SelectMany(i => i.Genres)
  86. .Distinct(StringComparer.OrdinalIgnoreCase)
  87. .ToList();
  88. }
  89. // Populate counts of items
  90. //SetItemCounts(artist, null, allItems.OfType<IHasArtist>());
  91. foreach (var lib in userLibraries)
  92. {
  93. SetItemCounts(artist, lib.Item1, lib.Item2);
  94. }
  95. numComplete++;
  96. double percent = numComplete;
  97. percent /= numArtists;
  98. percent *= 20;
  99. progress.Report(80 + percent);
  100. }
  101. progress.Report(100);
  102. }
  103. /// <summary>
  104. /// Sets the item counts.
  105. /// </summary>
  106. /// <param name="artist">The artist.</param>
  107. /// <param name="userId">The user id.</param>
  108. /// <param name="allItems">All items.</param>
  109. private void SetItemCounts(Artist artist, Guid? userId, IEnumerable<IHasArtist> allItems)
  110. {
  111. var name = artist.Name;
  112. var items = allItems
  113. .Where(i => i.HasArtist(name))
  114. .ToList();
  115. var counts = new ItemByNameCounts
  116. {
  117. TotalCount = items.Count,
  118. SongCount = items.OfType<Audio>().Count(),
  119. AlbumCount = items.OfType<MusicAlbum>().Count(),
  120. MusicVideoCount = items.OfType<MusicVideo>().Count()
  121. };
  122. if (userId.HasValue)
  123. {
  124. artist.UserItemCounts[userId.Value] = counts;
  125. }
  126. }
  127. /// <summary>
  128. /// Merges the images.
  129. /// </summary>
  130. /// <param name="source">The source.</param>
  131. /// <param name="target">The target.</param>
  132. private void MergeImages(Dictionary<ImageType, string> source, Dictionary<ImageType, string> target)
  133. {
  134. foreach (var key in source.Keys
  135. .Where(k => !target.ContainsKey(k)))
  136. {
  137. string path;
  138. if (source.TryGetValue(key, out path))
  139. {
  140. target[key] = path;
  141. }
  142. }
  143. }
  144. /// <summary>
  145. /// Gets all artists.
  146. /// </summary>
  147. /// <param name="allSongs">All songs.</param>
  148. /// <param name="cancellationToken">The cancellation token.</param>
  149. /// <param name="progress">The progress.</param>
  150. /// <returns>Task{Artist[]}.</returns>
  151. private async Task<List<Artist>> GetAllArtists(IEnumerable<Audio> allSongs, CancellationToken cancellationToken, IProgress<double> progress)
  152. {
  153. var allArtists = allSongs
  154. .SelectMany(i =>
  155. {
  156. var list = new List<string>();
  157. if (!string.IsNullOrEmpty(i.AlbumArtist))
  158. {
  159. list.Add(i.AlbumArtist);
  160. }
  161. list.AddRange(i.Artists);
  162. return list;
  163. })
  164. .Distinct(StringComparer.OrdinalIgnoreCase)
  165. .ToList();
  166. var returnArtists = new List<Artist>(allArtists.Count);
  167. var numComplete = 0;
  168. var numArtists = allArtists.Count;
  169. foreach (var artist in allArtists)
  170. {
  171. cancellationToken.ThrowIfCancellationRequested();
  172. try
  173. {
  174. var artistItem = _libraryManager.GetArtist(artist);
  175. await artistItem.RefreshMetadata(cancellationToken).ConfigureAwait(false);
  176. returnArtists.Add(artistItem);
  177. }
  178. catch (IOException ex)
  179. {
  180. _logger.ErrorException("Error validating Artist {0}", ex, artist);
  181. }
  182. // Update progress
  183. numComplete++;
  184. double percent = numComplete;
  185. percent /= numArtists;
  186. progress.Report(100 * percent);
  187. }
  188. return returnArtists;
  189. }
  190. }
  191. }