2
0

LibraryManager.cs 22 KB

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