CleanDatabaseScheduledTask.cs 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  1. using MediaBrowser.Common.Progress;
  2. using MediaBrowser.Common.ScheduledTasks;
  3. using MediaBrowser.Controller.Configuration;
  4. using MediaBrowser.Controller.Entities;
  5. using MediaBrowser.Controller.Library;
  6. using MediaBrowser.Controller.LiveTv;
  7. using MediaBrowser.Controller.Persistence;
  8. using MediaBrowser.Model.Entities;
  9. using MediaBrowser.Model.Logging;
  10. using System;
  11. using System.Collections.Generic;
  12. using System.Threading;
  13. using System.Threading.Tasks;
  14. using CommonIO;
  15. using MediaBrowser.Controller.Entities.Audio;
  16. namespace MediaBrowser.Server.Implementations.Persistence
  17. {
  18. public class CleanDatabaseScheduledTask : IScheduledTask
  19. {
  20. private readonly ILibraryManager _libraryManager;
  21. private readonly IItemRepository _itemRepo;
  22. private readonly ILogger _logger;
  23. private readonly IServerConfigurationManager _config;
  24. private readonly IFileSystem _fileSystem;
  25. public const int MigrationVersion = 4;
  26. public CleanDatabaseScheduledTask(ILibraryManager libraryManager, IItemRepository itemRepo, ILogger logger, IServerConfigurationManager config, IFileSystem fileSystem)
  27. {
  28. _libraryManager = libraryManager;
  29. _itemRepo = itemRepo;
  30. _logger = logger;
  31. _config = config;
  32. _fileSystem = fileSystem;
  33. }
  34. public string Name
  35. {
  36. get { return "Clean Database"; }
  37. }
  38. public string Description
  39. {
  40. get { return "Deletes obsolete content from the database."; }
  41. }
  42. public string Category
  43. {
  44. get { return "Library"; }
  45. }
  46. public async Task Execute(CancellationToken cancellationToken, IProgress<double> progress)
  47. {
  48. var innerProgress = new ActionableProgress<double>();
  49. innerProgress.RegisterAction(p => progress.Report(.4 * p));
  50. await UpdateToLatestSchema(cancellationToken, innerProgress).ConfigureAwait(false);
  51. innerProgress = new ActionableProgress<double>();
  52. innerProgress.RegisterAction(p => progress.Report(40 + (.05 * p)));
  53. await CleanDeadItems(cancellationToken, innerProgress).ConfigureAwait(false);
  54. progress.Report(45);
  55. innerProgress = new ActionableProgress<double>();
  56. innerProgress.RegisterAction(p => progress.Report(45 + (.55 * p)));
  57. await CleanDeletedItems(cancellationToken, innerProgress).ConfigureAwait(false);
  58. progress.Report(100);
  59. await _itemRepo.UpdateInheritedValues(cancellationToken).ConfigureAwait(false);
  60. }
  61. private async Task UpdateToLatestSchema(CancellationToken cancellationToken, IProgress<double> progress)
  62. {
  63. var itemIds = _libraryManager.GetItemIds(new InternalItemsQuery
  64. {
  65. IsCurrentSchema = false,
  66. // These are constantly getting regenerated so don't bother with them here
  67. ExcludeItemTypes = new[] { typeof(LiveTvProgram).Name }
  68. });
  69. var numComplete = 0;
  70. var numItems = itemIds.Count;
  71. _logger.Debug("Upgrading schema for {0} items", numItems);
  72. foreach (var itemId in itemIds)
  73. {
  74. cancellationToken.ThrowIfCancellationRequested();
  75. if (itemId == Guid.Empty)
  76. {
  77. // Somehow some invalid data got into the db. It probably predates the boundary checking
  78. continue;
  79. }
  80. var item = _libraryManager.GetItemById(itemId);
  81. if (item != null)
  82. {
  83. try
  84. {
  85. await _itemRepo.SaveItem(item, cancellationToken).ConfigureAwait(false);
  86. }
  87. catch (OperationCanceledException)
  88. {
  89. throw;
  90. }
  91. catch (Exception ex)
  92. {
  93. _logger.ErrorException("Error saving item", ex);
  94. }
  95. }
  96. numComplete++;
  97. double percent = numComplete;
  98. percent /= numItems;
  99. progress.Report(percent * 100);
  100. }
  101. if (!_config.Configuration.DisableStartupScan)
  102. {
  103. _config.Configuration.DisableStartupScan = true;
  104. _config.SaveConfiguration();
  105. }
  106. if (_config.Configuration.MigrationVersion < MigrationVersion)
  107. {
  108. _config.Configuration.MigrationVersion = MigrationVersion;
  109. _config.SaveConfiguration();
  110. }
  111. progress.Report(100);
  112. }
  113. private async Task CleanDeadItems(CancellationToken cancellationToken, IProgress<double> progress)
  114. {
  115. var itemIds = _libraryManager.GetItemIds(new InternalItemsQuery
  116. {
  117. HasDeadParentId = true
  118. });
  119. var numComplete = 0;
  120. var numItems = itemIds.Count;
  121. _logger.Debug("Cleaning {0} items with dead parent links", numItems);
  122. foreach (var itemId in itemIds)
  123. {
  124. cancellationToken.ThrowIfCancellationRequested();
  125. var item = _libraryManager.GetItemById(itemId);
  126. if (item != null)
  127. {
  128. _logger.Debug("Cleaning item {0} type: {1} path: {2}", item.Name, item.GetType().Name, item.Path ?? string.Empty);
  129. await _libraryManager.DeleteItem(item, new DeleteOptions
  130. {
  131. DeleteFileLocation = false
  132. });
  133. }
  134. numComplete++;
  135. double percent = numComplete;
  136. percent /= numItems;
  137. progress.Report(percent * 100);
  138. }
  139. progress.Report(100);
  140. }
  141. private async Task CleanDeletedItems(CancellationToken cancellationToken, IProgress<double> progress)
  142. {
  143. var result = _itemRepo.GetItemIdsWithPath(new InternalItemsQuery
  144. {
  145. IsOffline = false,
  146. LocationType = LocationType.FileSystem,
  147. //Limit = limit,
  148. // These have their own cleanup routines
  149. ExcludeItemTypes = new[] { typeof(Person).Name, typeof(Genre).Name, typeof(MusicGenre).Name, typeof(GameGenre).Name, typeof(Studio).Name, typeof(Year).Name }
  150. });
  151. var numComplete = 0;
  152. var numItems = result.Items.Length;
  153. foreach (var item in result.Items)
  154. {
  155. cancellationToken.ThrowIfCancellationRequested();
  156. var path = item.Item2;
  157. try
  158. {
  159. if (_fileSystem.FileExists(path) || _fileSystem.DirectoryExists(path))
  160. {
  161. continue;
  162. }
  163. var libraryItem = _libraryManager.GetItemById(item.Item1);
  164. if (Folder.IsPathOffline(path))
  165. {
  166. libraryItem.IsOffline = true;
  167. await libraryItem.UpdateToRepository(ItemUpdateType.None, cancellationToken).ConfigureAwait(false);
  168. continue;
  169. }
  170. await _libraryManager.DeleteItem(libraryItem, new DeleteOptions
  171. {
  172. DeleteFileLocation = false
  173. });
  174. }
  175. catch (OperationCanceledException)
  176. {
  177. throw;
  178. }
  179. catch (Exception ex)
  180. {
  181. _logger.ErrorException("Error in CleanDeletedItems. File {0}", ex, path);
  182. }
  183. numComplete++;
  184. double percent = numComplete;
  185. percent /= numItems;
  186. progress.Report(percent * 100);
  187. }
  188. }
  189. public IEnumerable<ITaskTrigger> GetDefaultTriggers()
  190. {
  191. return new ITaskTrigger[]
  192. {
  193. new IntervalTrigger{ Interval = TimeSpan.FromHours(24)}
  194. };
  195. }
  196. }
  197. }