LibraryManager.cs 20 KB

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