CleanDatabaseScheduledTask.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  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.Server.Implementations.ScheduledTasks;
  22. namespace MediaBrowser.Server.Implementations.Persistence
  23. {
  24. public class CleanDatabaseScheduledTask : IScheduledTask
  25. {
  26. private readonly ILibraryManager _libraryManager;
  27. private readonly IItemRepository _itemRepo;
  28. private readonly ILogger _logger;
  29. private readonly IServerConfigurationManager _config;
  30. private readonly IFileSystem _fileSystem;
  31. private readonly IHttpServer _httpServer;
  32. private readonly ILocalizationManager _localization;
  33. private readonly ITaskManager _taskManager;
  34. public const int MigrationVersion = 23;
  35. public static bool EnableUnavailableMessage = false;
  36. public CleanDatabaseScheduledTask(ILibraryManager libraryManager, IItemRepository itemRepo, ILogger logger, IServerConfigurationManager config, IFileSystem fileSystem, IHttpServer httpServer, ILocalizationManager localization, ITaskManager taskManager)
  37. {
  38. _libraryManager = libraryManager;
  39. _itemRepo = itemRepo;
  40. _logger = logger;
  41. _config = config;
  42. _fileSystem = fileSystem;
  43. _httpServer = httpServer;
  44. _localization = localization;
  45. _taskManager = taskManager;
  46. }
  47. public string Name
  48. {
  49. get { return "Clean Database"; }
  50. }
  51. public string Description
  52. {
  53. get { return "Deletes obsolete content from the database."; }
  54. }
  55. public string Category
  56. {
  57. get { return "Library"; }
  58. }
  59. public async Task Execute(CancellationToken cancellationToken, IProgress<double> progress)
  60. {
  61. OnProgress(0);
  62. // Ensure these objects are lazy loaded.
  63. // Without this there is a deadlock that will need to be investigated
  64. var rootChildren = _libraryManager.RootFolder.Children.ToList();
  65. rootChildren = _libraryManager.GetUserRootFolder().Children.ToList();
  66. var innerProgress = new ActionableProgress<double>();
  67. innerProgress.RegisterAction(p =>
  68. {
  69. double newPercentCommplete = .4 * p;
  70. OnProgress(newPercentCommplete);
  71. progress.Report(newPercentCommplete);
  72. });
  73. await UpdateToLatestSchema(cancellationToken, innerProgress).ConfigureAwait(false);
  74. innerProgress = new ActionableProgress<double>();
  75. innerProgress.RegisterAction(p =>
  76. {
  77. double newPercentCommplete = 40 + .05 * p;
  78. OnProgress(newPercentCommplete);
  79. progress.Report(newPercentCommplete);
  80. });
  81. await CleanDeadItems(cancellationToken, innerProgress).ConfigureAwait(false);
  82. progress.Report(45);
  83. innerProgress = new ActionableProgress<double>();
  84. innerProgress.RegisterAction(p =>
  85. {
  86. double newPercentCommplete = 45 + .55 * p;
  87. OnProgress(newPercentCommplete);
  88. progress.Report(newPercentCommplete);
  89. });
  90. await CleanDeletedItems(cancellationToken, innerProgress).ConfigureAwait(false);
  91. progress.Report(100);
  92. await _itemRepo.UpdateInheritedValues(cancellationToken).ConfigureAwait(false);
  93. if (_config.Configuration.MigrationVersion < MigrationVersion)
  94. {
  95. _config.Configuration.MigrationVersion = MigrationVersion;
  96. _config.SaveConfiguration();
  97. }
  98. if (_config.Configuration.SchemaVersion < SqliteItemRepository.LatestSchemaVersion)
  99. {
  100. _config.Configuration.SchemaVersion = SqliteItemRepository.LatestSchemaVersion;
  101. _config.SaveConfiguration();
  102. }
  103. if (EnableUnavailableMessage)
  104. {
  105. EnableUnavailableMessage = false;
  106. _httpServer.GlobalResponse = null;
  107. _taskManager.QueueScheduledTask<RefreshMediaLibraryTask>();
  108. }
  109. _taskManager.SuspendTriggers = false;
  110. }
  111. private void OnProgress(double newPercentCommplete)
  112. {
  113. if (EnableUnavailableMessage)
  114. {
  115. var html = "<!doctype html><html><head><title>Emby</title></head><body>";
  116. var text = _localization.GetLocalizedString("DbUpgradeMessage");
  117. html += string.Format(text, newPercentCommplete.ToString("N2", CultureInfo.InvariantCulture));
  118. html += "<script>setTimeout(function(){window.location.reload(true);}, 5000);</script>";
  119. html += "</body></html>";
  120. _httpServer.GlobalResponse = html;
  121. }
  122. }
  123. private Task UpdateToLatestSchema(CancellationToken cancellationToken, IProgress<double> progress)
  124. {
  125. return UpdateToLatestSchema(0, 0, null, cancellationToken, progress);
  126. }
  127. private async Task UpdateToLatestSchema(int queryStartIndex, int progressStartIndex, int? totalRecordCount, CancellationToken cancellationToken, IProgress<double> progress)
  128. {
  129. IEnumerable<BaseItem> items;
  130. int numItemsToSave;
  131. var pageSize = 1000;
  132. if (totalRecordCount.HasValue)
  133. {
  134. var list = _libraryManager.GetItemList(new InternalItemsQuery
  135. {
  136. IsCurrentSchema = false,
  137. ExcludeItemTypes = new[] { typeof(LiveTvProgram).Name },
  138. StartIndex = queryStartIndex,
  139. Limit = pageSize
  140. }).ToList();
  141. items = list;
  142. numItemsToSave = list.Count;
  143. }
  144. else
  145. {
  146. var itemsResult = _libraryManager.GetItemsResult(new InternalItemsQuery
  147. {
  148. IsCurrentSchema = false,
  149. ExcludeItemTypes = new[] { typeof(LiveTvProgram).Name },
  150. StartIndex = queryStartIndex,
  151. Limit = pageSize
  152. });
  153. totalRecordCount = itemsResult.TotalRecordCount;
  154. items = itemsResult.Items;
  155. numItemsToSave = itemsResult.Items.Length;
  156. }
  157. var numItems = totalRecordCount.Value;
  158. _logger.Debug("Upgrading schema for {0} items", numItems);
  159. if (numItemsToSave > 0)
  160. {
  161. try
  162. {
  163. await _itemRepo.SaveItems(items, cancellationToken).ConfigureAwait(false);
  164. }
  165. catch (OperationCanceledException)
  166. {
  167. throw;
  168. }
  169. catch (Exception ex)
  170. {
  171. _logger.ErrorException("Error saving item", ex);
  172. }
  173. progressStartIndex += pageSize;
  174. double percent = progressStartIndex;
  175. percent /= numItems;
  176. progress.Report(percent * 100);
  177. var newStartIndex = queryStartIndex + (pageSize - numItemsToSave);
  178. await UpdateToLatestSchema(newStartIndex, progressStartIndex, totalRecordCount, cancellationToken, progress).ConfigureAwait(false);
  179. }
  180. else
  181. {
  182. progress.Report(100);
  183. }
  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. libraryItem.IsOffline = true;
  264. await libraryItem.UpdateToRepository(ItemUpdateType.None, cancellationToken).ConfigureAwait(false);
  265. continue;
  266. }
  267. _logger.Info("Deleting item from database {0} because path no longer exists. type: {1} path: {2}", libraryItem.Name, libraryItem.GetType().Name, libraryItemPath ?? string.Empty);
  268. await libraryItem.OnFileDeleted().ConfigureAwait(false);
  269. }
  270. catch (OperationCanceledException)
  271. {
  272. throw;
  273. }
  274. catch (Exception ex)
  275. {
  276. _logger.ErrorException("Error in CleanDeletedItems. File {0}", ex, path);
  277. }
  278. numComplete++;
  279. double percent = numComplete;
  280. percent /= numItems;
  281. progress.Report(percent * 100);
  282. }
  283. }
  284. public IEnumerable<ITaskTrigger> GetDefaultTriggers()
  285. {
  286. return new ITaskTrigger[]
  287. {
  288. new IntervalTrigger{ Interval = TimeSpan.FromHours(24)}
  289. };
  290. }
  291. }
  292. }