LibraryManager.cs 19 KB

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