2
0

LibraryManager.cs 53 KB

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