CleanDatabaseScheduledTask.cs 8.4 KB

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