2
0

LibraryManager.cs 51 KB

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