CleanDatabaseScheduledTask.cs 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  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 = 2;
  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. }
  60. private async Task UpdateToLatestSchema(CancellationToken cancellationToken, IProgress<double> progress)
  61. {
  62. var itemIds = _libraryManager.GetItemIds(new InternalItemsQuery
  63. {
  64. IsCurrentSchema = false,
  65. // These are constantly getting regenerated so don't bother with them here
  66. ExcludeItemTypes = new[] { typeof(LiveTvProgram).Name }
  67. });
  68. var numComplete = 0;
  69. var numItems = itemIds.Count;
  70. _logger.Debug("Upgrading schema for {0} items", numItems);
  71. foreach (var itemId in itemIds)
  72. {
  73. cancellationToken.ThrowIfCancellationRequested();
  74. if (itemId == Guid.Empty)
  75. {
  76. // Somehow some invalid data got into the db. It probably predates the boundary checking
  77. continue;
  78. }
  79. var item = _libraryManager.GetItemById(itemId);
  80. if (item != null)
  81. {
  82. try
  83. {
  84. await _itemRepo.SaveItem(item, cancellationToken).ConfigureAwait(false);
  85. }
  86. catch (OperationCanceledException)
  87. {
  88. throw;
  89. }
  90. catch (Exception ex)
  91. {
  92. _logger.ErrorException("Error saving item", ex);
  93. }
  94. }
  95. numComplete++;
  96. double percent = numComplete;
  97. percent /= numItems;
  98. progress.Report(percent * 100);
  99. }
  100. if (!_config.Configuration.DisableStartupScan)
  101. {
  102. _config.Configuration.DisableStartupScan = true;
  103. _config.SaveConfiguration();
  104. }
  105. if (_config.Configuration.MigrationVersion < MigrationVersion)
  106. {
  107. _config.Configuration.MigrationVersion = MigrationVersion;
  108. _config.SaveConfiguration();
  109. }
  110. progress.Report(100);
  111. }
  112. private async Task CleanDeadItems(CancellationToken cancellationToken, IProgress<double> progress)
  113. {
  114. var itemIds = _libraryManager.GetItemIds(new InternalItemsQuery
  115. {
  116. HasDeadParentId = true
  117. });
  118. var numComplete = 0;
  119. var numItems = itemIds.Count;
  120. _logger.Debug("Cleaning {0} items with dead parent links", numItems);
  121. foreach (var itemId in itemIds)
  122. {
  123. cancellationToken.ThrowIfCancellationRequested();
  124. var item = _libraryManager.GetItemById(itemId);
  125. if (item != null)
  126. {
  127. _logger.Debug("Cleaning item {0} type: {1} path: {2}", item.Name, item.GetType().Name, item.Path ?? string.Empty);
  128. await _libraryManager.DeleteItem(item, new DeleteOptions
  129. {
  130. DeleteFileLocation = false
  131. });
  132. }
  133. numComplete++;
  134. double percent = numComplete;
  135. percent /= numItems;
  136. progress.Report(percent * 100);
  137. }
  138. progress.Report(100);
  139. }
  140. private async Task CleanDeletedItems(CancellationToken cancellationToken, IProgress<double> progress)
  141. {
  142. var result = _itemRepo.GetItemIdsWithPath(new InternalItemsQuery
  143. {
  144. IsOffline = false,
  145. LocationType = LocationType.FileSystem,
  146. //Limit = limit,
  147. // These have their own cleanup routines
  148. ExcludeItemTypes = new[] { typeof(Person).Name, typeof(Genre).Name, typeof(MusicGenre).Name, typeof(GameGenre).Name, typeof(Studio).Name, typeof(Year).Name }
  149. });
  150. var numComplete = 0;
  151. var numItems = result.Items.Length;
  152. foreach (var item in result.Items)
  153. {
  154. cancellationToken.ThrowIfCancellationRequested();
  155. var path = item.Item2;
  156. try
  157. {
  158. if (_fileSystem.FileExists(path) || _fileSystem.DirectoryExists(path))
  159. {
  160. continue;
  161. }
  162. var libraryItem = _libraryManager.GetItemById(item.Item1);
  163. if (Folder.IsPathOffline(path))
  164. {
  165. libraryItem.IsOffline = true;
  166. await libraryItem.UpdateToRepository(ItemUpdateType.None, cancellationToken).ConfigureAwait(false);
  167. continue;
  168. }
  169. await _libraryManager.DeleteItem(libraryItem, new DeleteOptions
  170. {
  171. DeleteFileLocation = false
  172. });
  173. }
  174. catch (OperationCanceledException)
  175. {
  176. throw;
  177. }
  178. catch (Exception ex)
  179. {
  180. _logger.ErrorException("Error in CleanDeletedItems. File {0}", ex, path);
  181. }
  182. numComplete++;
  183. double percent = numComplete;
  184. percent /= numItems;
  185. progress.Report(percent * 100);
  186. }
  187. }
  188. public IEnumerable<ITaskTrigger> GetDefaultTriggers()
  189. {
  190. return new ITaskTrigger[]
  191. {
  192. new IntervalTrigger{ Interval = TimeSpan.FromHours(24)}
  193. };
  194. }
  195. }
  196. }