CleanDatabaseScheduledTask.cs 9.7 KB

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