LibraryManager.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562
  1. using MediaBrowser.Common.Events;
  2. using MediaBrowser.Common.Extensions;
  3. using MediaBrowser.Common.ScheduledTasks;
  4. using MediaBrowser.Controller.Entities;
  5. using MediaBrowser.Controller.IO;
  6. using MediaBrowser.Controller.Resolvers;
  7. using MediaBrowser.Controller.ScheduledTasks;
  8. using MediaBrowser.Model.Entities;
  9. using MediaBrowser.Model.Logging;
  10. using MoreLinq;
  11. using System;
  12. using System.Collections.Concurrent;
  13. using System.Collections.Generic;
  14. using System.Globalization;
  15. using System.IO;
  16. using System.Linq;
  17. using System.Threading;
  18. using System.Threading.Tasks;
  19. namespace MediaBrowser.Controller.Library
  20. {
  21. /// <summary>
  22. /// Class LibraryManager
  23. /// </summary>
  24. public class LibraryManager
  25. {
  26. #region LibraryChanged Event
  27. /// <summary>
  28. /// Fires whenever any validation routine adds or removes items. The added and removed items are properties of the args.
  29. /// *** Will fire asynchronously. ***
  30. /// </summary>
  31. public event EventHandler<ChildrenChangedEventArgs> LibraryChanged;
  32. /// <summary>
  33. /// Raises the <see cref="E:LibraryChanged" /> event.
  34. /// </summary>
  35. /// <param name="args">The <see cref="ChildrenChangedEventArgs" /> instance containing the event data.</param>
  36. internal void OnLibraryChanged(ChildrenChangedEventArgs args)
  37. {
  38. EventHelper.QueueEventIfNotNull(LibraryChanged, this, args, _logger);
  39. // Had to put this in a separate method to avoid an implicitly captured closure
  40. SendLibraryChangedWebSocketMessage(args);
  41. }
  42. /// <summary>
  43. /// Sends the library changed web socket message.
  44. /// </summary>
  45. /// <param name="args">The <see cref="ChildrenChangedEventArgs" /> instance containing the event data.</param>
  46. private void SendLibraryChangedWebSocketMessage(ChildrenChangedEventArgs args)
  47. {
  48. // Notify connected ui's
  49. Kernel.ServerManager.SendWebSocketMessage("LibraryChanged", () => DtoBuilder.GetLibraryUpdateInfo(args));
  50. }
  51. #endregion
  52. /// <summary>
  53. /// The _logger
  54. /// </summary>
  55. private readonly ILogger _logger;
  56. /// <summary>
  57. /// The _task manager
  58. /// </summary>
  59. private readonly ITaskManager _taskManager;
  60. private readonly IUserManager _userManager;
  61. /// <summary>
  62. /// Gets or sets the kernel.
  63. /// </summary>
  64. /// <value>The kernel.</value>
  65. private Kernel Kernel { get; set; }
  66. /// <summary>
  67. /// Initializes a new instance of the <see cref="LibraryManager" /> class.
  68. /// </summary>
  69. /// <param name="kernel">The kernel.</param>
  70. /// <param name="logger">The logger.</param>
  71. /// <param name="taskManager">The task manager.</param>
  72. public LibraryManager(Kernel kernel, ILogger logger, ITaskManager taskManager, IUserManager userManager)
  73. {
  74. Kernel = kernel;
  75. _logger = logger;
  76. _taskManager = taskManager;
  77. _userManager = userManager;
  78. kernel.ConfigurationUpdated += kernel_ConfigurationUpdated;
  79. }
  80. /// <summary>
  81. /// Handles the ConfigurationUpdated event of the kernel control.
  82. /// </summary>
  83. /// <param name="sender">The source of the event.</param>
  84. /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
  85. void kernel_ConfigurationUpdated(object sender, EventArgs e)
  86. {
  87. //// Figure out whether or not we should refresh people after the update is finished
  88. //var refreshPeopleAfterUpdate = !oldConfiguration.EnableInternetProviders && config.EnableInternetProviders;
  89. //// This is true if internet providers has just been turned on, or if People have just been removed from InternetProviderExcludeTypes
  90. //if (!refreshPeopleAfterUpdate)
  91. //{
  92. // var oldConfigurationFetchesPeopleImages = oldConfiguration.InternetProviderExcludeTypes == null || !oldConfiguration.InternetProviderExcludeTypes.Contains(typeof(Person).Name, StringComparer.OrdinalIgnoreCase);
  93. // var newConfigurationFetchesPeopleImages = config.InternetProviderExcludeTypes == null || !config.InternetProviderExcludeTypes.Contains(typeof(Person).Name, StringComparer.OrdinalIgnoreCase);
  94. // refreshPeopleAfterUpdate = newConfigurationFetchesPeopleImages && !oldConfigurationFetchesPeopleImages;
  95. //}
  96. Task.Run(() =>
  97. {
  98. // Any number of configuration settings could change the way the library is refreshed, so do that now
  99. _taskManager.CancelIfRunningAndQueue<RefreshMediaLibraryTask>();
  100. _taskManager.CancelIfRunningAndQueue<PeopleValidationTask>();
  101. });
  102. }
  103. /// <summary>
  104. /// Resolves the item.
  105. /// </summary>
  106. /// <param name="args">The args.</param>
  107. /// <returns>BaseItem.</returns>
  108. public BaseItem ResolveItem(ItemResolveArgs args)
  109. {
  110. return Kernel.EntityResolvers.Select(r => r.ResolvePath(args)).FirstOrDefault(i => i != null);
  111. }
  112. /// <summary>
  113. /// Resolves a path into a BaseItem
  114. /// </summary>
  115. /// <param name="path">The path.</param>
  116. /// <param name="parent">The parent.</param>
  117. /// <param name="fileInfo">The file info.</param>
  118. /// <returns>BaseItem.</returns>
  119. /// <exception cref="System.ArgumentNullException"></exception>
  120. public BaseItem GetItem(string path, Folder parent = null, WIN32_FIND_DATA? fileInfo = null)
  121. {
  122. if (string.IsNullOrEmpty(path))
  123. {
  124. throw new ArgumentNullException();
  125. }
  126. fileInfo = fileInfo ?? FileSystem.GetFileData(path);
  127. if (!fileInfo.HasValue)
  128. {
  129. return null;
  130. }
  131. var args = new ItemResolveArgs
  132. {
  133. Parent = parent,
  134. Path = path,
  135. FileInfo = fileInfo.Value
  136. };
  137. // Return null if ignore rules deem that we should do so
  138. if (Kernel.EntityResolutionIgnoreRules.Any(r => r.ShouldIgnore(args)))
  139. {
  140. return null;
  141. }
  142. // Gather child folder and files
  143. if (args.IsDirectory)
  144. {
  145. // When resolving the root, we need it's grandchildren (children of user views)
  146. var flattenFolderDepth = args.IsPhysicalRoot ? 2 : 0;
  147. args.FileSystemDictionary = FileData.GetFilteredFileSystemEntries(args.Path, _logger, flattenFolderDepth: flattenFolderDepth, args: args);
  148. }
  149. // Check to see if we should resolve based on our contents
  150. if (args.IsDirectory && !EntityResolutionHelper.ShouldResolvePathContents(args))
  151. {
  152. return null;
  153. }
  154. return ResolveItem(args);
  155. }
  156. /// <summary>
  157. /// Resolves a set of files into a list of BaseItem
  158. /// </summary>
  159. /// <typeparam name="T"></typeparam>
  160. /// <param name="files">The files.</param>
  161. /// <param name="parent">The parent.</param>
  162. /// <returns>List{``0}.</returns>
  163. public List<T> GetItems<T>(IEnumerable<WIN32_FIND_DATA> files, Folder parent)
  164. where T : BaseItem
  165. {
  166. var list = new List<T>();
  167. Parallel.ForEach(files, f =>
  168. {
  169. try
  170. {
  171. var item = GetItem(f.Path, parent, f) as T;
  172. if (item != null)
  173. {
  174. lock (list)
  175. {
  176. list.Add(item);
  177. }
  178. }
  179. }
  180. catch (Exception ex)
  181. {
  182. _logger.ErrorException("Error resolving path {0}", ex, f.Path);
  183. }
  184. });
  185. return list;
  186. }
  187. /// <summary>
  188. /// Creates the root media folder
  189. /// </summary>
  190. /// <returns>AggregateFolder.</returns>
  191. /// <exception cref="System.InvalidOperationException">Cannot create the root folder until plugins have loaded</exception>
  192. internal AggregateFolder CreateRootFolder()
  193. {
  194. if (Kernel.Plugins == null)
  195. {
  196. throw new InvalidOperationException("Cannot create the root folder until plugins have loaded");
  197. }
  198. var rootFolderPath = Kernel.ApplicationPaths.RootFolderPath;
  199. var rootFolder = Kernel.ItemRepository.RetrieveItem(rootFolderPath.GetMBId(typeof(AggregateFolder))) as AggregateFolder ?? (AggregateFolder)GetItem(rootFolderPath);
  200. // Add in the plug-in folders
  201. foreach (var child in Kernel.PluginFolderCreators)
  202. {
  203. rootFolder.AddVirtualChild(child.GetFolder());
  204. }
  205. return rootFolder;
  206. }
  207. /// <summary>
  208. /// Gets a Person
  209. /// </summary>
  210. /// <param name="name">The name.</param>
  211. /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param>
  212. /// <returns>Task{Person}.</returns>
  213. public Task<Person> GetPerson(string name, bool allowSlowProviders = false)
  214. {
  215. return GetPerson(name, CancellationToken.None, allowSlowProviders);
  216. }
  217. /// <summary>
  218. /// Gets a Person
  219. /// </summary>
  220. /// <param name="name">The name.</param>
  221. /// <param name="cancellationToken">The cancellation token.</param>
  222. /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param>
  223. /// <returns>Task{Person}.</returns>
  224. private Task<Person> GetPerson(string name, CancellationToken cancellationToken, bool allowSlowProviders = false)
  225. {
  226. return GetImagesByNameItem<Person>(Kernel.ApplicationPaths.PeoplePath, name, cancellationToken, allowSlowProviders);
  227. }
  228. /// <summary>
  229. /// Gets a Studio
  230. /// </summary>
  231. /// <param name="name">The name.</param>
  232. /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param>
  233. /// <returns>Task{Studio}.</returns>
  234. public Task<Studio> GetStudio(string name, bool allowSlowProviders = false)
  235. {
  236. return GetImagesByNameItem<Studio>(Kernel.ApplicationPaths.StudioPath, name, CancellationToken.None, allowSlowProviders);
  237. }
  238. /// <summary>
  239. /// Gets a Genre
  240. /// </summary>
  241. /// <param name="name">The name.</param>
  242. /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param>
  243. /// <returns>Task{Genre}.</returns>
  244. public Task<Genre> GetGenre(string name, bool allowSlowProviders = false)
  245. {
  246. return GetImagesByNameItem<Genre>(Kernel.ApplicationPaths.GenrePath, name, CancellationToken.None, allowSlowProviders);
  247. }
  248. /// <summary>
  249. /// The us culture
  250. /// </summary>
  251. private static readonly CultureInfo UsCulture = new CultureInfo("en-US");
  252. /// <summary>
  253. /// Gets a Year
  254. /// </summary>
  255. /// <param name="value">The value.</param>
  256. /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param>
  257. /// <returns>Task{Year}.</returns>
  258. /// <exception cref="System.ArgumentOutOfRangeException"></exception>
  259. public Task<Year> GetYear(int value, bool allowSlowProviders = false)
  260. {
  261. if (value <= 0)
  262. {
  263. throw new ArgumentOutOfRangeException();
  264. }
  265. return GetImagesByNameItem<Year>(Kernel.ApplicationPaths.YearPath, value.ToString(UsCulture), CancellationToken.None, allowSlowProviders);
  266. }
  267. /// <summary>
  268. /// The images by name item cache
  269. /// </summary>
  270. private readonly ConcurrentDictionary<string, object> ImagesByNameItemCache = new ConcurrentDictionary<string, object>(StringComparer.OrdinalIgnoreCase);
  271. /// <summary>
  272. /// Generically retrieves an IBN item
  273. /// </summary>
  274. /// <typeparam name="T"></typeparam>
  275. /// <param name="path">The path.</param>
  276. /// <param name="name">The name.</param>
  277. /// <param name="cancellationToken">The cancellation token.</param>
  278. /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param>
  279. /// <returns>Task{``0}.</returns>
  280. /// <exception cref="System.ArgumentNullException"></exception>
  281. private Task<T> GetImagesByNameItem<T>(string path, string name, CancellationToken cancellationToken, bool allowSlowProviders = true)
  282. where T : BaseItem, new()
  283. {
  284. if (string.IsNullOrEmpty(path))
  285. {
  286. throw new ArgumentNullException();
  287. }
  288. if (string.IsNullOrEmpty(name))
  289. {
  290. throw new ArgumentNullException();
  291. }
  292. var key = Path.Combine(path, FileSystem.GetValidFilename(name));
  293. var obj = ImagesByNameItemCache.GetOrAdd(key, keyname => CreateImagesByNameItem<T>(path, name, cancellationToken, allowSlowProviders));
  294. return obj as Task<T>;
  295. }
  296. /// <summary>
  297. /// Creates an IBN item based on a given path
  298. /// </summary>
  299. /// <typeparam name="T"></typeparam>
  300. /// <param name="path">The path.</param>
  301. /// <param name="name">The name.</param>
  302. /// <param name="cancellationToken">The cancellation token.</param>
  303. /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param>
  304. /// <returns>Task{``0}.</returns>
  305. /// <exception cref="System.IO.IOException">Path not created: + path</exception>
  306. private async Task<T> CreateImagesByNameItem<T>(string path, string name, CancellationToken cancellationToken, bool allowSlowProviders = true)
  307. where T : BaseItem, new()
  308. {
  309. cancellationToken.ThrowIfCancellationRequested();
  310. _logger.Debug("Creating {0}: {1}", typeof(T).Name, name);
  311. path = Path.Combine(path, FileSystem.GetValidFilename(name));
  312. var fileInfo = FileSystem.GetFileData(path);
  313. var isNew = false;
  314. if (!fileInfo.HasValue)
  315. {
  316. Directory.CreateDirectory(path);
  317. fileInfo = FileSystem.GetFileData(path);
  318. if (!fileInfo.HasValue)
  319. {
  320. throw new IOException("Path not created: " + path);
  321. }
  322. isNew = true;
  323. }
  324. cancellationToken.ThrowIfCancellationRequested();
  325. var id = path.GetMBId(typeof(T));
  326. var item = Kernel.ItemRepository.RetrieveItem(id) as T;
  327. if (item == null)
  328. {
  329. item = new T
  330. {
  331. Name = name,
  332. Id = id,
  333. DateCreated = fileInfo.Value.CreationTimeUtc,
  334. DateModified = fileInfo.Value.LastWriteTimeUtc,
  335. Path = path
  336. };
  337. isNew = true;
  338. }
  339. cancellationToken.ThrowIfCancellationRequested();
  340. // Set this now so we don't cause additional file system access during provider executions
  341. item.ResetResolveArgs(fileInfo);
  342. await item.RefreshMetadata(cancellationToken, isNew, allowSlowProviders: allowSlowProviders).ConfigureAwait(false);
  343. cancellationToken.ThrowIfCancellationRequested();
  344. return item;
  345. }
  346. /// <summary>
  347. /// Validate and refresh the People sub-set of the IBN.
  348. /// The items are stored in the db but not loaded into memory until actually requested by an operation.
  349. /// </summary>
  350. /// <param name="cancellationToken">The cancellation token.</param>
  351. /// <param name="progress">The progress.</param>
  352. /// <returns>Task.</returns>
  353. internal async Task ValidatePeople(CancellationToken cancellationToken, IProgress<double> progress)
  354. {
  355. // Clear the IBN cache
  356. ImagesByNameItemCache.Clear();
  357. const int maxTasks = 250;
  358. var tasks = new List<Task>();
  359. var includedPersonTypes = new[] { PersonType.Actor, PersonType.Director };
  360. var people = Kernel.RootFolder.RecursiveChildren
  361. .Where(c => c.People != null)
  362. .SelectMany(c => c.People.Where(p => includedPersonTypes.Contains(p.Type)))
  363. .DistinctBy(p => p.Name, StringComparer.OrdinalIgnoreCase)
  364. .ToList();
  365. var numComplete = 0;
  366. foreach (var person in people)
  367. {
  368. if (tasks.Count > maxTasks)
  369. {
  370. await Task.WhenAll(tasks).ConfigureAwait(false);
  371. tasks.Clear();
  372. // Safe cancellation point, when there are no pending tasks
  373. cancellationToken.ThrowIfCancellationRequested();
  374. }
  375. // Avoid accessing the foreach variable within the closure
  376. var currentPerson = person;
  377. tasks.Add(Task.Run(async () =>
  378. {
  379. cancellationToken.ThrowIfCancellationRequested();
  380. try
  381. {
  382. await GetPerson(currentPerson.Name, cancellationToken, allowSlowProviders: true).ConfigureAwait(false);
  383. }
  384. catch (IOException ex)
  385. {
  386. _logger.ErrorException("Error validating IBN entry {0}", ex, currentPerson.Name);
  387. }
  388. // Update progress
  389. lock (progress)
  390. {
  391. numComplete++;
  392. double percent = numComplete;
  393. percent /= people.Count;
  394. progress.Report(100 * percent);
  395. }
  396. }));
  397. }
  398. await Task.WhenAll(tasks).ConfigureAwait(false);
  399. progress.Report(100);
  400. _logger.Info("People validation complete");
  401. }
  402. /// <summary>
  403. /// Reloads the root media folder
  404. /// </summary>
  405. /// <param name="progress">The progress.</param>
  406. /// <param name="cancellationToken">The cancellation token.</param>
  407. /// <returns>Task.</returns>
  408. internal async Task ValidateMediaLibrary(IProgress<double> progress, CancellationToken cancellationToken)
  409. {
  410. _logger.Info("Validating media library");
  411. await Kernel.RootFolder.RefreshMetadata(cancellationToken).ConfigureAwait(false);
  412. // Start by just validating the children of the root, but go no further
  413. await Kernel.RootFolder.ValidateChildren(new Progress<double> { }, cancellationToken, recursive: false);
  414. // Validate only the collection folders for each user, just to make them available as quickly as possible
  415. var userCollectionFolderTasks = _userManager.Users.AsParallel().Select(user => user.ValidateCollectionFolders(new Progress<double> { }, cancellationToken));
  416. await Task.WhenAll(userCollectionFolderTasks).ConfigureAwait(false);
  417. // Now validate the entire media library
  418. await Kernel.RootFolder.ValidateChildren(progress, cancellationToken, recursive: true).ConfigureAwait(false);
  419. foreach (var user in _userManager.Users)
  420. {
  421. await user.ValidateMediaLibrary(new Progress<double> { }, cancellationToken).ConfigureAwait(false);
  422. }
  423. }
  424. /// <summary>
  425. /// Saves display preferences for a Folder
  426. /// </summary>
  427. /// <param name="user">The user.</param>
  428. /// <param name="folder">The folder.</param>
  429. /// <param name="data">The data.</param>
  430. /// <returns>Task.</returns>
  431. public Task SaveDisplayPreferencesForFolder(User user, Folder folder, DisplayPreferences data)
  432. {
  433. // Need to update all items with the same DisplayPrefsId
  434. foreach (var child in Kernel.RootFolder.GetRecursiveChildren(user)
  435. .OfType<Folder>()
  436. .Where(i => i.DisplayPrefsId == folder.DisplayPrefsId))
  437. {
  438. child.AddOrUpdateDisplayPrefs(user, data);
  439. }
  440. return Kernel.DisplayPreferencesRepository.SaveDisplayPrefs(folder, CancellationToken.None);
  441. }
  442. /// <summary>
  443. /// Gets the default view.
  444. /// </summary>
  445. /// <returns>IEnumerable{VirtualFolderInfo}.</returns>
  446. public IEnumerable<VirtualFolderInfo> GetDefaultVirtualFolders()
  447. {
  448. return GetView(Kernel.ApplicationPaths.DefaultUserViewsPath);
  449. }
  450. /// <summary>
  451. /// Gets the view.
  452. /// </summary>
  453. /// <param name="user">The user.</param>
  454. /// <returns>IEnumerable{VirtualFolderInfo}.</returns>
  455. public IEnumerable<VirtualFolderInfo> GetVirtualFolders(User user)
  456. {
  457. return GetView(user.RootFolderPath);
  458. }
  459. /// <summary>
  460. /// Gets the view.
  461. /// </summary>
  462. /// <param name="path">The path.</param>
  463. /// <returns>IEnumerable{VirtualFolderInfo}.</returns>
  464. private IEnumerable<VirtualFolderInfo> GetView(string path)
  465. {
  466. return Directory.EnumerateDirectories(path, "*", SearchOption.TopDirectoryOnly)
  467. .Select(dir => new VirtualFolderInfo
  468. {
  469. Name = Path.GetFileName(dir),
  470. Locations = Directory.EnumerateFiles(dir, "*.lnk", SearchOption.TopDirectoryOnly).Select(FileSystem.ResolveShortcut).ToList()
  471. });
  472. }
  473. }
  474. }