CleanDatabaseScheduledTask.cs 10 KB

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