LibraryManager.cs 54 KB

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