CleanDatabaseScheduledTask.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  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.Persistence;
  7. using MediaBrowser.Model.Entities;
  8. using MediaBrowser.Model.Logging;
  9. using System;
  10. using System.Collections.Generic;
  11. using System.Globalization;
  12. using System.Linq;
  13. using System.Threading;
  14. using System.Threading.Tasks;
  15. using CommonIO;
  16. using MediaBrowser.Controller.Channels;
  17. using MediaBrowser.Controller.Entities.Audio;
  18. using MediaBrowser.Controller.Localization;
  19. using MediaBrowser.Controller.Net;
  20. using MediaBrowser.Server.Implementations.ScheduledTasks;
  21. namespace MediaBrowser.Server.Implementations.Persistence
  22. {
  23. public class CleanDatabaseScheduledTask : IScheduledTask
  24. {
  25. private readonly ILibraryManager _libraryManager;
  26. private readonly IItemRepository _itemRepo;
  27. private readonly ILogger _logger;
  28. private readonly IServerConfigurationManager _config;
  29. private readonly IFileSystem _fileSystem;
  30. private readonly IHttpServer _httpServer;
  31. private readonly ILocalizationManager _localization;
  32. private readonly ITaskManager _taskManager;
  33. public const int MigrationVersion = 23;
  34. public static bool EnableUnavailableMessage = false;
  35. public CleanDatabaseScheduledTask(ILibraryManager libraryManager, IItemRepository itemRepo, ILogger logger, IServerConfigurationManager config, IFileSystem fileSystem, IHttpServer httpServer, ILocalizationManager localization, ITaskManager taskManager)
  36. {
  37. _libraryManager = libraryManager;
  38. _itemRepo = itemRepo;
  39. _logger = logger;
  40. _config = config;
  41. _fileSystem = fileSystem;
  42. _httpServer = httpServer;
  43. _localization = localization;
  44. _taskManager = taskManager;
  45. }
  46. public string Name
  47. {
  48. get { return "Clean Database"; }
  49. }
  50. public string Description
  51. {
  52. get { return "Deletes obsolete content from the database."; }
  53. }
  54. public string Category
  55. {
  56. get { return "Library"; }
  57. }
  58. public async Task Execute(CancellationToken cancellationToken, IProgress<double> progress)
  59. {
  60. OnProgress(0);
  61. // Ensure these objects are lazy loaded.
  62. // Without this there is a deadlock that will need to be investigated
  63. var rootChildren = _libraryManager.RootFolder.Children.ToList();
  64. rootChildren = _libraryManager.GetUserRootFolder().Children.ToList();
  65. var innerProgress = new ActionableProgress<double>();
  66. innerProgress.RegisterAction(p =>
  67. {
  68. double newPercentCommplete = .4 * p;
  69. OnProgress(newPercentCommplete);
  70. progress.Report(newPercentCommplete);
  71. });
  72. await UpdateToLatestSchema(cancellationToken, innerProgress).ConfigureAwait(false);
  73. innerProgress = new ActionableProgress<double>();
  74. innerProgress.RegisterAction(p =>
  75. {
  76. double newPercentCommplete = 40 + .05 * p;
  77. OnProgress(newPercentCommplete);
  78. progress.Report(newPercentCommplete);
  79. });
  80. await CleanDeadItems(cancellationToken, innerProgress).ConfigureAwait(false);
  81. progress.Report(45);
  82. innerProgress = new ActionableProgress<double>();
  83. innerProgress.RegisterAction(p =>
  84. {
  85. double newPercentCommplete = 45 + .55 * p;
  86. OnProgress(newPercentCommplete);
  87. progress.Report(newPercentCommplete);
  88. });
  89. await CleanDeletedItems(cancellationToken, innerProgress).ConfigureAwait(false);
  90. progress.Report(100);
  91. await _itemRepo.UpdateInheritedValues(cancellationToken).ConfigureAwait(false);
  92. if (_config.Configuration.MigrationVersion < MigrationVersion)
  93. {
  94. _config.Configuration.MigrationVersion = MigrationVersion;
  95. _config.SaveConfiguration();
  96. }
  97. if (EnableUnavailableMessage)
  98. {
  99. EnableUnavailableMessage = false;
  100. _httpServer.GlobalResponse = null;
  101. _taskManager.QueueScheduledTask<RefreshMediaLibraryTask>();
  102. }
  103. _taskManager.SuspendTriggers = false;
  104. }
  105. private void OnProgress(double newPercentCommplete)
  106. {
  107. if (EnableUnavailableMessage)
  108. {
  109. var html = "<!doctype html><html><head><title>Emby</title></head><body>";
  110. var text = _localization.GetLocalizedString("DbUpgradeMessage");
  111. html += string.Format(text, newPercentCommplete.ToString("N2", CultureInfo.InvariantCulture));
  112. html += "<script>setTimeout(function(){window.location.reload(true);}, 5000);</script>";
  113. html += "</body></html>";
  114. _httpServer.GlobalResponse = html;
  115. }
  116. }
  117. private async Task UpdateToLatestSchema(CancellationToken cancellationToken, IProgress<double> progress)
  118. {
  119. var itemIds = _libraryManager.GetItemIds(new InternalItemsQuery
  120. {
  121. IsCurrentSchema = false
  122. });
  123. var numComplete = 0;
  124. var numItems = itemIds.Count;
  125. _logger.Debug("Upgrading schema for {0} items", numItems);
  126. foreach (var itemId in itemIds)
  127. {
  128. cancellationToken.ThrowIfCancellationRequested();
  129. if (itemId != Guid.Empty)
  130. {
  131. // Somehow some invalid data got into the db. It probably predates the boundary checking
  132. var item = _libraryManager.GetItemById(itemId);
  133. if (item != null)
  134. {
  135. try
  136. {
  137. await _itemRepo.SaveItem(item, cancellationToken).ConfigureAwait(false);
  138. }
  139. catch (OperationCanceledException)
  140. {
  141. throw;
  142. }
  143. catch (Exception ex)
  144. {
  145. _logger.ErrorException("Error saving item", ex);
  146. }
  147. }
  148. }
  149. numComplete++;
  150. double percent = numComplete;
  151. percent /= numItems;
  152. progress.Report(percent * 100);
  153. }
  154. progress.Report(100);
  155. }
  156. private async Task CleanDeadItems(CancellationToken cancellationToken, IProgress<double> progress)
  157. {
  158. var itemIds = _libraryManager.GetItemIds(new InternalItemsQuery
  159. {
  160. HasDeadParentId = true
  161. });
  162. var numComplete = 0;
  163. var numItems = itemIds.Count;
  164. _logger.Debug("Cleaning {0} items with dead parent links", numItems);
  165. foreach (var itemId in itemIds)
  166. {
  167. cancellationToken.ThrowIfCancellationRequested();
  168. var item = _libraryManager.GetItemById(itemId);
  169. if (item != null)
  170. {
  171. _logger.Info("Cleaning item {0} type: {1} path: {2}", item.Name, item.GetType().Name, item.Path ?? string.Empty);
  172. await item.Delete(new DeleteOptions
  173. {
  174. DeleteFileLocation = false
  175. }).ConfigureAwait(false);
  176. }
  177. numComplete++;
  178. double percent = numComplete;
  179. percent /= numItems;
  180. progress.Report(percent * 100);
  181. }
  182. progress.Report(100);
  183. }
  184. private async Task CleanDeletedItems(CancellationToken cancellationToken, IProgress<double> progress)
  185. {
  186. var result = _itemRepo.GetItemIdsWithPath(new InternalItemsQuery
  187. {
  188. LocationTypes = new[] { LocationType.FileSystem },
  189. //Limit = limit,
  190. // These have their own cleanup routines
  191. ExcludeItemTypes = new[]
  192. {
  193. typeof(Person).Name,
  194. typeof(Genre).Name,
  195. typeof(MusicGenre).Name,
  196. typeof(GameGenre).Name,
  197. typeof(Studio).Name,
  198. typeof(Year).Name,
  199. typeof(Channel).Name,
  200. typeof(AggregateFolder).Name,
  201. typeof(CollectionFolder).Name
  202. }
  203. });
  204. var numComplete = 0;
  205. var numItems = result.Items.Length;
  206. foreach (var item in result.Items)
  207. {
  208. cancellationToken.ThrowIfCancellationRequested();
  209. var path = item.Item2;
  210. try
  211. {
  212. if (_fileSystem.FileExists(path) || _fileSystem.DirectoryExists(path))
  213. {
  214. continue;
  215. }
  216. var libraryItem = _libraryManager.GetItemById(item.Item1);
  217. if (libraryItem.IsTopParent)
  218. {
  219. continue;
  220. }
  221. var hasDualAccess = libraryItem as IHasDualAccess;
  222. if (hasDualAccess != null && hasDualAccess.IsAccessedByName)
  223. {
  224. continue;
  225. }
  226. var libraryItemPath = libraryItem.Path;
  227. if (!string.Equals(libraryItemPath, path, StringComparison.OrdinalIgnoreCase))
  228. {
  229. _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);
  230. continue;
  231. }
  232. if (Folder.IsPathOffline(path))
  233. {
  234. libraryItem.IsOffline = true;
  235. await libraryItem.UpdateToRepository(ItemUpdateType.None, cancellationToken).ConfigureAwait(false);
  236. continue;
  237. }
  238. _logger.Info("Deleting item from database {0} because path no longer exists. type: {1} path: {2}", libraryItem.Name, libraryItem.GetType().Name, libraryItemPath ?? string.Empty);
  239. await libraryItem.OnFileDeleted().ConfigureAwait(false);
  240. }
  241. catch (OperationCanceledException)
  242. {
  243. throw;
  244. }
  245. catch (Exception ex)
  246. {
  247. _logger.ErrorException("Error in CleanDeletedItems. File {0}", ex, path);
  248. }
  249. numComplete++;
  250. double percent = numComplete;
  251. percent /= numItems;
  252. progress.Report(percent * 100);
  253. }
  254. }
  255. public IEnumerable<ITaskTrigger> GetDefaultTriggers()
  256. {
  257. return new ITaskTrigger[]
  258. {
  259. new IntervalTrigger{ Interval = TimeSpan.FromHours(24)}
  260. };
  261. }
  262. }
  263. }