CleanDatabaseScheduledTask.cs 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  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.DisableStartupScan)
  103. {
  104. _config.Configuration.DisableStartupScan = true;
  105. _config.SaveConfiguration();
  106. }
  107. if (_config.Configuration.MigrationVersion < MigrationVersion)
  108. {
  109. _config.Configuration.MigrationVersion = MigrationVersion;
  110. _config.SaveConfiguration();
  111. }
  112. progress.Report(100);
  113. }
  114. private async Task CleanDeadItems(CancellationToken cancellationToken, IProgress<double> progress)
  115. {
  116. var itemIds = _libraryManager.GetItemIds(new InternalItemsQuery
  117. {
  118. HasDeadParentId = true
  119. });
  120. var numComplete = 0;
  121. var numItems = itemIds.Count;
  122. _logger.Debug("Cleaning {0} items with dead parent links", numItems);
  123. foreach (var itemId in itemIds)
  124. {
  125. cancellationToken.ThrowIfCancellationRequested();
  126. var item = _libraryManager.GetItemById(itemId);
  127. if (item != null)
  128. {
  129. _logger.Debug("Cleaning item {0} type: {1} path: {2}", item.Name, item.GetType().Name, item.Path ?? string.Empty);
  130. await _libraryManager.DeleteItem(item, new DeleteOptions
  131. {
  132. DeleteFileLocation = false
  133. });
  134. }
  135. numComplete++;
  136. double percent = numComplete;
  137. percent /= numItems;
  138. progress.Report(percent * 100);
  139. }
  140. progress.Report(100);
  141. }
  142. private async Task CleanDeletedItems(CancellationToken cancellationToken, IProgress<double> progress)
  143. {
  144. var result = _itemRepo.GetItemIdsWithPath(new InternalItemsQuery
  145. {
  146. IsOffline = false,
  147. LocationType = LocationType.FileSystem,
  148. //Limit = limit,
  149. // These have their own cleanup routines
  150. ExcludeItemTypes = new[] { typeof(Person).Name, typeof(Genre).Name, typeof(MusicGenre).Name, typeof(GameGenre).Name, typeof(Studio).Name, typeof(Year).Name, typeof(Channel).Name }
  151. });
  152. var numComplete = 0;
  153. var numItems = result.Items.Length;
  154. foreach (var item in result.Items)
  155. {
  156. cancellationToken.ThrowIfCancellationRequested();
  157. var path = item.Item2;
  158. try
  159. {
  160. if (_fileSystem.FileExists(path) || _fileSystem.DirectoryExists(path))
  161. {
  162. continue;
  163. }
  164. var libraryItem = _libraryManager.GetItemById(item.Item1);
  165. if (Folder.IsPathOffline(path))
  166. {
  167. libraryItem.IsOffline = true;
  168. await libraryItem.UpdateToRepository(ItemUpdateType.None, cancellationToken).ConfigureAwait(false);
  169. continue;
  170. }
  171. await _libraryManager.DeleteItem(libraryItem, new DeleteOptions
  172. {
  173. DeleteFileLocation = false
  174. });
  175. }
  176. catch (OperationCanceledException)
  177. {
  178. throw;
  179. }
  180. catch (Exception ex)
  181. {
  182. _logger.ErrorException("Error in CleanDeletedItems. File {0}", ex, path);
  183. }
  184. numComplete++;
  185. double percent = numComplete;
  186. percent /= numItems;
  187. progress.Report(percent * 100);
  188. }
  189. }
  190. public IEnumerable<ITaskTrigger> GetDefaultTriggers()
  191. {
  192. return new ITaskTrigger[]
  193. {
  194. new IntervalTrigger{ Interval = TimeSpan.FromHours(24)}
  195. };
  196. }
  197. }
  198. }