CleanDatabaseScheduledTask.cs 13 KB

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