ArtistsValidator.cs 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  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 additionalBackdrops = musicArtist
  76. .BackdropImagePaths
  77. .Except(artist.BackdropImagePaths)
  78. .ToList();
  79. var sources = additionalBackdrops
  80. .Select(musicArtist.GetImageSourceInfo)
  81. .ToList();
  82. foreach (var path in additionalBackdrops)
  83. {
  84. artist.RemoveImageSourceForPath(path);
  85. }
  86. artist.BackdropImagePaths.AddRange(additionalBackdrops);
  87. artist.ImageSources.AddRange(sources);
  88. }
  89. if (!artist.LockedFields.Contains(MetadataFields.Genres))
  90. {
  91. // Avoid implicitly captured closure
  92. var artist1 = artist;
  93. artist.Genres = allSongs.Where(i => i.HasArtist(artist1.Name))
  94. .SelectMany(i => i.Genres)
  95. .Distinct(StringComparer.OrdinalIgnoreCase)
  96. .ToList();
  97. }
  98. // Populate counts of items
  99. //SetItemCounts(artist, null, allItems.OfType<IHasArtist>());
  100. foreach (var lib in userLibraries)
  101. {
  102. SetItemCounts(artist, lib.Item1, lib.Item2);
  103. }
  104. numComplete++;
  105. double percent = numComplete;
  106. percent /= numArtists;
  107. percent *= 20;
  108. progress.Report(80 + percent);
  109. }
  110. progress.Report(100);
  111. }
  112. /// <summary>
  113. /// Sets the item counts.
  114. /// </summary>
  115. /// <param name="artist">The artist.</param>
  116. /// <param name="userId">The user id.</param>
  117. /// <param name="allItems">All items.</param>
  118. private void SetItemCounts(Artist artist, Guid? userId, IEnumerable<IHasArtist> allItems)
  119. {
  120. var name = artist.Name;
  121. var items = allItems
  122. .Where(i => i.HasArtist(name))
  123. .ToList();
  124. var counts = new ItemByNameCounts
  125. {
  126. TotalCount = items.Count,
  127. SongCount = items.OfType<Audio>().Count(),
  128. AlbumCount = items.OfType<MusicAlbum>().Count(),
  129. MusicVideoCount = items.OfType<MusicVideo>().Count()
  130. };
  131. if (userId.HasValue)
  132. {
  133. artist.UserItemCounts[userId.Value] = counts;
  134. }
  135. }
  136. /// <summary>
  137. /// Merges the images.
  138. /// </summary>
  139. /// <param name="source">The source.</param>
  140. /// <param name="target">The target.</param>
  141. private void MergeImages(Dictionary<ImageType, string> source, Dictionary<ImageType, string> target)
  142. {
  143. foreach (var key in source.Keys
  144. .Where(k => !target.ContainsKey(k)))
  145. {
  146. string path;
  147. if (source.TryGetValue(key, out path))
  148. {
  149. target[key] = path;
  150. }
  151. }
  152. }
  153. /// <summary>
  154. /// Gets all artists.
  155. /// </summary>
  156. /// <param name="allSongs">All songs.</param>
  157. /// <param name="cancellationToken">The cancellation token.</param>
  158. /// <param name="progress">The progress.</param>
  159. /// <returns>Task{Artist[]}.</returns>
  160. private async Task<List<Artist>> GetAllArtists(IEnumerable<Audio> allSongs, CancellationToken cancellationToken, IProgress<double> progress)
  161. {
  162. var allArtists = allSongs
  163. .SelectMany(i =>
  164. {
  165. var list = new List<string>();
  166. if (!string.IsNullOrEmpty(i.AlbumArtist))
  167. {
  168. list.Add(i.AlbumArtist);
  169. }
  170. list.AddRange(i.Artists);
  171. return list;
  172. })
  173. .Distinct(StringComparer.OrdinalIgnoreCase)
  174. .ToList();
  175. var returnArtists = new List<Artist>(allArtists.Count);
  176. var numComplete = 0;
  177. var numArtists = allArtists.Count;
  178. foreach (var artist in allArtists)
  179. {
  180. cancellationToken.ThrowIfCancellationRequested();
  181. try
  182. {
  183. var artistItem = _libraryManager.GetArtist(artist);
  184. await artistItem.RefreshMetadata(cancellationToken).ConfigureAwait(false);
  185. returnArtists.Add(artistItem);
  186. }
  187. catch (IOException ex)
  188. {
  189. _logger.ErrorException("Error validating Artist {0}", ex, artist);
  190. }
  191. // Update progress
  192. numComplete++;
  193. double percent = numComplete;
  194. percent /= numArtists;
  195. progress.Report(100 * percent);
  196. }
  197. return returnArtists;
  198. }
  199. }
  200. }