CleanDatabaseScheduledTask.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  1. using MediaBrowser.Common.Progress;
  2. using MediaBrowser.Controller.Configuration;
  3. using MediaBrowser.Controller.Entities;
  4. using MediaBrowser.Controller.Library;
  5. using MediaBrowser.Controller.Persistence;
  6. using MediaBrowser.Model.Entities;
  7. using MediaBrowser.Model.Logging;
  8. using System;
  9. using System.Collections.Generic;
  10. using System.Globalization;
  11. using System.Linq;
  12. using System.Threading;
  13. using System.Threading.Tasks;
  14. using MediaBrowser.Common.IO;
  15. using MediaBrowser.Model.IO;
  16. using MediaBrowser.Controller.Channels;
  17. using MediaBrowser.Controller.Entities.Audio;
  18. using MediaBrowser.Controller.IO;
  19. using MediaBrowser.Controller.LiveTv;
  20. using MediaBrowser.Controller.Net;
  21. using MediaBrowser.Model.Globalization;
  22. using MediaBrowser.Model.Tasks;
  23. using Emby.Server.Implementations.ScheduledTasks;
  24. namespace Emby.Server.Implementations.Data
  25. {
  26. public class CleanDatabaseScheduledTask : IScheduledTask
  27. {
  28. private readonly ILibraryManager _libraryManager;
  29. private readonly IItemRepository _itemRepo;
  30. private readonly ILogger _logger;
  31. private readonly IServerConfigurationManager _config;
  32. private readonly IFileSystem _fileSystem;
  33. private readonly IHttpServer _httpServer;
  34. private readonly ILocalizationManager _localization;
  35. private readonly ITaskManager _taskManager;
  36. public const int MigrationVersion = 23;
  37. public static bool EnableUnavailableMessage = false;
  38. const int LatestSchemaVersion = 109;
  39. public CleanDatabaseScheduledTask(ILibraryManager libraryManager, IItemRepository itemRepo, ILogger logger, IServerConfigurationManager config, IFileSystem fileSystem, IHttpServer httpServer, ILocalizationManager localization, ITaskManager taskManager)
  40. {
  41. _libraryManager = libraryManager;
  42. _itemRepo = itemRepo;
  43. _logger = logger;
  44. _config = config;
  45. _fileSystem = fileSystem;
  46. _httpServer = httpServer;
  47. _localization = localization;
  48. _taskManager = taskManager;
  49. }
  50. public string Name
  51. {
  52. get { return "Clean Database"; }
  53. }
  54. public string Description
  55. {
  56. get { return "Deletes obsolete content from the database."; }
  57. }
  58. public string Category
  59. {
  60. get { return "Library"; }
  61. }
  62. public async Task Execute(CancellationToken cancellationToken, IProgress<double> progress)
  63. {
  64. OnProgress(0);
  65. // Ensure these objects are lazy loaded.
  66. // Without this there is a deadlock that will need to be investigated
  67. var rootChildren = _libraryManager.RootFolder.Children.ToList();
  68. rootChildren = _libraryManager.GetUserRootFolder().Children.ToList();
  69. var innerProgress = new ActionableProgress<double>();
  70. innerProgress.RegisterAction(p =>
  71. {
  72. double newPercentCommplete = .4 * p;
  73. OnProgress(newPercentCommplete);
  74. progress.Report(newPercentCommplete);
  75. });
  76. await UpdateToLatestSchema(cancellationToken, innerProgress).ConfigureAwait(false);
  77. innerProgress = new ActionableProgress<double>();
  78. innerProgress.RegisterAction(p =>
  79. {
  80. double newPercentCommplete = 40 + .05 * p;
  81. OnProgress(newPercentCommplete);
  82. progress.Report(newPercentCommplete);
  83. });
  84. await CleanDeadItems(cancellationToken, innerProgress).ConfigureAwait(false);
  85. progress.Report(45);
  86. innerProgress = new ActionableProgress<double>();
  87. innerProgress.RegisterAction(p =>
  88. {
  89. double newPercentCommplete = 45 + .55 * p;
  90. OnProgress(newPercentCommplete);
  91. progress.Report(newPercentCommplete);
  92. });
  93. await CleanDeletedItems(cancellationToken, innerProgress).ConfigureAwait(false);
  94. progress.Report(100);
  95. await _itemRepo.UpdateInheritedValues(cancellationToken).ConfigureAwait(false);
  96. if (_config.Configuration.MigrationVersion < MigrationVersion)
  97. {
  98. _config.Configuration.MigrationVersion = MigrationVersion;
  99. _config.SaveConfiguration();
  100. }
  101. if (_config.Configuration.SchemaVersion < LatestSchemaVersion)
  102. {
  103. _config.Configuration.SchemaVersion = LatestSchemaVersion;
  104. _config.SaveConfiguration();
  105. }
  106. if (EnableUnavailableMessage)
  107. {
  108. EnableUnavailableMessage = false;
  109. _httpServer.GlobalResponse = null;
  110. _taskManager.QueueScheduledTask<RefreshMediaLibraryTask>();
  111. }
  112. _taskManager.SuspendTriggers = false;
  113. }
  114. private void OnProgress(double newPercentCommplete)
  115. {
  116. if (EnableUnavailableMessage)
  117. {
  118. var html = "<!doctype html><html><head><title>Emby</title></head><body>";
  119. var text = _localization.GetLocalizedString("DbUpgradeMessage");
  120. html += string.Format(text, newPercentCommplete.ToString("N2", CultureInfo.InvariantCulture));
  121. html += "<script>setTimeout(function(){window.location.reload(true);}, 5000);</script>";
  122. html += "</body></html>";
  123. _httpServer.GlobalResponse = html;
  124. }
  125. }
  126. private async Task UpdateToLatestSchema(CancellationToken cancellationToken, IProgress<double> progress)
  127. {
  128. var itemIds = _libraryManager.GetItemIds(new InternalItemsQuery
  129. {
  130. IsCurrentSchema = false,
  131. ExcludeItemTypes = new[] { typeof(LiveTvProgram).Name }
  132. });
  133. var numComplete = 0;
  134. var numItems = itemIds.Count;
  135. _logger.Debug("Upgrading schema for {0} items", numItems);
  136. var list = new List<BaseItem>();
  137. foreach (var itemId in itemIds)
  138. {
  139. cancellationToken.ThrowIfCancellationRequested();
  140. if (itemId != Guid.Empty)
  141. {
  142. // Somehow some invalid data got into the db. It probably predates the boundary checking
  143. var item = _libraryManager.GetItemById(itemId);
  144. if (item != null)
  145. {
  146. list.Add(item);
  147. }
  148. }
  149. if (list.Count >= 1000)
  150. {
  151. try
  152. {
  153. await _itemRepo.SaveItems(list, cancellationToken).ConfigureAwait(false);
  154. }
  155. catch (OperationCanceledException)
  156. {
  157. throw;
  158. }
  159. catch (Exception ex)
  160. {
  161. _logger.ErrorException("Error saving item", ex);
  162. }
  163. list.Clear();
  164. }
  165. numComplete++;
  166. double percent = numComplete;
  167. percent /= numItems;
  168. progress.Report(percent * 100);
  169. }
  170. if (list.Count > 0)
  171. {
  172. try
  173. {
  174. await _itemRepo.SaveItems(list, cancellationToken).ConfigureAwait(false);
  175. }
  176. catch (OperationCanceledException)
  177. {
  178. throw;
  179. }
  180. catch (Exception ex)
  181. {
  182. _logger.ErrorException("Error saving item", ex);
  183. }
  184. }
  185. progress.Report(100);
  186. }
  187. private async Task CleanDeadItems(CancellationToken cancellationToken, IProgress<double> progress)
  188. {
  189. var itemIds = _libraryManager.GetItemIds(new InternalItemsQuery
  190. {
  191. HasDeadParentId = true
  192. });
  193. var numComplete = 0;
  194. var numItems = itemIds.Count;
  195. _logger.Debug("Cleaning {0} items with dead parent links", numItems);
  196. foreach (var itemId in itemIds)
  197. {
  198. cancellationToken.ThrowIfCancellationRequested();
  199. var item = _libraryManager.GetItemById(itemId);
  200. if (item != null)
  201. {
  202. _logger.Info("Cleaning item {0} type: {1} path: {2}", item.Name, item.GetType().Name, item.Path ?? string.Empty);
  203. await item.Delete(new DeleteOptions
  204. {
  205. DeleteFileLocation = false
  206. }).ConfigureAwait(false);
  207. }
  208. numComplete++;
  209. double percent = numComplete;
  210. percent /= numItems;
  211. progress.Report(percent * 100);
  212. }
  213. progress.Report(100);
  214. }
  215. private async Task CleanDeletedItems(CancellationToken cancellationToken, IProgress<double> progress)
  216. {
  217. var result = _itemRepo.GetItemIdsWithPath(new InternalItemsQuery
  218. {
  219. LocationTypes = new[] { LocationType.FileSystem },
  220. //Limit = limit,
  221. // These have their own cleanup routines
  222. ExcludeItemTypes = new[]
  223. {
  224. typeof(Person).Name,
  225. typeof(Genre).Name,
  226. typeof(MusicGenre).Name,
  227. typeof(GameGenre).Name,
  228. typeof(Studio).Name,
  229. typeof(Year).Name,
  230. typeof(Channel).Name,
  231. typeof(AggregateFolder).Name,
  232. typeof(CollectionFolder).Name
  233. }
  234. });
  235. var numComplete = 0;
  236. var numItems = result.Items.Length;
  237. foreach (var item in result.Items)
  238. {
  239. cancellationToken.ThrowIfCancellationRequested();
  240. var path = item.Item2;
  241. try
  242. {
  243. if (_fileSystem.FileExists(path) || _fileSystem.DirectoryExists(path))
  244. {
  245. continue;
  246. }
  247. var libraryItem = _libraryManager.GetItemById(item.Item1);
  248. if (libraryItem.IsTopParent)
  249. {
  250. continue;
  251. }
  252. var hasDualAccess = libraryItem as IHasDualAccess;
  253. if (hasDualAccess != null && hasDualAccess.IsAccessedByName)
  254. {
  255. continue;
  256. }
  257. var libraryItemPath = libraryItem.Path;
  258. if (!string.Equals(libraryItemPath, path, StringComparison.OrdinalIgnoreCase))
  259. {
  260. _logger.Error("CleanDeletedItems aborting delete for item {0}-{1} because paths don't match. {2}---{3}", libraryItem.Id, libraryItem.Name, libraryItem.Path ?? string.Empty, path ?? string.Empty);
  261. continue;
  262. }
  263. if (Folder.IsPathOffline(path))
  264. {
  265. await libraryItem.UpdateIsOffline(true).ConfigureAwait(false);
  266. continue;
  267. }
  268. _logger.Info("Deleting item from database {0} because path no longer exists. type: {1} path: {2}", libraryItem.Name, libraryItem.GetType().Name, libraryItemPath ?? string.Empty);
  269. await libraryItem.OnFileDeleted().ConfigureAwait(false);
  270. }
  271. catch (OperationCanceledException)
  272. {
  273. throw;
  274. }
  275. catch (Exception ex)
  276. {
  277. _logger.ErrorException("Error in CleanDeletedItems. File {0}", ex, path);
  278. }
  279. numComplete++;
  280. double percent = numComplete;
  281. percent /= numItems;
  282. progress.Report(percent * 100);
  283. }
  284. }
  285. /// <summary>
  286. /// Creates the triggers that define when the task will run
  287. /// </summary>
  288. /// <returns>IEnumerable{BaseTaskTrigger}.</returns>
  289. public IEnumerable<TaskTriggerInfo> GetDefaultTriggers()
  290. {
  291. return new[] {
  292. // Every so often
  293. new TaskTriggerInfo { Type = TaskTriggerInfo.TriggerInterval, IntervalTicks = TimeSpan.FromHours(24).Ticks}
  294. };
  295. }
  296. public string Key
  297. {
  298. get { return "CleanDatabase"; }
  299. }
  300. }
  301. }