LibraryManager.cs 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494
  1. using MediaBrowser.Common.Extensions;
  2. using MediaBrowser.Common.IO;
  3. using MediaBrowser.Common.Progress;
  4. using MediaBrowser.Common.ScheduledTasks;
  5. using MediaBrowser.Controller.Configuration;
  6. using MediaBrowser.Controller.Entities;
  7. using MediaBrowser.Controller.Entities.Audio;
  8. using MediaBrowser.Controller.Entities.Movies;
  9. using MediaBrowser.Controller.Entities.TV;
  10. using MediaBrowser.Controller.IO;
  11. using MediaBrowser.Controller.Library;
  12. using MediaBrowser.Controller.Persistence;
  13. using MediaBrowser.Controller.Providers;
  14. using MediaBrowser.Controller.Resolvers;
  15. using MediaBrowser.Controller.Sorting;
  16. using MediaBrowser.Model.Configuration;
  17. using MediaBrowser.Model.Entities;
  18. using MediaBrowser.Model.Logging;
  19. using MediaBrowser.Server.Implementations.Library.Validators;
  20. using MediaBrowser.Server.Implementations.ScheduledTasks;
  21. using System;
  22. using System.Collections.Concurrent;
  23. using System.Collections.Generic;
  24. using System.Globalization;
  25. using System.IO;
  26. using System.Linq;
  27. using System.Threading;
  28. using System.Threading.Tasks;
  29. using MoreLinq;
  30. using SortOrder = MediaBrowser.Model.Entities.SortOrder;
  31. namespace MediaBrowser.Server.Implementations.Library
  32. {
  33. /// <summary>
  34. /// Class LibraryManager
  35. /// </summary>
  36. public class LibraryManager : ILibraryManager
  37. {
  38. /// <summary>
  39. /// Gets or sets the postscan tasks.
  40. /// </summary>
  41. /// <value>The postscan tasks.</value>
  42. private ILibraryPostScanTask[] PostscanTasks { get; set; }
  43. /// <summary>
  44. /// Gets the intro providers.
  45. /// </summary>
  46. /// <value>The intro providers.</value>
  47. private IIntroProvider[] IntroProviders { get; set; }
  48. /// <summary>
  49. /// Gets the list of entity resolution ignore rules
  50. /// </summary>
  51. /// <value>The entity resolution ignore rules.</value>
  52. private IResolverIgnoreRule[] EntityResolutionIgnoreRules { get; set; }
  53. /// <summary>
  54. /// Gets the list of BasePluginFolders added by plugins
  55. /// </summary>
  56. /// <value>The plugin folders.</value>
  57. private IVirtualFolderCreator[] PluginFolderCreators { get; set; }
  58. /// <summary>
  59. /// Gets the list of currently registered entity resolvers
  60. /// </summary>
  61. /// <value>The entity resolvers enumerable.</value>
  62. private IItemResolver[] EntityResolvers { get; set; }
  63. /// <summary>
  64. /// Gets or sets the comparers.
  65. /// </summary>
  66. /// <value>The comparers.</value>
  67. private IBaseItemComparer[] Comparers { get; set; }
  68. /// <summary>
  69. /// Gets the active item repository
  70. /// </summary>
  71. /// <value>The item repository.</value>
  72. public IItemRepository ItemRepository { get; set; }
  73. /// <summary>
  74. /// Occurs when [item added].
  75. /// </summary>
  76. public event EventHandler<ItemChangeEventArgs> ItemAdded;
  77. /// <summary>
  78. /// Occurs when [item updated].
  79. /// </summary>
  80. public event EventHandler<ItemChangeEventArgs> ItemUpdated;
  81. /// <summary>
  82. /// Occurs when [item removed].
  83. /// </summary>
  84. public event EventHandler<ItemChangeEventArgs> ItemRemoved;
  85. /// <summary>
  86. /// The _logger
  87. /// </summary>
  88. private readonly ILogger _logger;
  89. /// <summary>
  90. /// The _task manager
  91. /// </summary>
  92. private readonly ITaskManager _taskManager;
  93. /// <summary>
  94. /// The _user manager
  95. /// </summary>
  96. private readonly IUserManager _userManager;
  97. /// <summary>
  98. /// The _user data repository
  99. /// </summary>
  100. private readonly IUserDataManager _userDataRepository;
  101. /// <summary>
  102. /// Gets or sets the configuration manager.
  103. /// </summary>
  104. /// <value>The configuration manager.</value>
  105. private IServerConfigurationManager ConfigurationManager { get; set; }
  106. /// <summary>
  107. /// A collection of items that may be referenced from multiple physical places in the library
  108. /// (typically, multiple user roots). We store them here and be sure they all reference a
  109. /// single instance.
  110. /// </summary>
  111. /// <value>The by reference items.</value>
  112. private ConcurrentDictionary<Guid, BaseItem> ByReferenceItems { get; set; }
  113. private readonly Func<ILibraryMonitor> _libraryMonitorFactory;
  114. private readonly Func<IProviderManager> _providerManagerFactory;
  115. /// <summary>
  116. /// The _library items cache
  117. /// </summary>
  118. private readonly ConcurrentDictionary<Guid, BaseItem> _libraryItemsCache;
  119. /// <summary>
  120. /// Gets the library items cache.
  121. /// </summary>
  122. /// <value>The library items cache.</value>
  123. private ConcurrentDictionary<Guid, BaseItem> LibraryItemsCache
  124. {
  125. get
  126. {
  127. return _libraryItemsCache;
  128. }
  129. }
  130. private readonly IFileSystem _fileSystem;
  131. /// <summary>
  132. /// Initializes a new instance of the <see cref="LibraryManager" /> class.
  133. /// </summary>
  134. /// <param name="logger">The logger.</param>
  135. /// <param name="taskManager">The task manager.</param>
  136. /// <param name="userManager">The user manager.</param>
  137. /// <param name="configurationManager">The configuration manager.</param>
  138. /// <param name="userDataRepository">The user data repository.</param>
  139. public LibraryManager(ILogger logger, ITaskManager taskManager, IUserManager userManager, IServerConfigurationManager configurationManager, IUserDataManager userDataRepository, Func<ILibraryMonitor> libraryMonitorFactory, IFileSystem fileSystem, Func<IProviderManager> providerManagerFactory)
  140. {
  141. _logger = logger;
  142. _taskManager = taskManager;
  143. _userManager = userManager;
  144. ConfigurationManager = configurationManager;
  145. _userDataRepository = userDataRepository;
  146. _libraryMonitorFactory = libraryMonitorFactory;
  147. _fileSystem = fileSystem;
  148. _providerManagerFactory = providerManagerFactory;
  149. ByReferenceItems = new ConcurrentDictionary<Guid, BaseItem>();
  150. _libraryItemsCache = new ConcurrentDictionary<Guid, BaseItem>();
  151. ConfigurationManager.ConfigurationUpdated += ConfigurationUpdated;
  152. RecordConfigurationValues(configurationManager.Configuration);
  153. }
  154. /// <summary>
  155. /// Adds the parts.
  156. /// </summary>
  157. /// <param name="rules">The rules.</param>
  158. /// <param name="pluginFolders">The plugin folders.</param>
  159. /// <param name="resolvers">The resolvers.</param>
  160. /// <param name="introProviders">The intro providers.</param>
  161. /// <param name="itemComparers">The item comparers.</param>
  162. /// <param name="postscanTasks">The postscan tasks.</param>
  163. public void AddParts(IEnumerable<IResolverIgnoreRule> rules,
  164. IEnumerable<IVirtualFolderCreator> pluginFolders,
  165. IEnumerable<IItemResolver> resolvers,
  166. IEnumerable<IIntroProvider> introProviders,
  167. IEnumerable<IBaseItemComparer> itemComparers,
  168. IEnumerable<ILibraryPostScanTask> postscanTasks)
  169. {
  170. EntityResolutionIgnoreRules = rules.ToArray();
  171. PluginFolderCreators = pluginFolders.ToArray();
  172. EntityResolvers = resolvers.OrderBy(i => i.Priority).ToArray();
  173. IntroProviders = introProviders.ToArray();
  174. Comparers = itemComparers.ToArray();
  175. PostscanTasks = postscanTasks.OrderBy(i =>
  176. {
  177. var hasOrder = i as IHasOrder;
  178. return hasOrder == null ? 0 : hasOrder.Order;
  179. }).ToArray();
  180. }
  181. /// <summary>
  182. /// The _root folder
  183. /// </summary>
  184. private AggregateFolder _rootFolder;
  185. /// <summary>
  186. /// The _root folder sync lock
  187. /// </summary>
  188. private object _rootFolderSyncLock = new object();
  189. /// <summary>
  190. /// The _root folder initialized
  191. /// </summary>
  192. private bool _rootFolderInitialized;
  193. /// <summary>
  194. /// Gets the root folder.
  195. /// </summary>
  196. /// <value>The root folder.</value>
  197. public AggregateFolder RootFolder
  198. {
  199. get
  200. {
  201. LazyInitializer.EnsureInitialized(ref _rootFolder, ref _rootFolderInitialized, ref _rootFolderSyncLock, CreateRootFolder);
  202. return _rootFolder;
  203. }
  204. private set
  205. {
  206. _rootFolder = value;
  207. if (value == null)
  208. {
  209. _rootFolderInitialized = false;
  210. }
  211. }
  212. }
  213. /// <summary>
  214. /// The _items by name path
  215. /// </summary>
  216. private string _itemsByNamePath;
  217. /// <summary>
  218. /// The _season zero display name
  219. /// </summary>
  220. private string _seasonZeroDisplayName;
  221. private bool _wizardCompleted;
  222. /// <summary>
  223. /// Records the configuration values.
  224. /// </summary>
  225. /// <param name="configuration">The configuration.</param>
  226. private void RecordConfigurationValues(ServerConfiguration configuration)
  227. {
  228. _seasonZeroDisplayName = configuration.SeasonZeroDisplayName;
  229. _itemsByNamePath = ConfigurationManager.ApplicationPaths.ItemsByNamePath;
  230. _wizardCompleted = configuration.IsStartupWizardCompleted;
  231. }
  232. /// <summary>
  233. /// Configurations the updated.
  234. /// </summary>
  235. /// <param name="sender">The sender.</param>
  236. /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
  237. void ConfigurationUpdated(object sender, EventArgs e)
  238. {
  239. var config = ConfigurationManager.Configuration;
  240. var ibnPathChanged = !string.Equals(_itemsByNamePath, ConfigurationManager.ApplicationPaths.ItemsByNamePath, StringComparison.CurrentCulture);
  241. if (ibnPathChanged)
  242. {
  243. RemoveItemsByNameFromCache();
  244. }
  245. var newSeasonZeroName = ConfigurationManager.Configuration.SeasonZeroDisplayName;
  246. var seasonZeroNameChanged = !string.Equals(_seasonZeroDisplayName, newSeasonZeroName, StringComparison.CurrentCulture);
  247. var wizardChanged = config.IsStartupWizardCompleted != _wizardCompleted;
  248. RecordConfigurationValues(config);
  249. Task.Run(async () =>
  250. {
  251. if (seasonZeroNameChanged)
  252. {
  253. await UpdateSeasonZeroNames(newSeasonZeroName, CancellationToken.None).ConfigureAwait(false);
  254. }
  255. if (seasonZeroNameChanged || ibnPathChanged || wizardChanged)
  256. {
  257. _taskManager.CancelIfRunningAndQueue<RefreshMediaLibraryTask>();
  258. }
  259. });
  260. }
  261. private void RemoveItemsByNameFromCache()
  262. {
  263. RemoveItemsFromCache(i => i is Person);
  264. RemoveItemsFromCache(i => i is Year);
  265. RemoveItemsFromCache(i => i is Genre);
  266. RemoveItemsFromCache(i => i is MusicGenre);
  267. RemoveItemsFromCache(i => i is GameGenre);
  268. RemoveItemsFromCache(i => i is Studio);
  269. RemoveItemsFromCache(i =>
  270. {
  271. var artist = i as MusicArtist;
  272. return artist != null && artist.IsAccessedByName;
  273. });
  274. }
  275. private void RemoveItemsFromCache(Func<BaseItem, bool> remove)
  276. {
  277. var items = _libraryItemsCache.ToList().Where(i => remove(i.Value)).ToList();
  278. foreach (var item in items)
  279. {
  280. BaseItem value;
  281. _libraryItemsCache.TryRemove(item.Key, out value);
  282. }
  283. }
  284. /// <summary>
  285. /// Updates the season zero names.
  286. /// </summary>
  287. /// <param name="newName">The new name.</param>
  288. /// <param name="cancellationToken">The cancellation token.</param>
  289. /// <returns>Task.</returns>
  290. private async Task UpdateSeasonZeroNames(string newName, CancellationToken cancellationToken)
  291. {
  292. var seasons = RootFolder.RecursiveChildren
  293. .OfType<Season>()
  294. .Where(i => i.IndexNumber.HasValue && i.IndexNumber.Value == 0 && !string.Equals(i.Name, newName, StringComparison.CurrentCulture))
  295. .ToList();
  296. foreach (var season in seasons)
  297. {
  298. season.Name = newName;
  299. try
  300. {
  301. await UpdateItem(season, ItemUpdateType.MetadataDownload, cancellationToken).ConfigureAwait(false);
  302. }
  303. catch (Exception ex)
  304. {
  305. _logger.ErrorException("Error saving {0}", ex, season.Path);
  306. }
  307. }
  308. }
  309. /// <summary>
  310. /// Updates the item in library cache.
  311. /// </summary>
  312. /// <param name="item">The item.</param>
  313. private void UpdateItemInLibraryCache(BaseItem item)
  314. {
  315. RegisterItem(item);
  316. }
  317. public void RegisterItem(BaseItem item)
  318. {
  319. if (item == null)
  320. {
  321. throw new ArgumentNullException("item");
  322. }
  323. RegisterItem(item.Id, item);
  324. }
  325. private void RegisterItem(Guid id, BaseItem item)
  326. {
  327. LibraryItemsCache.AddOrUpdate(id, item, delegate { return item; });
  328. }
  329. public async Task DeleteItem(BaseItem item, DeleteOptions options)
  330. {
  331. _logger.Debug("Deleting item, Type: {0}, Name: {1}, Path: {2}, Id: {3}",
  332. item.GetType().Name,
  333. item.Name,
  334. item.Path ?? string.Empty,
  335. item.Id);
  336. var parent = item.Parent;
  337. var locationType = item.LocationType;
  338. var children = item.IsFolder
  339. ? ((Folder)item).RecursiveChildren.ToList()
  340. : new List<BaseItem>();
  341. foreach (var metadataPath in GetMetadataPaths(item, children))
  342. {
  343. _logger.Debug("Deleting path {0}", metadataPath);
  344. try
  345. {
  346. Directory.Delete(metadataPath, true);
  347. }
  348. catch (DirectoryNotFoundException)
  349. {
  350. }
  351. catch (Exception ex)
  352. {
  353. _logger.ErrorException("Error deleting {0}", ex, metadataPath);
  354. }
  355. }
  356. if (options.DeleteFileLocation && locationType != LocationType.Remote && locationType != LocationType.Virtual)
  357. {
  358. foreach (var path in item.GetDeletePaths().ToList())
  359. {
  360. if (Directory.Exists(path))
  361. {
  362. _logger.Debug("Deleting path {0}", path);
  363. Directory.Delete(path, true);
  364. }
  365. else if (File.Exists(path))
  366. {
  367. _logger.Debug("Deleting path {0}", path);
  368. File.Delete(path);
  369. }
  370. }
  371. if (parent != null)
  372. {
  373. await parent.ValidateChildren(new Progress<double>(), CancellationToken.None)
  374. .ConfigureAwait(false);
  375. }
  376. }
  377. else if (parent != null)
  378. {
  379. await parent.RemoveChild(item, CancellationToken.None).ConfigureAwait(false);
  380. }
  381. await ItemRepository.DeleteItem(item.Id, CancellationToken.None).ConfigureAwait(false);
  382. foreach (var child in children)
  383. {
  384. await ItemRepository.DeleteItem(child.Id, CancellationToken.None).ConfigureAwait(false);
  385. }
  386. BaseItem removed;
  387. _libraryItemsCache.TryRemove(item.Id, out removed);
  388. ReportItemRemoved(item);
  389. }
  390. private IEnumerable<string> GetMetadataPaths(BaseItem item, IEnumerable<BaseItem> children)
  391. {
  392. var list = new List<string>
  393. {
  394. ConfigurationManager.ApplicationPaths.GetInternalMetadataPath(item.Id)
  395. };
  396. list.AddRange(children.Select(i => ConfigurationManager.ApplicationPaths.GetInternalMetadataPath(i.Id)));
  397. return list;
  398. }
  399. /// <summary>
  400. /// Resolves the item.
  401. /// </summary>
  402. /// <param name="args">The args.</param>
  403. /// <returns>BaseItem.</returns>
  404. public BaseItem ResolveItem(ItemResolveArgs args)
  405. {
  406. var item = EntityResolvers.Select(r =>
  407. {
  408. try
  409. {
  410. return r.ResolvePath(args);
  411. }
  412. catch (Exception ex)
  413. {
  414. _logger.ErrorException("Error in {0} resolving {1}", ex, r.GetType().Name, args.Path);
  415. return null;
  416. }
  417. }).FirstOrDefault(i => i != null);
  418. if (item != null)
  419. {
  420. ResolverHelper.SetInitialItemValues(item, args, _fileSystem);
  421. }
  422. return item;
  423. }
  424. public IEnumerable<BaseItem> ReplaceVideosWithPrimaryVersions(IEnumerable<BaseItem> items)
  425. {
  426. return items.Select(i =>
  427. {
  428. var video = i as Video;
  429. if (video != null)
  430. {
  431. if (video.PrimaryVersionId.HasValue)
  432. {
  433. var primary = GetItemById(video.PrimaryVersionId.Value) as Video;
  434. if (primary != null)
  435. {
  436. return primary;
  437. }
  438. }
  439. }
  440. return i;
  441. }).DistinctBy(i => i.Id);
  442. }
  443. /// <summary>
  444. /// Ensure supplied item has only one instance throughout
  445. /// </summary>
  446. /// <param name="item">The item.</param>
  447. /// <returns>The proper instance to the item</returns>
  448. public BaseItem GetOrAddByReferenceItem(BaseItem item)
  449. {
  450. // Add this item to our list if not there already
  451. if (!ByReferenceItems.TryAdd(item.Id, item))
  452. {
  453. // Already there - return the existing reference
  454. item = ByReferenceItems[item.Id];
  455. }
  456. return item;
  457. }
  458. public BaseItem ResolvePath(FileSystemInfo fileInfo, Folder parent = null)
  459. {
  460. return ResolvePath(fileInfo, new DirectoryService(_logger), parent);
  461. }
  462. /// <summary>
  463. /// Resolves a path into a BaseItem
  464. /// </summary>
  465. /// <param name="fileInfo">The file info.</param>
  466. /// <param name="directoryService">The directory service.</param>
  467. /// <param name="parent">The parent.</param>
  468. /// <returns>BaseItem.</returns>
  469. /// <exception cref="System.ArgumentNullException">fileInfo</exception>
  470. public BaseItem ResolvePath(FileSystemInfo fileInfo, IDirectoryService directoryService, Folder parent = null)
  471. {
  472. if (fileInfo == null)
  473. {
  474. throw new ArgumentNullException("fileInfo");
  475. }
  476. var args = new ItemResolveArgs(ConfigurationManager.ApplicationPaths, this, directoryService)
  477. {
  478. Parent = parent,
  479. Path = fileInfo.FullName,
  480. FileInfo = fileInfo
  481. };
  482. // Return null if ignore rules deem that we should do so
  483. if (EntityResolutionIgnoreRules.Any(r => r.ShouldIgnore(args)))
  484. {
  485. return null;
  486. }
  487. // Gather child folder and files
  488. if (args.IsDirectory)
  489. {
  490. var isPhysicalRoot = args.IsPhysicalRoot;
  491. // When resolving the root, we need it's grandchildren (children of user views)
  492. var flattenFolderDepth = isPhysicalRoot ? 2 : 0;
  493. var fileSystemDictionary = FileData.GetFilteredFileSystemEntries(directoryService, args.Path, _fileSystem, _logger, args, flattenFolderDepth: flattenFolderDepth, resolveShortcuts: isPhysicalRoot || args.IsVf);
  494. // Need to remove subpaths that may have been resolved from shortcuts
  495. // Example: if \\server\movies exists, then strip out \\server\movies\action
  496. if (isPhysicalRoot)
  497. {
  498. var paths = NormalizeRootPathList(fileSystemDictionary.Keys);
  499. fileSystemDictionary = paths.Select(i => (FileSystemInfo)new DirectoryInfo(i)).ToDictionary(i => i.FullName);
  500. }
  501. args.FileSystemDictionary = fileSystemDictionary;
  502. }
  503. // Check to see if we should resolve based on our contents
  504. if (args.IsDirectory && !ShouldResolvePathContents(args))
  505. {
  506. return null;
  507. }
  508. return ResolveItem(args);
  509. }
  510. public IEnumerable<string> NormalizeRootPathList(IEnumerable<string> paths)
  511. {
  512. var list = paths.Select(_fileSystem.NormalizePath)
  513. .Distinct(StringComparer.OrdinalIgnoreCase)
  514. .ToList();
  515. var dupes = list.Where(subPath => !subPath.EndsWith(":\\", StringComparison.OrdinalIgnoreCase) && list.Any(i => _fileSystem.ContainsSubPath(i, subPath)))
  516. .ToList();
  517. foreach (var dupe in dupes)
  518. {
  519. _logger.Info("Found duplicate path: {0}", dupe);
  520. }
  521. return list.Except(dupes, StringComparer.OrdinalIgnoreCase);
  522. }
  523. /// <summary>
  524. /// Determines whether a path should be ignored based on its contents - called after the contents have been read
  525. /// </summary>
  526. /// <param name="args">The args.</param>
  527. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  528. private static bool ShouldResolvePathContents(ItemResolveArgs args)
  529. {
  530. // Ignore any folders containing a file called .ignore
  531. return !args.ContainsFileSystemEntryByName(".ignore");
  532. }
  533. /// <summary>
  534. /// Resolves a set of files into a list of BaseItem
  535. /// </summary>
  536. /// <typeparam name="T"></typeparam>
  537. /// <param name="files">The files.</param>
  538. /// <param name="directoryService">The directory service.</param>
  539. /// <param name="parent">The parent.</param>
  540. /// <returns>List{``0}.</returns>
  541. public List<T> ResolvePaths<T>(IEnumerable<FileSystemInfo> files, IDirectoryService directoryService, Folder parent)
  542. where T : BaseItem
  543. {
  544. var list = new List<T>();
  545. Parallel.ForEach(files, f =>
  546. {
  547. try
  548. {
  549. var item = ResolvePath(f, directoryService, parent) as T;
  550. if (item != null)
  551. {
  552. lock (list)
  553. {
  554. list.Add(item);
  555. }
  556. }
  557. }
  558. catch (Exception ex)
  559. {
  560. _logger.ErrorException("Error resolving path {0}", ex, f.FullName);
  561. }
  562. });
  563. return list;
  564. }
  565. /// <summary>
  566. /// Creates the root media folder
  567. /// </summary>
  568. /// <returns>AggregateFolder.</returns>
  569. /// <exception cref="System.InvalidOperationException">Cannot create the root folder until plugins have loaded</exception>
  570. public AggregateFolder CreateRootFolder()
  571. {
  572. var rootFolderPath = ConfigurationManager.ApplicationPaths.RootFolderPath;
  573. Directory.CreateDirectory(rootFolderPath);
  574. var rootFolder = GetItemById(rootFolderPath.GetMBId(typeof(AggregateFolder))) as AggregateFolder ?? (AggregateFolder)ResolvePath(new DirectoryInfo(rootFolderPath));
  575. // Add in the plug-in folders
  576. foreach (var child in PluginFolderCreators)
  577. {
  578. var folder = child.GetFolder();
  579. if (folder.Id == Guid.Empty)
  580. {
  581. folder.Id = (folder.Path ?? folder.GetType().Name).GetMBId(folder.GetType());
  582. }
  583. rootFolder.AddVirtualChild(folder);
  584. RegisterItem(folder);
  585. }
  586. return rootFolder;
  587. }
  588. private UserRootFolder _userRootFolder;
  589. public Folder GetUserRootFolder()
  590. {
  591. if (_userRootFolder == null)
  592. {
  593. var userRootPath = ConfigurationManager.ApplicationPaths.DefaultUserViewsPath;
  594. Directory.CreateDirectory(userRootPath);
  595. _userRootFolder = GetItemById(userRootPath.GetMBId(typeof(UserRootFolder))) as UserRootFolder ??
  596. (UserRootFolder)ResolvePath(new DirectoryInfo(userRootPath));
  597. }
  598. return _userRootFolder;
  599. }
  600. /// <summary>
  601. /// Gets a Person
  602. /// </summary>
  603. /// <param name="name">The name.</param>
  604. /// <returns>Task{Person}.</returns>
  605. public Person GetPerson(string name)
  606. {
  607. return GetItemByName<Person>(ConfigurationManager.ApplicationPaths.PeoplePath, name);
  608. }
  609. /// <summary>
  610. /// Gets a Studio
  611. /// </summary>
  612. /// <param name="name">The name.</param>
  613. /// <returns>Task{Studio}.</returns>
  614. public Studio GetStudio(string name)
  615. {
  616. return GetItemByName<Studio>(ConfigurationManager.ApplicationPaths.StudioPath, name);
  617. }
  618. /// <summary>
  619. /// Gets a Genre
  620. /// </summary>
  621. /// <param name="name">The name.</param>
  622. /// <returns>Task{Genre}.</returns>
  623. public Genre GetGenre(string name)
  624. {
  625. return GetItemByName<Genre>(ConfigurationManager.ApplicationPaths.GenrePath, name);
  626. }
  627. /// <summary>
  628. /// Gets the genre.
  629. /// </summary>
  630. /// <param name="name">The name.</param>
  631. /// <returns>Task{MusicGenre}.</returns>
  632. public MusicGenre GetMusicGenre(string name)
  633. {
  634. return GetItemByName<MusicGenre>(ConfigurationManager.ApplicationPaths.MusicGenrePath, name);
  635. }
  636. /// <summary>
  637. /// Gets the game genre.
  638. /// </summary>
  639. /// <param name="name">The name.</param>
  640. /// <returns>Task{GameGenre}.</returns>
  641. public GameGenre GetGameGenre(string name)
  642. {
  643. return GetItemByName<GameGenre>(ConfigurationManager.ApplicationPaths.GameGenrePath, name);
  644. }
  645. /// <summary>
  646. /// The us culture
  647. /// </summary>
  648. private static readonly CultureInfo UsCulture = new CultureInfo("en-US");
  649. /// <summary>
  650. /// Gets a Year
  651. /// </summary>
  652. /// <param name="value">The value.</param>
  653. /// <returns>Task{Year}.</returns>
  654. /// <exception cref="System.ArgumentOutOfRangeException"></exception>
  655. public Year GetYear(int value)
  656. {
  657. if (value <= 0)
  658. {
  659. throw new ArgumentOutOfRangeException("Years less than or equal to 0 are invalid.");
  660. }
  661. return GetItemByName<Year>(ConfigurationManager.ApplicationPaths.YearPath, value.ToString(UsCulture));
  662. }
  663. /// <summary>
  664. /// Gets a Genre
  665. /// </summary>
  666. /// <param name="name">The name.</param>
  667. /// <returns>Task{Genre}.</returns>
  668. public MusicArtist GetArtist(string name)
  669. {
  670. return GetItemByName<MusicArtist>(ConfigurationManager.ApplicationPaths.ArtistsPath, name);
  671. }
  672. private T GetItemByName<T>(string path, string name)
  673. where T : BaseItem, new()
  674. {
  675. if (string.IsNullOrWhiteSpace(path))
  676. {
  677. throw new ArgumentNullException("path");
  678. }
  679. if (string.IsNullOrWhiteSpace(name))
  680. {
  681. throw new ArgumentNullException("name");
  682. }
  683. var validFilename = _fileSystem.GetValidFilename(name).Trim();
  684. string subFolderPrefix = null;
  685. var type = typeof(T);
  686. if (type == typeof(Person) && ConfigurationManager.Configuration.EnablePeoplePrefixSubFolders)
  687. {
  688. subFolderPrefix = validFilename.Substring(0, 1);
  689. }
  690. var fullPath = string.IsNullOrEmpty(subFolderPrefix) ?
  691. Path.Combine(path, validFilename) :
  692. Path.Combine(path, subFolderPrefix, validFilename);
  693. var id = fullPath.GetMBId(type);
  694. BaseItem obj;
  695. if (!_libraryItemsCache.TryGetValue(id, out obj))
  696. {
  697. obj = CreateItemByName<T>(fullPath, name, id);
  698. RegisterItem(id, obj);
  699. }
  700. return obj as T;
  701. }
  702. /// <summary>
  703. /// Creates an IBN item based on a given path
  704. /// </summary>
  705. /// <typeparam name="T"></typeparam>
  706. /// <param name="path">The path.</param>
  707. /// <param name="name">The name.</param>
  708. /// <returns>Task{``0}.</returns>
  709. /// <exception cref="System.IO.IOException">Path not created: + path</exception>
  710. private T CreateItemByName<T>(string path, string name, Guid id)
  711. where T : BaseItem, new()
  712. {
  713. var isArtist = typeof(T) == typeof(MusicArtist);
  714. if (isArtist)
  715. {
  716. var existing = RootFolder.RecursiveChildren
  717. .OfType<T>()
  718. .FirstOrDefault(i => string.Equals(i.Name, name, StringComparison.OrdinalIgnoreCase));
  719. if (existing != null)
  720. {
  721. return existing;
  722. }
  723. }
  724. var fileInfo = new DirectoryInfo(path);
  725. var isNew = false;
  726. if (!fileInfo.Exists)
  727. {
  728. Directory.CreateDirectory(path);
  729. fileInfo = new DirectoryInfo(path);
  730. if (!fileInfo.Exists)
  731. {
  732. throw new IOException("Path not created: " + path);
  733. }
  734. isNew = true;
  735. }
  736. var item = isNew ? null : GetItemById(id) as T;
  737. if (item == null)
  738. {
  739. item = new T
  740. {
  741. Name = name,
  742. Id = id,
  743. DateCreated = _fileSystem.GetCreationTimeUtc(fileInfo),
  744. DateModified = _fileSystem.GetLastWriteTimeUtc(fileInfo),
  745. Path = path
  746. };
  747. }
  748. if (isArtist)
  749. {
  750. (item as MusicArtist).IsAccessedByName = true;
  751. }
  752. return item;
  753. }
  754. /// <summary>
  755. /// Validate and refresh the People sub-set of the IBN.
  756. /// The items are stored in the db but not loaded into memory until actually requested by an operation.
  757. /// </summary>
  758. /// <param name="cancellationToken">The cancellation token.</param>
  759. /// <param name="progress">The progress.</param>
  760. /// <returns>Task.</returns>
  761. public Task ValidatePeople(CancellationToken cancellationToken, IProgress<double> progress)
  762. {
  763. // Ensure the location is available.
  764. Directory.CreateDirectory(ConfigurationManager.ApplicationPaths.PeoplePath);
  765. return new PeopleValidator(this, _logger).ValidatePeople(cancellationToken, new MetadataRefreshOptions(), progress);
  766. }
  767. /// <summary>
  768. /// Validates the artists.
  769. /// </summary>
  770. /// <param name="cancellationToken">The cancellation token.</param>
  771. /// <param name="progress">The progress.</param>
  772. /// <returns>Task.</returns>
  773. public Task ValidateArtists(CancellationToken cancellationToken, IProgress<double> progress)
  774. {
  775. // Ensure the location is unavailable.
  776. Directory.CreateDirectory(ConfigurationManager.ApplicationPaths.ArtistsPath);
  777. return new ArtistsValidator(this, _userManager, _logger).Run(progress, cancellationToken);
  778. }
  779. /// <summary>
  780. /// Validates the music genres.
  781. /// </summary>
  782. /// <param name="cancellationToken">The cancellation token.</param>
  783. /// <param name="progress">The progress.</param>
  784. /// <returns>Task.</returns>
  785. public Task ValidateMusicGenres(CancellationToken cancellationToken, IProgress<double> progress)
  786. {
  787. // Ensure the location is unavailable.
  788. Directory.CreateDirectory(ConfigurationManager.ApplicationPaths.MusicGenrePath);
  789. return new MusicGenresValidator(this, _logger).Run(progress, cancellationToken);
  790. }
  791. /// <summary>
  792. /// Validates the game genres.
  793. /// </summary>
  794. /// <param name="cancellationToken">The cancellation token.</param>
  795. /// <param name="progress">The progress.</param>
  796. /// <returns>Task.</returns>
  797. public Task ValidateGameGenres(CancellationToken cancellationToken, IProgress<double> progress)
  798. {
  799. // Ensure the location is unavailable.
  800. Directory.CreateDirectory(ConfigurationManager.ApplicationPaths.GameGenrePath);
  801. return new GameGenresValidator(this, _userManager, _logger).Run(progress, cancellationToken);
  802. }
  803. /// <summary>
  804. /// Validates the studios.
  805. /// </summary>
  806. /// <param name="cancellationToken">The cancellation token.</param>
  807. /// <param name="progress">The progress.</param>
  808. /// <returns>Task.</returns>
  809. public Task ValidateStudios(CancellationToken cancellationToken, IProgress<double> progress)
  810. {
  811. // Ensure the location is unavailable.
  812. Directory.CreateDirectory(ConfigurationManager.ApplicationPaths.StudioPath);
  813. return new StudiosValidator(this, _userManager, _logger).Run(progress, cancellationToken);
  814. }
  815. /// <summary>
  816. /// Validates the genres.
  817. /// </summary>
  818. /// <param name="cancellationToken">The cancellation token.</param>
  819. /// <param name="progress">The progress.</param>
  820. /// <returns>Task.</returns>
  821. public Task ValidateGenres(CancellationToken cancellationToken, IProgress<double> progress)
  822. {
  823. // Ensure the location is unavailable.
  824. Directory.CreateDirectory(ConfigurationManager.ApplicationPaths.GenrePath);
  825. return new GenresValidator(this, _userManager, _logger).Run(progress, cancellationToken);
  826. }
  827. /// <summary>
  828. /// Reloads the root media folder
  829. /// </summary>
  830. /// <param name="progress">The progress.</param>
  831. /// <param name="cancellationToken">The cancellation token.</param>
  832. /// <returns>Task.</returns>
  833. public Task ValidateMediaLibrary(IProgress<double> progress, CancellationToken cancellationToken)
  834. {
  835. // Just run the scheduled task so that the user can see it
  836. _taskManager.CancelIfRunningAndQueue<RefreshMediaLibraryTask>();
  837. return Task.FromResult(true);
  838. }
  839. /// <summary>
  840. /// Queues the library scan.
  841. /// </summary>
  842. public void QueueLibraryScan()
  843. {
  844. // Just run the scheduled task so that the user can see it
  845. _taskManager.QueueScheduledTask<RefreshMediaLibraryTask>();
  846. }
  847. /// <summary>
  848. /// Validates the media library internal.
  849. /// </summary>
  850. /// <param name="progress">The progress.</param>
  851. /// <param name="cancellationToken">The cancellation token.</param>
  852. /// <returns>Task.</returns>
  853. public async Task ValidateMediaLibraryInternal(IProgress<double> progress, CancellationToken cancellationToken)
  854. {
  855. _libraryMonitorFactory().Stop();
  856. try
  857. {
  858. await PerformLibraryValidation(progress, cancellationToken).ConfigureAwait(false);
  859. }
  860. finally
  861. {
  862. _libraryMonitorFactory().Start();
  863. }
  864. }
  865. private async Task PerformLibraryValidation(IProgress<double> progress, CancellationToken cancellationToken)
  866. {
  867. _logger.Info("Validating media library");
  868. await RootFolder.RefreshMetadata(cancellationToken).ConfigureAwait(false);
  869. progress.Report(.5);
  870. // Start by just validating the children of the root, but go no further
  871. await RootFolder.ValidateChildren(new Progress<double>(), cancellationToken, new MetadataRefreshOptions(), recursive: false);
  872. progress.Report(1);
  873. var userRoot = GetUserRootFolder();
  874. await userRoot.RefreshMetadata(cancellationToken).ConfigureAwait(false);
  875. await userRoot.ValidateChildren(new Progress<double>(), cancellationToken, new MetadataRefreshOptions(), recursive: false).ConfigureAwait(false);
  876. progress.Report(2);
  877. var innerProgress = new ActionableProgress<double>();
  878. innerProgress.RegisterAction(pct => progress.Report(2 + pct * .73));
  879. // Now validate the entire media library
  880. await RootFolder.ValidateChildren(innerProgress, cancellationToken, new MetadataRefreshOptions(), recursive: true).ConfigureAwait(false);
  881. progress.Report(75);
  882. innerProgress = new ActionableProgress<double>();
  883. innerProgress.RegisterAction(pct => progress.Report(75 + pct * .25));
  884. // Run post-scan tasks
  885. await RunPostScanTasks(innerProgress, cancellationToken).ConfigureAwait(false);
  886. progress.Report(100);
  887. // Bad practice, i know. But we keep a lot in memory, unfortunately.
  888. GC.Collect(2, GCCollectionMode.Forced, true);
  889. GC.Collect(2, GCCollectionMode.Forced, true);
  890. }
  891. /// <summary>
  892. /// Runs the post scan tasks.
  893. /// </summary>
  894. /// <param name="progress">The progress.</param>
  895. /// <param name="cancellationToken">The cancellation token.</param>
  896. /// <returns>Task.</returns>
  897. private async Task RunPostScanTasks(IProgress<double> progress, CancellationToken cancellationToken)
  898. {
  899. var tasks = PostscanTasks.ToList();
  900. var numComplete = 0;
  901. var numTasks = tasks.Count;
  902. foreach (var task in tasks)
  903. {
  904. var innerProgress = new ActionableProgress<double>();
  905. // Prevent access to modified closure
  906. var currentNumComplete = numComplete;
  907. innerProgress.RegisterAction(pct =>
  908. {
  909. double innerPercent = (currentNumComplete * 100) + pct;
  910. innerPercent /= numTasks;
  911. progress.Report(innerPercent);
  912. });
  913. try
  914. {
  915. await task.Run(innerProgress, cancellationToken);
  916. }
  917. catch (OperationCanceledException)
  918. {
  919. _logger.Info("Post-scan task cancelled: {0}", task.GetType().Name);
  920. }
  921. catch (Exception ex)
  922. {
  923. _logger.ErrorException("Error running postscan task", ex);
  924. }
  925. numComplete++;
  926. double percent = numComplete;
  927. percent /= numTasks;
  928. progress.Report(percent * 100);
  929. }
  930. progress.Report(100);
  931. }
  932. /// <summary>
  933. /// Gets the default view.
  934. /// </summary>
  935. /// <returns>IEnumerable{VirtualFolderInfo}.</returns>
  936. public IEnumerable<VirtualFolderInfo> GetDefaultVirtualFolders()
  937. {
  938. return GetView(ConfigurationManager.ApplicationPaths.DefaultUserViewsPath);
  939. }
  940. /// <summary>
  941. /// Gets the view.
  942. /// </summary>
  943. /// <param name="user">The user.</param>
  944. /// <returns>IEnumerable{VirtualFolderInfo}.</returns>
  945. public IEnumerable<VirtualFolderInfo> GetVirtualFolders(User user)
  946. {
  947. return GetDefaultVirtualFolders();
  948. }
  949. /// <summary>
  950. /// Gets the view.
  951. /// </summary>
  952. /// <param name="path">The path.</param>
  953. /// <returns>IEnumerable{VirtualFolderInfo}.</returns>
  954. private IEnumerable<VirtualFolderInfo> GetView(string path)
  955. {
  956. return Directory.EnumerateDirectories(path, "*", SearchOption.TopDirectoryOnly)
  957. .Select(dir => new VirtualFolderInfo
  958. {
  959. Name = Path.GetFileName(dir),
  960. Locations = Directory.EnumerateFiles(dir, "*.mblink", SearchOption.TopDirectoryOnly)
  961. .Select(_fileSystem.ResolveShortcut)
  962. .OrderBy(i => i)
  963. .ToList(),
  964. CollectionType = GetCollectionType(dir)
  965. });
  966. }
  967. private string GetCollectionType(string path)
  968. {
  969. return new DirectoryInfo(path).EnumerateFiles("*.collection", SearchOption.TopDirectoryOnly)
  970. .Select(i => Path.GetFileNameWithoutExtension(i.FullName))
  971. .FirstOrDefault();
  972. }
  973. /// <summary>
  974. /// Gets the item by id.
  975. /// </summary>
  976. /// <param name="id">The id.</param>
  977. /// <returns>BaseItem.</returns>
  978. /// <exception cref="System.ArgumentNullException">id</exception>
  979. public BaseItem GetItemById(Guid id)
  980. {
  981. if (id == Guid.Empty)
  982. {
  983. throw new ArgumentNullException("id");
  984. }
  985. BaseItem item;
  986. if (LibraryItemsCache.TryGetValue(id, out item))
  987. {
  988. return item;
  989. }
  990. item = RetrieveItem(id);
  991. if (item != null)
  992. {
  993. RegisterItem(item);
  994. }
  995. return item;
  996. }
  997. /// <summary>
  998. /// Gets the intros.
  999. /// </summary>
  1000. /// <param name="item">The item.</param>
  1001. /// <param name="user">The user.</param>
  1002. /// <returns>IEnumerable{System.String}.</returns>
  1003. public IEnumerable<Video> GetIntros(BaseItem item, User user)
  1004. {
  1005. return IntroProviders.SelectMany(i => i.GetIntros(item, user))
  1006. .Select(ResolveIntro)
  1007. .Where(i => i != null);
  1008. }
  1009. /// <summary>
  1010. /// Gets all intro files.
  1011. /// </summary>
  1012. /// <returns>IEnumerable{System.String}.</returns>
  1013. public IEnumerable<string> GetAllIntroFiles()
  1014. {
  1015. return IntroProviders.SelectMany(i => i.GetAllIntroFiles());
  1016. }
  1017. /// <summary>
  1018. /// Resolves the intro.
  1019. /// </summary>
  1020. /// <param name="info">The info.</param>
  1021. /// <returns>Video.</returns>
  1022. private Video ResolveIntro(IntroInfo info)
  1023. {
  1024. Video video = null;
  1025. if (info.ItemId.HasValue)
  1026. {
  1027. // Get an existing item by Id
  1028. video = GetItemById(info.ItemId.Value) as Video;
  1029. if (video == null)
  1030. {
  1031. _logger.Error("Unable to locate item with Id {0}.", info.ItemId.Value);
  1032. }
  1033. }
  1034. else if (!string.IsNullOrEmpty(info.Path))
  1035. {
  1036. try
  1037. {
  1038. // Try to resolve the path into a video
  1039. video = ResolvePath(_fileSystem.GetFileSystemInfo(info.Path)) as Video;
  1040. if (video == null)
  1041. {
  1042. _logger.Error("Intro resolver returned null for {0}.", info.Path);
  1043. }
  1044. else
  1045. {
  1046. // Pull the saved db item that will include metadata
  1047. var dbItem = GetItemById(video.Id) as Video;
  1048. if (dbItem != null)
  1049. {
  1050. video = dbItem;
  1051. }
  1052. }
  1053. }
  1054. catch (Exception ex)
  1055. {
  1056. _logger.ErrorException("Error resolving path {0}.", ex, info.Path);
  1057. }
  1058. }
  1059. else
  1060. {
  1061. _logger.Error("IntroProvider returned an IntroInfo with null Path and ItemId.");
  1062. }
  1063. return video;
  1064. }
  1065. /// <summary>
  1066. /// Sorts the specified sort by.
  1067. /// </summary>
  1068. /// <param name="items">The items.</param>
  1069. /// <param name="user">The user.</param>
  1070. /// <param name="sortBy">The sort by.</param>
  1071. /// <param name="sortOrder">The sort order.</param>
  1072. /// <returns>IEnumerable{BaseItem}.</returns>
  1073. public IEnumerable<BaseItem> Sort(IEnumerable<BaseItem> items, User user, IEnumerable<string> sortBy, SortOrder sortOrder)
  1074. {
  1075. var isFirst = true;
  1076. IOrderedEnumerable<BaseItem> orderedItems = null;
  1077. foreach (var orderBy in sortBy.Select(o => GetComparer(o, user)).Where(c => c != null))
  1078. {
  1079. if (isFirst)
  1080. {
  1081. orderedItems = sortOrder == SortOrder.Descending ? items.OrderByDescending(i => i, orderBy) : items.OrderBy(i => i, orderBy);
  1082. }
  1083. else
  1084. {
  1085. orderedItems = sortOrder == SortOrder.Descending ? orderedItems.ThenByDescending(i => i, orderBy) : orderedItems.ThenBy(i => i, orderBy);
  1086. }
  1087. isFirst = false;
  1088. }
  1089. return orderedItems ?? items;
  1090. }
  1091. /// <summary>
  1092. /// Gets the comparer.
  1093. /// </summary>
  1094. /// <param name="name">The name.</param>
  1095. /// <param name="user">The user.</param>
  1096. /// <returns>IBaseItemComparer.</returns>
  1097. private IBaseItemComparer GetComparer(string name, User user)
  1098. {
  1099. var comparer = Comparers.FirstOrDefault(c => string.Equals(name, c.Name, StringComparison.OrdinalIgnoreCase));
  1100. if (comparer != null)
  1101. {
  1102. // If it requires a user, create a new one, and assign the user
  1103. if (comparer is IUserBaseItemComparer)
  1104. {
  1105. var userComparer = (IUserBaseItemComparer)Activator.CreateInstance(comparer.GetType());
  1106. userComparer.User = user;
  1107. userComparer.UserManager = _userManager;
  1108. userComparer.UserDataRepository = _userDataRepository;
  1109. return userComparer;
  1110. }
  1111. }
  1112. return comparer;
  1113. }
  1114. /// <summary>
  1115. /// Creates the item.
  1116. /// </summary>
  1117. /// <param name="item">The item.</param>
  1118. /// <param name="cancellationToken">The cancellation token.</param>
  1119. /// <returns>Task.</returns>
  1120. public Task CreateItem(BaseItem item, CancellationToken cancellationToken)
  1121. {
  1122. return CreateItems(new[] { item }, cancellationToken);
  1123. }
  1124. /// <summary>
  1125. /// Creates the items.
  1126. /// </summary>
  1127. /// <param name="items">The items.</param>
  1128. /// <param name="cancellationToken">The cancellation token.</param>
  1129. /// <returns>Task.</returns>
  1130. public async Task CreateItems(IEnumerable<BaseItem> items, CancellationToken cancellationToken)
  1131. {
  1132. var list = items.ToList();
  1133. await ItemRepository.SaveItems(list, cancellationToken).ConfigureAwait(false);
  1134. foreach (var item in list)
  1135. {
  1136. UpdateItemInLibraryCache(item);
  1137. }
  1138. if (ItemAdded != null)
  1139. {
  1140. foreach (var item in list)
  1141. {
  1142. try
  1143. {
  1144. ItemAdded(this, new ItemChangeEventArgs { Item = item });
  1145. }
  1146. catch (Exception ex)
  1147. {
  1148. _logger.ErrorException("Error in ItemAdded event handler", ex);
  1149. }
  1150. }
  1151. }
  1152. }
  1153. /// <summary>
  1154. /// Updates the item.
  1155. /// </summary>
  1156. /// <param name="item">The item.</param>
  1157. /// <param name="updateReason">The update reason.</param>
  1158. /// <param name="cancellationToken">The cancellation token.</param>
  1159. /// <returns>Task.</returns>
  1160. public async Task UpdateItem(BaseItem item, ItemUpdateType updateReason, CancellationToken cancellationToken)
  1161. {
  1162. var locationType = item.LocationType;
  1163. if (locationType != LocationType.Remote && locationType != LocationType.Virtual)
  1164. {
  1165. await _providerManagerFactory().SaveMetadata(item, updateReason).ConfigureAwait(false);
  1166. }
  1167. item.DateLastSaved = DateTime.UtcNow;
  1168. _logger.Debug("Saving {0} to database.", item.Path ?? item.Name);
  1169. await ItemRepository.SaveItem(item, cancellationToken).ConfigureAwait(false);
  1170. UpdateItemInLibraryCache(item);
  1171. if (ItemUpdated != null)
  1172. {
  1173. try
  1174. {
  1175. ItemUpdated(this, new ItemChangeEventArgs
  1176. {
  1177. Item = item,
  1178. UpdateReason = updateReason
  1179. });
  1180. }
  1181. catch (Exception ex)
  1182. {
  1183. _logger.ErrorException("Error in ItemUpdated event handler", ex);
  1184. }
  1185. }
  1186. }
  1187. /// <summary>
  1188. /// Reports the item removed.
  1189. /// </summary>
  1190. /// <param name="item">The item.</param>
  1191. public void ReportItemRemoved(BaseItem item)
  1192. {
  1193. if (ItemRemoved != null)
  1194. {
  1195. try
  1196. {
  1197. ItemRemoved(this, new ItemChangeEventArgs { Item = item });
  1198. }
  1199. catch (Exception ex)
  1200. {
  1201. _logger.ErrorException("Error in ItemRemoved event handler", ex);
  1202. }
  1203. }
  1204. }
  1205. /// <summary>
  1206. /// Retrieves the item.
  1207. /// </summary>
  1208. /// <param name="id">The id.</param>
  1209. /// <returns>BaseItem.</returns>
  1210. public BaseItem RetrieveItem(Guid id)
  1211. {
  1212. return ItemRepository.RetrieveItem(id);
  1213. }
  1214. /// <summary>
  1215. /// Finds the type of the collection.
  1216. /// </summary>
  1217. /// <param name="item">The item.</param>
  1218. /// <returns>System.String.</returns>
  1219. public string FindCollectionType(BaseItem item)
  1220. {
  1221. while (!(item.Parent is AggregateFolder) && item.Parent != null)
  1222. {
  1223. item = item.Parent;
  1224. }
  1225. if (item == null)
  1226. {
  1227. return null;
  1228. }
  1229. var collectionTypes = _userManager.Users
  1230. .Select(i => i.RootFolder)
  1231. .Distinct()
  1232. .SelectMany(i => i.Children)
  1233. .OfType<CollectionFolder>()
  1234. .Where(i => string.Equals(i.Path, item.Path, StringComparison.OrdinalIgnoreCase) || i.PhysicalLocations.Contains(item.Path))
  1235. .Select(i => i.CollectionType)
  1236. .Where(i => !string.IsNullOrEmpty(i))
  1237. .Distinct()
  1238. .ToList();
  1239. return collectionTypes.Count == 1 ? collectionTypes[0] : null;
  1240. }
  1241. public IEnumerable<string> GetAllArtists()
  1242. {
  1243. return GetAllArtists(RootFolder.RecursiveChildren);
  1244. }
  1245. public IEnumerable<string> GetAllArtists(IEnumerable<BaseItem> items)
  1246. {
  1247. return items
  1248. .OfType<Audio>()
  1249. .SelectMany(i =>
  1250. {
  1251. var list = new List<string>();
  1252. if (!string.IsNullOrEmpty(i.AlbumArtist))
  1253. {
  1254. list.Add(i.AlbumArtist);
  1255. }
  1256. list.AddRange(i.Artists);
  1257. return list;
  1258. })
  1259. .Distinct(StringComparer.OrdinalIgnoreCase);
  1260. }
  1261. }
  1262. }