CleanDatabaseScheduledTask.cs 11 KB

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