ArtistsValidator.cs 8.1 KB

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