LibraryManager.cs 54 KB

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