2
0

CleanDatabaseScheduledTask.cs 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  1. using MediaBrowser.Common.Progress;
  2. using MediaBrowser.Controller.Entities;
  3. using MediaBrowser.Controller.Library;
  4. using MediaBrowser.Controller.Persistence;
  5. using MediaBrowser.Model.Entities;
  6. using MediaBrowser.Model.Logging;
  7. using System;
  8. using System.Collections.Generic;
  9. using System.Linq;
  10. using System.Threading;
  11. using System.Threading.Tasks;
  12. using MediaBrowser.Common.Configuration;
  13. using MediaBrowser.Model.IO;
  14. using MediaBrowser.Controller.Channels;
  15. using MediaBrowser.Controller.Entities.Audio;
  16. using MediaBrowser.Model.Tasks;
  17. namespace Emby.Server.Implementations.Data
  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 IFileSystem _fileSystem;
  25. private readonly IApplicationPaths _appPaths;
  26. public CleanDatabaseScheduledTask(ILibraryManager libraryManager, IItemRepository itemRepo, ILogger logger, IFileSystem fileSystem, IApplicationPaths appPaths)
  27. {
  28. _libraryManager = libraryManager;
  29. _itemRepo = itemRepo;
  30. _logger = logger;
  31. _fileSystem = fileSystem;
  32. _appPaths = appPaths;
  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. // Ensure these objects are lazy loaded.
  49. // Without this there is a deadlock that will need to be investigated
  50. var rootChildren = _libraryManager.RootFolder.Children.ToList();
  51. rootChildren = _libraryManager.GetUserRootFolder().Children.ToList();
  52. var innerProgress = new ActionableProgress<double>();
  53. innerProgress.RegisterAction(p =>
  54. {
  55. double newPercentCommplete = .45 * p;
  56. progress.Report(newPercentCommplete);
  57. });
  58. await CleanDeadItems(cancellationToken, innerProgress).ConfigureAwait(false);
  59. progress.Report(45);
  60. innerProgress = new ActionableProgress<double>();
  61. innerProgress.RegisterAction(p =>
  62. {
  63. double newPercentCommplete = 45 + .55 * p;
  64. progress.Report(newPercentCommplete);
  65. });
  66. await CleanDeletedItems(cancellationToken, innerProgress).ConfigureAwait(false);
  67. progress.Report(100);
  68. await _itemRepo.UpdateInheritedValues(cancellationToken).ConfigureAwait(false);
  69. }
  70. private async Task CleanDeadItems(CancellationToken cancellationToken, IProgress<double> progress)
  71. {
  72. var itemIds = _libraryManager.GetItemIds(new InternalItemsQuery
  73. {
  74. HasDeadParentId = true
  75. });
  76. var numComplete = 0;
  77. var numItems = itemIds.Count;
  78. _logger.Debug("Cleaning {0} items with dead parent links", numItems);
  79. foreach (var itemId in itemIds)
  80. {
  81. cancellationToken.ThrowIfCancellationRequested();
  82. var item = _libraryManager.GetItemById(itemId);
  83. if (item != null)
  84. {
  85. _logger.Info("Cleaning item {0} type: {1} path: {2}", item.Name, item.GetType().Name, item.Path ?? string.Empty);
  86. await item.Delete(new DeleteOptions
  87. {
  88. DeleteFileLocation = false
  89. }).ConfigureAwait(false);
  90. }
  91. numComplete++;
  92. double percent = numComplete;
  93. percent /= numItems;
  94. progress.Report(percent * 100);
  95. }
  96. progress.Report(100);
  97. }
  98. private async Task CleanDeletedItems(CancellationToken cancellationToken, IProgress<double> progress)
  99. {
  100. var result = _itemRepo.GetItemIdsWithPath(new InternalItemsQuery
  101. {
  102. LocationTypes = new[] { LocationType.FileSystem },
  103. //Limit = limit,
  104. // These have their own cleanup routines
  105. ExcludeItemTypes = new[]
  106. {
  107. typeof(Person).Name,
  108. typeof(Genre).Name,
  109. typeof(MusicGenre).Name,
  110. typeof(GameGenre).Name,
  111. typeof(Studio).Name,
  112. typeof(Year).Name,
  113. typeof(Channel).Name,
  114. typeof(AggregateFolder).Name,
  115. typeof(CollectionFolder).Name
  116. }
  117. });
  118. var numComplete = 0;
  119. var numItems = result.Count;
  120. var allLibraryPaths = _libraryManager
  121. .GetVirtualFolders()
  122. .SelectMany(i => i.Locations)
  123. .ToList();
  124. foreach (var item in result)
  125. {
  126. cancellationToken.ThrowIfCancellationRequested();
  127. var path = item.Item2;
  128. try
  129. {
  130. var isPathInLibrary = false;
  131. if (allLibraryPaths.Any(i => path.StartsWith(i, StringComparison.Ordinal)) ||
  132. allLibraryPaths.Contains(path, StringComparer.Ordinal) ||
  133. path.StartsWith(_appPaths.ProgramDataPath, StringComparison.Ordinal))
  134. {
  135. isPathInLibrary = true;
  136. if (_fileSystem.FileExists(path) || _fileSystem.DirectoryExists(path))
  137. {
  138. continue;
  139. }
  140. }
  141. var libraryItem = _libraryManager.GetItemById(item.Item1);
  142. if (libraryItem == null)
  143. {
  144. continue;
  145. }
  146. if (libraryItem.IsTopParent)
  147. {
  148. continue;
  149. }
  150. var hasDualAccess = libraryItem as IHasDualAccess;
  151. if (hasDualAccess != null && hasDualAccess.IsAccessedByName)
  152. {
  153. continue;
  154. }
  155. var libraryItemPath = libraryItem.Path;
  156. if (!string.Equals(libraryItemPath, path, StringComparison.OrdinalIgnoreCase))
  157. {
  158. _logger.Error("CleanDeletedItems aborting delete for item {0}-{1} because paths don't match. {2}---{3}", libraryItem.Id, libraryItem.Name, libraryItem.Path ?? string.Empty, path ?? string.Empty);
  159. continue;
  160. }
  161. if (Folder.IsPathOffline(path, allLibraryPaths))
  162. {
  163. continue;
  164. }
  165. if (isPathInLibrary)
  166. {
  167. _logger.Info("Deleting item from database {0} because path no longer exists. type: {1} path: {2}", libraryItem.Name, libraryItem.GetType().Name, libraryItemPath ?? string.Empty);
  168. }
  169. else
  170. {
  171. _logger.Info("Deleting item from database {0} because path is no longer in the server library. type: {1} path: {2}", libraryItem.Name, libraryItem.GetType().Name, libraryItemPath ?? string.Empty);
  172. }
  173. await libraryItem.OnFileDeleted().ConfigureAwait(false);
  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. /// <summary>
  190. /// Creates the triggers that define when the task will run
  191. /// </summary>
  192. /// <returns>IEnumerable{BaseTaskTrigger}.</returns>
  193. public IEnumerable<TaskTriggerInfo> GetDefaultTriggers()
  194. {
  195. return new[] {
  196. // Every so often
  197. new TaskTriggerInfo { Type = TaskTriggerInfo.TriggerInterval, IntervalTicks = TimeSpan.FromHours(24).Ticks}
  198. };
  199. }
  200. public string Key
  201. {
  202. get { return "CleanDatabase"; }
  203. }
  204. }
  205. }