CleanDatabaseScheduledTask.cs 8.4 KB

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