CleanDatabaseScheduledTask.cs 10 KB

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