LibraryManager.cs 52 KB

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