2
0

CleanDatabaseScheduledTask.cs 13 KB

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