CleanDatabaseScheduledTask.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  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. OnProgress(newPercentCommplete);
  62. progress.Report(newPercentCommplete);
  63. });
  64. await UpdateToLatestSchema(cancellationToken, innerProgress).ConfigureAwait(false);
  65. innerProgress = new ActionableProgress<double>();
  66. innerProgress.RegisterAction(p =>
  67. {
  68. double newPercentCommplete = 40 + (.05 * p);
  69. OnProgress(newPercentCommplete);
  70. progress.Report(newPercentCommplete);
  71. });
  72. await CleanDeadItems(cancellationToken, innerProgress).ConfigureAwait(false);
  73. progress.Report(45);
  74. innerProgress = new ActionableProgress<double>();
  75. innerProgress.RegisterAction(p =>
  76. {
  77. double newPercentCommplete = 45 + (.55 * p);
  78. OnProgress(newPercentCommplete);
  79. progress.Report(newPercentCommplete);
  80. });
  81. await CleanDeletedItems(cancellationToken, innerProgress).ConfigureAwait(false);
  82. progress.Report(100);
  83. await _itemRepo.UpdateInheritedValues(cancellationToken).ConfigureAwait(false);
  84. if (EnableUnavailableMessage)
  85. {
  86. EnableUnavailableMessage = false;
  87. _httpServer.GlobalResponse = null;
  88. }
  89. }
  90. private void OnProgress(double newPercentCommplete)
  91. {
  92. if (EnableUnavailableMessage)
  93. {
  94. var html = "<!doctype html><html><head><title>Emby</title></head><body>";
  95. var text = _localization.GetLocalizedString("DbUpgradeMessage");
  96. html += string.Format(text, newPercentCommplete.ToString("N2", CultureInfo.InvariantCulture));
  97. html += "<script>setTimeout(function(){window.location.reload(true);}, 5000);</script>";
  98. html += "</body></html>";
  99. _httpServer.GlobalResponse = html;
  100. }
  101. }
  102. private async Task UpdateToLatestSchema(CancellationToken cancellationToken, IProgress<double> progress)
  103. {
  104. var itemIds = _libraryManager.GetItemIds(new InternalItemsQuery
  105. {
  106. IsCurrentSchema = false
  107. });
  108. var numComplete = 0;
  109. var numItems = itemIds.Count;
  110. _logger.Debug("Upgrading schema for {0} items", numItems);
  111. foreach (var itemId in itemIds)
  112. {
  113. cancellationToken.ThrowIfCancellationRequested();
  114. if (itemId != Guid.Empty)
  115. {
  116. // Somehow some invalid data got into the db. It probably predates the boundary checking
  117. var item = _libraryManager.GetItemById(itemId);
  118. if (item != null)
  119. {
  120. try
  121. {
  122. await _itemRepo.SaveItem(item, cancellationToken).ConfigureAwait(false);
  123. }
  124. catch (OperationCanceledException)
  125. {
  126. throw;
  127. }
  128. catch (Exception ex)
  129. {
  130. _logger.ErrorException("Error saving item", ex);
  131. }
  132. }
  133. }
  134. numComplete++;
  135. double percent = numComplete;
  136. percent /= numItems;
  137. progress.Report(percent * 100);
  138. }
  139. if (_config.Configuration.MigrationVersion < MigrationVersion)
  140. {
  141. _config.Configuration.MigrationVersion = MigrationVersion;
  142. _config.SaveConfiguration();
  143. }
  144. progress.Report(100);
  145. }
  146. private async Task CleanDeadItems(CancellationToken cancellationToken, IProgress<double> progress)
  147. {
  148. var itemIds = _libraryManager.GetItemIds(new InternalItemsQuery
  149. {
  150. HasDeadParentId = true
  151. });
  152. var numComplete = 0;
  153. var numItems = itemIds.Count;
  154. _logger.Debug("Cleaning {0} items with dead parent links", numItems);
  155. foreach (var itemId in itemIds)
  156. {
  157. cancellationToken.ThrowIfCancellationRequested();
  158. var item = _libraryManager.GetItemById(itemId);
  159. if (item != null)
  160. {
  161. _logger.Info("Cleaning item {0} type: {1} path: {2}", item.Name, item.GetType().Name, item.Path ?? string.Empty);
  162. await _libraryManager.DeleteItem(item, new DeleteOptions
  163. {
  164. DeleteFileLocation = false
  165. });
  166. }
  167. numComplete++;
  168. double percent = numComplete;
  169. percent /= numItems;
  170. progress.Report(percent * 100);
  171. }
  172. progress.Report(100);
  173. }
  174. private async Task CleanDeletedItems(CancellationToken cancellationToken, IProgress<double> progress)
  175. {
  176. var result = _itemRepo.GetItemIdsWithPath(new InternalItemsQuery
  177. {
  178. LocationType = LocationType.FileSystem,
  179. //Limit = limit,
  180. // These have their own cleanup routines
  181. ExcludeItemTypes = new[]
  182. {
  183. typeof(Person).Name,
  184. typeof(Genre).Name,
  185. typeof(MusicGenre).Name,
  186. typeof(GameGenre).Name,
  187. typeof(Studio).Name,
  188. typeof(Year).Name,
  189. typeof(Channel).Name,
  190. typeof(AggregateFolder).Name,
  191. typeof(CollectionFolder).Name
  192. }
  193. });
  194. var numComplete = 0;
  195. var numItems = result.Items.Length;
  196. foreach (var item in result.Items)
  197. {
  198. cancellationToken.ThrowIfCancellationRequested();
  199. var path = item.Item2;
  200. try
  201. {
  202. if (_fileSystem.FileExists(path) || _fileSystem.DirectoryExists(path))
  203. {
  204. continue;
  205. }
  206. var libraryItem = _libraryManager.GetItemById(item.Item1);
  207. if (libraryItem.IsTopParent)
  208. {
  209. continue;
  210. }
  211. if (Folder.IsPathOffline(path))
  212. {
  213. libraryItem.IsOffline = true;
  214. await libraryItem.UpdateToRepository(ItemUpdateType.None, cancellationToken).ConfigureAwait(false);
  215. continue;
  216. }
  217. _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);
  218. await _libraryManager.DeleteItem(libraryItem, new DeleteOptions
  219. {
  220. DeleteFileLocation = false
  221. });
  222. }
  223. catch (OperationCanceledException)
  224. {
  225. throw;
  226. }
  227. catch (Exception ex)
  228. {
  229. _logger.ErrorException("Error in CleanDeletedItems. File {0}", ex, path);
  230. }
  231. numComplete++;
  232. double percent = numComplete;
  233. percent /= numItems;
  234. progress.Report(percent * 100);
  235. }
  236. }
  237. public IEnumerable<ITaskTrigger> GetDefaultTriggers()
  238. {
  239. return new ITaskTrigger[]
  240. {
  241. new IntervalTrigger{ Interval = TimeSpan.FromHours(24)}
  242. };
  243. }
  244. }
  245. }