StudiosValidator.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. using MediaBrowser.Controller.Entities;
  2. using MediaBrowser.Controller.Library;
  3. using MediaBrowser.Model.Logging;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. using System.Threading;
  8. using System.Threading.Tasks;
  9. namespace MediaBrowser.Server.Implementations.Library.Validators
  10. {
  11. class StudiosValidator
  12. {
  13. /// <summary>
  14. /// The _library manager
  15. /// </summary>
  16. private readonly ILibraryManager _libraryManager;
  17. /// <summary>
  18. /// The _logger
  19. /// </summary>
  20. private readonly ILogger _logger;
  21. public StudiosValidator(ILibraryManager libraryManager, ILogger logger)
  22. {
  23. _libraryManager = libraryManager;
  24. _logger = logger;
  25. }
  26. /// <summary>
  27. /// Runs the specified progress.
  28. /// </summary>
  29. /// <param name="progress">The progress.</param>
  30. /// <param name="cancellationToken">The cancellation token.</param>
  31. /// <returns>Task.</returns>
  32. public async Task Run(IProgress<double> progress, CancellationToken cancellationToken)
  33. {
  34. var items = _libraryManager.RootFolder.GetRecursiveChildren()
  35. .SelectMany(i => i.Studios)
  36. .DistinctNames()
  37. .ToList();
  38. var numComplete = 0;
  39. var count = items.Count;
  40. var validIds = new List<Guid>();
  41. foreach (var name in items)
  42. {
  43. try
  44. {
  45. var itemByName = _libraryManager.GetStudio(name);
  46. validIds.Add(itemByName.Id);
  47. await itemByName.RefreshMetadata(cancellationToken).ConfigureAwait(false);
  48. }
  49. catch (OperationCanceledException)
  50. {
  51. // Don't clutter the log
  52. break;
  53. }
  54. catch (Exception ex)
  55. {
  56. _logger.ErrorException("Error refreshing {0}", ex, name);
  57. }
  58. numComplete++;
  59. double percent = numComplete;
  60. percent /= count;
  61. percent *= 100;
  62. progress.Report(percent);
  63. }
  64. var allIds = _libraryManager.GetItemIds(new InternalItemsQuery
  65. {
  66. IncludeItemTypes = new[] { typeof(Studio).Name }
  67. });
  68. var invalidIds = allIds
  69. .Except(validIds)
  70. .ToList();
  71. foreach (var id in invalidIds)
  72. {
  73. cancellationToken.ThrowIfCancellationRequested();
  74. var item = _libraryManager.GetItemById(id);
  75. await _libraryManager.DeleteItem(item, new DeleteOptions
  76. {
  77. DeleteFileLocation = false
  78. }).ConfigureAwait(false);
  79. }
  80. progress.Report(100);
  81. }
  82. }
  83. }