LibraryManager.cs 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525
  1. using MediaBrowser.Common.Extensions;
  2. using MediaBrowser.Common.IO;
  3. using MediaBrowser.Common.Progress;
  4. using MediaBrowser.Common.ScheduledTasks;
  5. using MediaBrowser.Controller.Configuration;
  6. using MediaBrowser.Controller.Entities;
  7. using MediaBrowser.Controller.Entities.Audio;
  8. using MediaBrowser.Controller.Entities.TV;
  9. using MediaBrowser.Controller.IO;
  10. using MediaBrowser.Controller.Library;
  11. using MediaBrowser.Controller.Persistence;
  12. using MediaBrowser.Controller.Providers;
  13. using MediaBrowser.Controller.Resolvers;
  14. using MediaBrowser.Controller.Sorting;
  15. using MediaBrowser.Model.Configuration;
  16. using MediaBrowser.Model.Entities;
  17. using MediaBrowser.Model.Logging;
  18. using MediaBrowser.Server.Implementations.Library.Validators;
  19. using MediaBrowser.Server.Implementations.ScheduledTasks;
  20. using System;
  21. using System.Collections.Concurrent;
  22. using System.Collections.Generic;
  23. using System.Globalization;
  24. using System.IO;
  25. using System.Linq;
  26. using System.Threading;
  27. using System.Threading.Tasks;
  28. using SortOrder = MediaBrowser.Model.Entities.SortOrder;
  29. namespace MediaBrowser.Server.Implementations.Library
  30. {
  31. /// <summary>
  32. /// Class LibraryManager
  33. /// </summary>
  34. public class LibraryManager : ILibraryManager
  35. {
  36. /// <summary>
  37. /// Gets or sets the postscan tasks.
  38. /// </summary>
  39. /// <value>The postscan tasks.</value>
  40. private ILibraryPostScanTask[] PostscanTasks { get; set; }
  41. /// <summary>
  42. /// Gets the intro providers.
  43. /// </summary>
  44. /// <value>The intro providers.</value>
  45. private IIntroProvider[] IntroProviders { get; set; }
  46. /// <summary>
  47. /// Gets the list of entity resolution ignore rules
  48. /// </summary>
  49. /// <value>The entity resolution ignore rules.</value>
  50. private IResolverIgnoreRule[] EntityResolutionIgnoreRules { get; set; }
  51. /// <summary>
  52. /// Gets the list of BasePluginFolders added by plugins
  53. /// </summary>
  54. /// <value>The plugin folders.</value>
  55. private IVirtualFolderCreator[] PluginFolderCreators { get; set; }
  56. /// <summary>
  57. /// Gets the list of currently registered entity resolvers
  58. /// </summary>
  59. /// <value>The entity resolvers enumerable.</value>
  60. private IItemResolver[] EntityResolvers { get; set; }
  61. /// <summary>
  62. /// Gets or sets the comparers.
  63. /// </summary>
  64. /// <value>The comparers.</value>
  65. private IBaseItemComparer[] Comparers { get; set; }
  66. /// <summary>
  67. /// Gets the active item repository
  68. /// </summary>
  69. /// <value>The item repository.</value>
  70. public IItemRepository ItemRepository { get; set; }
  71. /// <summary>
  72. /// Occurs when [item added].
  73. /// </summary>
  74. public event EventHandler<ItemChangeEventArgs> ItemAdded;
  75. /// <summary>
  76. /// Occurs when [item updated].
  77. /// </summary>
  78. public event EventHandler<ItemChangeEventArgs> ItemUpdated;
  79. /// <summary>
  80. /// Occurs when [item removed].
  81. /// </summary>
  82. public event EventHandler<ItemChangeEventArgs> ItemRemoved;
  83. /// <summary>
  84. /// The _logger
  85. /// </summary>
  86. private readonly ILogger _logger;
  87. /// <summary>
  88. /// The _task manager
  89. /// </summary>
  90. private readonly ITaskManager _taskManager;
  91. /// <summary>
  92. /// The _user manager
  93. /// </summary>
  94. private readonly IUserManager _userManager;
  95. /// <summary>
  96. /// The _user data repository
  97. /// </summary>
  98. private readonly IUserDataManager _userDataRepository;
  99. /// <summary>
  100. /// Gets or sets the configuration manager.
  101. /// </summary>
  102. /// <value>The configuration manager.</value>
  103. private IServerConfigurationManager ConfigurationManager { get; set; }
  104. /// <summary>
  105. /// A collection of items that may be referenced from multiple physical places in the library
  106. /// (typically, multiple user roots). We store them here and be sure they all reference a
  107. /// single instance.
  108. /// </summary>
  109. /// <value>The by reference items.</value>
  110. private ConcurrentDictionary<Guid, BaseItem> ByReferenceItems { get; set; }
  111. private readonly Func<ILibraryMonitor> _libraryMonitorFactory;
  112. private readonly Func<IProviderManager> _providerManagerFactory;
  113. /// <summary>
  114. /// The _library items cache
  115. /// </summary>
  116. private ConcurrentDictionary<Guid, BaseItem> _libraryItemsCache;
  117. /// <summary>
  118. /// The _library items cache sync lock
  119. /// </summary>
  120. private object _libraryItemsCacheSyncLock = new object();
  121. /// <summary>
  122. /// The _library items cache initialized
  123. /// </summary>
  124. private bool _libraryItemsCacheInitialized;
  125. /// <summary>
  126. /// Gets the library items cache.
  127. /// </summary>
  128. /// <value>The library items cache.</value>
  129. private ConcurrentDictionary<Guid, BaseItem> LibraryItemsCache
  130. {
  131. get
  132. {
  133. LazyInitializer.EnsureInitialized(ref _libraryItemsCache, ref _libraryItemsCacheInitialized, ref _libraryItemsCacheSyncLock, CreateLibraryItemsCache);
  134. return _libraryItemsCache;
  135. }
  136. }
  137. private readonly IFileSystem _fileSystem;
  138. /// <summary>
  139. /// Initializes a new instance of the <see cref="LibraryManager" /> class.
  140. /// </summary>
  141. /// <param name="logger">The logger.</param>
  142. /// <param name="taskManager">The task manager.</param>
  143. /// <param name="userManager">The user manager.</param>
  144. /// <param name="configurationManager">The configuration manager.</param>
  145. /// <param name="userDataRepository">The user data repository.</param>
  146. public LibraryManager(ILogger logger, ITaskManager taskManager, IUserManager userManager, IServerConfigurationManager configurationManager, IUserDataManager userDataRepository, Func<ILibraryMonitor> libraryMonitorFactory, IFileSystem fileSystem, Func<IProviderManager> providerManagerFactory)
  147. {
  148. _logger = logger;
  149. _taskManager = taskManager;
  150. _userManager = userManager;
  151. ConfigurationManager = configurationManager;
  152. _userDataRepository = userDataRepository;
  153. _libraryMonitorFactory = libraryMonitorFactory;
  154. _fileSystem = fileSystem;
  155. _providerManagerFactory = providerManagerFactory;
  156. ByReferenceItems = new ConcurrentDictionary<Guid, BaseItem>();
  157. ConfigurationManager.ConfigurationUpdated += ConfigurationUpdated;
  158. RecordConfigurationValues(configurationManager.Configuration);
  159. }
  160. /// <summary>
  161. /// Adds the parts.
  162. /// </summary>
  163. /// <param name="rules">The rules.</param>
  164. /// <param name="pluginFolders">The plugin folders.</param>
  165. /// <param name="resolvers">The resolvers.</param>
  166. /// <param name="introProviders">The intro providers.</param>
  167. /// <param name="itemComparers">The item comparers.</param>
  168. /// <param name="postscanTasks">The postscan tasks.</param>
  169. public void AddParts(IEnumerable<IResolverIgnoreRule> rules,
  170. IEnumerable<IVirtualFolderCreator> pluginFolders,
  171. IEnumerable<IItemResolver> resolvers,
  172. IEnumerable<IIntroProvider> introProviders,
  173. IEnumerable<IBaseItemComparer> itemComparers,
  174. IEnumerable<ILibraryPostScanTask> postscanTasks)
  175. {
  176. EntityResolutionIgnoreRules = rules.ToArray();
  177. PluginFolderCreators = pluginFolders.ToArray();
  178. EntityResolvers = resolvers.OrderBy(i => i.Priority).ToArray();
  179. IntroProviders = introProviders.ToArray();
  180. Comparers = itemComparers.ToArray();
  181. PostscanTasks = postscanTasks.OrderBy(i =>
  182. {
  183. var hasOrder = i as IHasOrder;
  184. return hasOrder == null ? 0 : hasOrder.Order;
  185. }).ToArray();
  186. }
  187. /// <summary>
  188. /// The _root folder
  189. /// </summary>
  190. private AggregateFolder _rootFolder;
  191. /// <summary>
  192. /// The _root folder sync lock
  193. /// </summary>
  194. private object _rootFolderSyncLock = new object();
  195. /// <summary>
  196. /// The _root folder initialized
  197. /// </summary>
  198. private bool _rootFolderInitialized;
  199. /// <summary>
  200. /// Gets the root folder.
  201. /// </summary>
  202. /// <value>The root folder.</value>
  203. public AggregateFolder RootFolder
  204. {
  205. get
  206. {
  207. LazyInitializer.EnsureInitialized(ref _rootFolder, ref _rootFolderInitialized, ref _rootFolderSyncLock, CreateRootFolder);
  208. return _rootFolder;
  209. }
  210. private set
  211. {
  212. _rootFolder = value;
  213. if (value == null)
  214. {
  215. _rootFolderInitialized = false;
  216. }
  217. }
  218. }
  219. /// <summary>
  220. /// The _items by name path
  221. /// </summary>
  222. private string _itemsByNamePath;
  223. /// <summary>
  224. /// The _season zero display name
  225. /// </summary>
  226. private string _seasonZeroDisplayName;
  227. private bool _wizardCompleted;
  228. /// <summary>
  229. /// Records the configuration values.
  230. /// </summary>
  231. /// <param name="configuration">The configuration.</param>
  232. private void RecordConfigurationValues(ServerConfiguration configuration)
  233. {
  234. _seasonZeroDisplayName = configuration.SeasonZeroDisplayName;
  235. _itemsByNamePath = ConfigurationManager.ApplicationPaths.ItemsByNamePath;
  236. _wizardCompleted = configuration.IsStartupWizardCompleted;
  237. }
  238. /// <summary>
  239. /// Configurations the updated.
  240. /// </summary>
  241. /// <param name="sender">The sender.</param>
  242. /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
  243. void ConfigurationUpdated(object sender, EventArgs e)
  244. {
  245. var config = ConfigurationManager.Configuration;
  246. var ibnPathChanged = !string.Equals(_itemsByNamePath, ConfigurationManager.ApplicationPaths.ItemsByNamePath, StringComparison.CurrentCulture);
  247. if (ibnPathChanged)
  248. {
  249. RemoveItemsByNameFromCache();
  250. }
  251. var newSeasonZeroName = ConfigurationManager.Configuration.SeasonZeroDisplayName;
  252. var seasonZeroNameChanged = !string.Equals(_seasonZeroDisplayName, newSeasonZeroName, StringComparison.CurrentCulture);
  253. var wizardChanged = config.IsStartupWizardCompleted != _wizardCompleted;
  254. RecordConfigurationValues(config);
  255. Task.Run(async () =>
  256. {
  257. if (seasonZeroNameChanged)
  258. {
  259. await UpdateSeasonZeroNames(newSeasonZeroName, CancellationToken.None).ConfigureAwait(false);
  260. }
  261. if (seasonZeroNameChanged || ibnPathChanged || wizardChanged)
  262. {
  263. _taskManager.CancelIfRunningAndQueue<RefreshMediaLibraryTask>();
  264. }
  265. });
  266. }
  267. private void RemoveItemsByNameFromCache()
  268. {
  269. RemoveItemsFromCache(i => i is Person);
  270. RemoveItemsFromCache(i => i is Year);
  271. RemoveItemsFromCache(i => i is Genre);
  272. RemoveItemsFromCache(i => i is MusicGenre);
  273. RemoveItemsFromCache(i => i is GameGenre);
  274. RemoveItemsFromCache(i => i is Studio);
  275. RemoveItemsFromCache(i =>
  276. {
  277. var artist = i as MusicArtist;
  278. return artist != null && artist.IsAccessedByName;
  279. });
  280. }
  281. private void RemoveItemsFromCache(Func<BaseItem, bool> remove)
  282. {
  283. var items = _libraryItemsCache.ToList().Where(i => remove(i.Value)).ToList();
  284. foreach (var item in items)
  285. {
  286. BaseItem value;
  287. _libraryItemsCache.TryRemove(item.Key, out value);
  288. }
  289. }
  290. /// <summary>
  291. /// Updates the season zero names.
  292. /// </summary>
  293. /// <param name="newName">The new name.</param>
  294. /// <param name="cancellationToken">The cancellation token.</param>
  295. /// <returns>Task.</returns>
  296. private async Task UpdateSeasonZeroNames(string newName, CancellationToken cancellationToken)
  297. {
  298. var seasons = RootFolder.RecursiveChildren
  299. .OfType<Season>()
  300. .Where(i => i.IndexNumber.HasValue && i.IndexNumber.Value == 0 && !string.Equals(i.Name, newName, StringComparison.CurrentCulture))
  301. .ToList();
  302. foreach (var season in seasons)
  303. {
  304. season.Name = newName;
  305. try
  306. {
  307. await UpdateItem(season, ItemUpdateType.MetadataDownload, cancellationToken).ConfigureAwait(false);
  308. }
  309. catch (Exception ex)
  310. {
  311. _logger.ErrorException("Error saving {0}", ex, season.Path);
  312. }
  313. }
  314. }
  315. /// <summary>
  316. /// Creates the library items cache.
  317. /// </summary>
  318. /// <returns>ConcurrentDictionary{GuidBaseItem}.</returns>
  319. private ConcurrentDictionary<Guid, BaseItem> CreateLibraryItemsCache()
  320. {
  321. var items = RootFolder.GetRecursiveChildren();
  322. items.Add(RootFolder);
  323. // Need to use Distinct because there could be multiple instances with the same id
  324. // due to sharing the default library
  325. var userRootFolders = _userManager.Users.Select(i => i.RootFolder)
  326. .Distinct()
  327. .ToList();
  328. foreach (var folder in userRootFolders)
  329. {
  330. items.Add(folder);
  331. }
  332. // Get all user collection folders
  333. // Skip BasePluginFolders because we already got them from RootFolder.RecursiveChildren
  334. var userFolders = userRootFolders.SelectMany(i => i.Children)
  335. .Where(i => !(i is BasePluginFolder))
  336. .ToList();
  337. foreach (var folder in userFolders)
  338. {
  339. items.Add(folder);
  340. }
  341. var dictionary = new ConcurrentDictionary<Guid, BaseItem>();
  342. foreach (var item in items)
  343. {
  344. dictionary[item.Id] = item;
  345. }
  346. return dictionary;
  347. }
  348. /// <summary>
  349. /// Updates the item in library cache.
  350. /// </summary>
  351. /// <param name="item">The item.</param>
  352. private void UpdateItemInLibraryCache(BaseItem item)
  353. {
  354. RegisterItem(item);
  355. }
  356. public void RegisterItem(BaseItem item)
  357. {
  358. RegisterItem(item.Id, item);
  359. }
  360. private void RegisterItem(Guid id, BaseItem item)
  361. {
  362. LibraryItemsCache.AddOrUpdate(id, item, delegate { return item; });
  363. }
  364. public async Task DeleteItem(BaseItem item, DeleteOptions options)
  365. {
  366. _logger.Debug("Deleting item, Type: {0}, Name: {1}, Path: {2}, Id: {3}",
  367. item.GetType().Name,
  368. item.Name,
  369. item.Path ?? string.Empty,
  370. item.Id);
  371. var parent = item.Parent;
  372. var locationType = item.LocationType;
  373. var children = item.IsFolder
  374. ? ((Folder)item).RecursiveChildren.ToList()
  375. : new List<BaseItem>();
  376. foreach (var metadataPath in GetMetadataPaths(item, children))
  377. {
  378. _logger.Debug("Deleting path {0}", metadataPath);
  379. try
  380. {
  381. Directory.Delete(metadataPath, true);
  382. }
  383. catch (DirectoryNotFoundException)
  384. {
  385. }
  386. catch (Exception ex)
  387. {
  388. _logger.ErrorException("Error deleting {0}", ex, metadataPath);
  389. }
  390. }
  391. if (options.DeleteFileLocation && locationType != LocationType.Remote && locationType != LocationType.Virtual)
  392. {
  393. foreach (var path in item.GetDeletePaths().ToList())
  394. {
  395. if (Directory.Exists(path))
  396. {
  397. _logger.Debug("Deleting path {0}", path);
  398. Directory.Delete(path, true);
  399. }
  400. else if (File.Exists(path))
  401. {
  402. _logger.Debug("Deleting path {0}", path);
  403. File.Delete(path);
  404. }
  405. }
  406. if (parent != null)
  407. {
  408. await parent.ValidateChildren(new Progress<double>(), CancellationToken.None)
  409. .ConfigureAwait(false);
  410. }
  411. }
  412. else if (parent != null)
  413. {
  414. await parent.RemoveChild(item, CancellationToken.None).ConfigureAwait(false);
  415. }
  416. await ItemRepository.DeleteItem(item.Id, CancellationToken.None).ConfigureAwait(false);
  417. foreach (var child in children)
  418. {
  419. await ItemRepository.DeleteItem(child.Id, CancellationToken.None).ConfigureAwait(false);
  420. }
  421. BaseItem removed;
  422. _libraryItemsCache.TryRemove(item.Id, out removed);
  423. ReportItemRemoved(item);
  424. }
  425. private IEnumerable<string> GetMetadataPaths(BaseItem item, IEnumerable<BaseItem> children)
  426. {
  427. var list = new List<string>
  428. {
  429. ConfigurationManager.ApplicationPaths.GetInternalMetadataPath(item.Id)
  430. };
  431. list.AddRange(children.Select(i => ConfigurationManager.ApplicationPaths.GetInternalMetadataPath(i.Id)));
  432. return list;
  433. }
  434. /// <summary>
  435. /// Resolves the item.
  436. /// </summary>
  437. /// <param name="args">The args.</param>
  438. /// <returns>BaseItem.</returns>
  439. public BaseItem ResolveItem(ItemResolveArgs args)
  440. {
  441. var item = EntityResolvers.Select(r =>
  442. {
  443. try
  444. {
  445. return r.ResolvePath(args);
  446. }
  447. catch (Exception ex)
  448. {
  449. _logger.ErrorException("Error in {0} resolving {1}", ex, r.GetType().Name, args.Path);
  450. return null;
  451. }
  452. }).FirstOrDefault(i => i != null);
  453. if (item != null)
  454. {
  455. ResolverHelper.SetInitialItemValues(item, args, _fileSystem);
  456. // Now handle the issue with posibly having the same item referenced from multiple physical
  457. // places within the library. Be sure we always end up with just one instance.
  458. if (item is IByReferenceItem)
  459. {
  460. item = GetOrAddByReferenceItem(item);
  461. }
  462. }
  463. return item;
  464. }
  465. /// <summary>
  466. /// Ensure supplied item has only one instance throughout
  467. /// </summary>
  468. /// <param name="item">The item.</param>
  469. /// <returns>The proper instance to the item</returns>
  470. public BaseItem GetOrAddByReferenceItem(BaseItem item)
  471. {
  472. // Add this item to our list if not there already
  473. if (!ByReferenceItems.TryAdd(item.Id, item))
  474. {
  475. // Already there - return the existing reference
  476. item = ByReferenceItems[item.Id];
  477. }
  478. return item;
  479. }
  480. public BaseItem ResolvePath(FileSystemInfo fileInfo, Folder parent = null)
  481. {
  482. return ResolvePath(fileInfo, new DirectoryService(_logger), parent);
  483. }
  484. /// <summary>
  485. /// Resolves a path into a BaseItem
  486. /// </summary>
  487. /// <param name="fileInfo">The file info.</param>
  488. /// <param name="directoryService">The directory service.</param>
  489. /// <param name="parent">The parent.</param>
  490. /// <returns>BaseItem.</returns>
  491. /// <exception cref="System.ArgumentNullException">fileInfo</exception>
  492. public BaseItem ResolvePath(FileSystemInfo fileInfo, IDirectoryService directoryService, Folder parent = null)
  493. {
  494. if (fileInfo == null)
  495. {
  496. throw new ArgumentNullException("fileInfo");
  497. }
  498. var args = new ItemResolveArgs(ConfigurationManager.ApplicationPaths, this, directoryService)
  499. {
  500. Parent = parent,
  501. Path = fileInfo.FullName,
  502. FileInfo = fileInfo
  503. };
  504. // Return null if ignore rules deem that we should do so
  505. if (EntityResolutionIgnoreRules.Any(r => r.ShouldIgnore(args)))
  506. {
  507. return null;
  508. }
  509. // Gather child folder and files
  510. if (args.IsDirectory)
  511. {
  512. var isPhysicalRoot = args.IsPhysicalRoot;
  513. // When resolving the root, we need it's grandchildren (children of user views)
  514. var flattenFolderDepth = isPhysicalRoot ? 2 : 0;
  515. var fileSystemDictionary = FileData.GetFilteredFileSystemEntries(directoryService, args.Path, _fileSystem, _logger, args, flattenFolderDepth: flattenFolderDepth, resolveShortcuts: isPhysicalRoot || args.IsVf);
  516. // Need to remove subpaths that may have been resolved from shortcuts
  517. // Example: if \\server\movies exists, then strip out \\server\movies\action
  518. if (isPhysicalRoot)
  519. {
  520. var paths = NormalizeRootPathList(fileSystemDictionary.Keys);
  521. fileSystemDictionary = paths.Select(i => (FileSystemInfo)new DirectoryInfo(i)).ToDictionary(i => i.FullName);
  522. }
  523. args.FileSystemDictionary = fileSystemDictionary;
  524. }
  525. // Check to see if we should resolve based on our contents
  526. if (args.IsDirectory && !ShouldResolvePathContents(args))
  527. {
  528. return null;
  529. }
  530. return ResolveItem(args);
  531. }
  532. public IEnumerable<string> NormalizeRootPathList(IEnumerable<string> paths)
  533. {
  534. var list = paths.Select(_fileSystem.NormalizePath)
  535. .Distinct(StringComparer.OrdinalIgnoreCase)
  536. .ToList();
  537. var dupes = list.Where(subPath => !subPath.EndsWith(":\\", StringComparison.OrdinalIgnoreCase) && list.Any(i => _fileSystem.ContainsSubPath(i, subPath)))
  538. .ToList();
  539. foreach (var dupe in dupes)
  540. {
  541. _logger.Info("Found duplicate path: {0}", dupe);
  542. }
  543. return list.Except(dupes, StringComparer.OrdinalIgnoreCase);
  544. }
  545. /// <summary>
  546. /// Determines whether a path should be ignored based on its contents - called after the contents have been read
  547. /// </summary>
  548. /// <param name="args">The args.</param>
  549. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  550. private static bool ShouldResolvePathContents(ItemResolveArgs args)
  551. {
  552. // Ignore any folders containing a file called .ignore
  553. return !args.ContainsFileSystemEntryByName(".ignore");
  554. }
  555. /// <summary>
  556. /// Resolves a set of files into a list of BaseItem
  557. /// </summary>
  558. /// <typeparam name="T"></typeparam>
  559. /// <param name="files">The files.</param>
  560. /// <param name="directoryService">The directory service.</param>
  561. /// <param name="parent">The parent.</param>
  562. /// <returns>List{``0}.</returns>
  563. public List<T> ResolvePaths<T>(IEnumerable<FileSystemInfo> files, IDirectoryService directoryService, Folder parent)
  564. where T : BaseItem
  565. {
  566. var list = new List<T>();
  567. Parallel.ForEach(files, f =>
  568. {
  569. try
  570. {
  571. var item = ResolvePath(f, directoryService, parent) as T;
  572. if (item != null)
  573. {
  574. lock (list)
  575. {
  576. list.Add(item);
  577. }
  578. }
  579. }
  580. catch (Exception ex)
  581. {
  582. _logger.ErrorException("Error resolving path {0}", ex, f.FullName);
  583. }
  584. });
  585. return list;
  586. }
  587. /// <summary>
  588. /// Creates the root media folder
  589. /// </summary>
  590. /// <returns>AggregateFolder.</returns>
  591. /// <exception cref="System.InvalidOperationException">Cannot create the root folder until plugins have loaded</exception>
  592. public AggregateFolder CreateRootFolder()
  593. {
  594. var rootFolderPath = ConfigurationManager.ApplicationPaths.RootFolderPath;
  595. Directory.CreateDirectory(rootFolderPath);
  596. var rootFolder = RetrieveItem(rootFolderPath.GetMBId(typeof(AggregateFolder))) as AggregateFolder ?? (AggregateFolder)ResolvePath(new DirectoryInfo(rootFolderPath));
  597. // Add in the plug-in folders
  598. foreach (var child in PluginFolderCreators)
  599. {
  600. var folder = child.GetFolder();
  601. if (folder.Id == Guid.Empty)
  602. {
  603. folder.Id = (folder.Path ?? folder.GetType().Name).GetMBId(folder.GetType());
  604. }
  605. rootFolder.AddVirtualChild(folder);
  606. }
  607. return rootFolder;
  608. }
  609. private UserRootFolder _userRootFolder;
  610. public Folder GetUserRootFolder()
  611. {
  612. if (_userRootFolder == null)
  613. {
  614. var userRootPath = ConfigurationManager.ApplicationPaths.DefaultUserViewsPath;
  615. Directory.CreateDirectory(userRootPath);
  616. _userRootFolder = RetrieveItem(userRootPath.GetMBId(typeof(UserRootFolder))) as UserRootFolder ??
  617. (UserRootFolder)ResolvePath(new DirectoryInfo(userRootPath));
  618. }
  619. return _userRootFolder;
  620. }
  621. /// <summary>
  622. /// Gets a Person
  623. /// </summary>
  624. /// <param name="name">The name.</param>
  625. /// <returns>Task{Person}.</returns>
  626. public Person GetPerson(string name)
  627. {
  628. return GetItemByName<Person>(ConfigurationManager.ApplicationPaths.PeoplePath, name);
  629. }
  630. /// <summary>
  631. /// Gets a Studio
  632. /// </summary>
  633. /// <param name="name">The name.</param>
  634. /// <returns>Task{Studio}.</returns>
  635. public Studio GetStudio(string name)
  636. {
  637. return GetItemByName<Studio>(ConfigurationManager.ApplicationPaths.StudioPath, name);
  638. }
  639. /// <summary>
  640. /// Gets a Genre
  641. /// </summary>
  642. /// <param name="name">The name.</param>
  643. /// <returns>Task{Genre}.</returns>
  644. public Genre GetGenre(string name)
  645. {
  646. return GetItemByName<Genre>(ConfigurationManager.ApplicationPaths.GenrePath, name);
  647. }
  648. /// <summary>
  649. /// Gets the genre.
  650. /// </summary>
  651. /// <param name="name">The name.</param>
  652. /// <returns>Task{MusicGenre}.</returns>
  653. public MusicGenre GetMusicGenre(string name)
  654. {
  655. return GetItemByName<MusicGenre>(ConfigurationManager.ApplicationPaths.MusicGenrePath, name);
  656. }
  657. /// <summary>
  658. /// Gets the game genre.
  659. /// </summary>
  660. /// <param name="name">The name.</param>
  661. /// <returns>Task{GameGenre}.</returns>
  662. public GameGenre GetGameGenre(string name)
  663. {
  664. return GetItemByName<GameGenre>(ConfigurationManager.ApplicationPaths.GameGenrePath, name);
  665. }
  666. /// <summary>
  667. /// The us culture
  668. /// </summary>
  669. private static readonly CultureInfo UsCulture = new CultureInfo("en-US");
  670. /// <summary>
  671. /// Gets a Year
  672. /// </summary>
  673. /// <param name="value">The value.</param>
  674. /// <returns>Task{Year}.</returns>
  675. /// <exception cref="System.ArgumentOutOfRangeException"></exception>
  676. public Year GetYear(int value)
  677. {
  678. if (value <= 0)
  679. {
  680. throw new ArgumentOutOfRangeException("Years less than or equal to 0 are invalid.");
  681. }
  682. return GetItemByName<Year>(ConfigurationManager.ApplicationPaths.YearPath, value.ToString(UsCulture));
  683. }
  684. /// <summary>
  685. /// Gets a Genre
  686. /// </summary>
  687. /// <param name="name">The name.</param>
  688. /// <returns>Task{Genre}.</returns>
  689. public MusicArtist GetArtist(string name)
  690. {
  691. return GetItemByName<MusicArtist>(ConfigurationManager.ApplicationPaths.ArtistsPath, name);
  692. }
  693. private T GetItemByName<T>(string path, string name)
  694. where T : BaseItem, new()
  695. {
  696. if (string.IsNullOrEmpty(path))
  697. {
  698. throw new ArgumentNullException("path");
  699. }
  700. if (string.IsNullOrEmpty(name))
  701. {
  702. throw new ArgumentNullException("name");
  703. }
  704. var validFilename = _fileSystem.GetValidFilename(name).Trim();
  705. string subFolderPrefix = null;
  706. var type = typeof(T);
  707. if (type == typeof(Person) && ConfigurationManager.Configuration.EnablePeoplePrefixSubFolders)
  708. {
  709. subFolderPrefix = validFilename.Substring(0, 1);
  710. }
  711. var fullPath = string.IsNullOrEmpty(subFolderPrefix) ?
  712. Path.Combine(path, validFilename) :
  713. Path.Combine(path, subFolderPrefix, validFilename);
  714. var id = fullPath.GetMBId(type);
  715. BaseItem obj;
  716. if (!_libraryItemsCache.TryGetValue(id, out obj))
  717. {
  718. obj = CreateItemByName<T>(fullPath, name, id);
  719. RegisterItem(id, obj);
  720. }
  721. return obj as T;
  722. }
  723. /// <summary>
  724. /// Creates an IBN item based on a given path
  725. /// </summary>
  726. /// <typeparam name="T"></typeparam>
  727. /// <param name="path">The path.</param>
  728. /// <param name="name">The name.</param>
  729. /// <returns>Task{``0}.</returns>
  730. /// <exception cref="System.IO.IOException">Path not created: + path</exception>
  731. private T CreateItemByName<T>(string path, string name, Guid id)
  732. where T : BaseItem, new()
  733. {
  734. var isArtist = typeof(T) == typeof(MusicArtist);
  735. if (isArtist)
  736. {
  737. var existing = RootFolder.RecursiveChildren
  738. .OfType<T>()
  739. .FirstOrDefault(i => string.Equals(i.Name, name, StringComparison.OrdinalIgnoreCase));
  740. if (existing != null)
  741. {
  742. return existing;
  743. }
  744. }
  745. var fileInfo = new DirectoryInfo(path);
  746. var isNew = false;
  747. if (!fileInfo.Exists)
  748. {
  749. Directory.CreateDirectory(path);
  750. fileInfo = new DirectoryInfo(path);
  751. if (!fileInfo.Exists)
  752. {
  753. throw new IOException("Path not created: " + path);
  754. }
  755. isNew = true;
  756. }
  757. var item = isNew ? null : RetrieveItem(id) as T;
  758. if (item == null)
  759. {
  760. item = new T
  761. {
  762. Name = name,
  763. Id = id,
  764. DateCreated = _fileSystem.GetCreationTimeUtc(fileInfo),
  765. DateModified = _fileSystem.GetLastWriteTimeUtc(fileInfo),
  766. Path = path
  767. };
  768. }
  769. if (isArtist)
  770. {
  771. (item as MusicArtist).IsAccessedByName = true;
  772. }
  773. return item;
  774. }
  775. /// <summary>
  776. /// Validate and refresh the People sub-set of the IBN.
  777. /// The items are stored in the db but not loaded into memory until actually requested by an operation.
  778. /// </summary>
  779. /// <param name="cancellationToken">The cancellation token.</param>
  780. /// <param name="progress">The progress.</param>
  781. /// <returns>Task.</returns>
  782. public Task ValidatePeople(CancellationToken cancellationToken, IProgress<double> progress)
  783. {
  784. // Ensure the location is available.
  785. Directory.CreateDirectory(ConfigurationManager.ApplicationPaths.PeoplePath);
  786. return new PeopleValidator(this, _logger).ValidatePeople(cancellationToken, new MetadataRefreshOptions(), progress);
  787. }
  788. /// <summary>
  789. /// Validates the artists.
  790. /// </summary>
  791. /// <param name="cancellationToken">The cancellation token.</param>
  792. /// <param name="progress">The progress.</param>
  793. /// <returns>Task.</returns>
  794. public Task ValidateArtists(CancellationToken cancellationToken, IProgress<double> progress)
  795. {
  796. // Ensure the location is unavailable.
  797. Directory.CreateDirectory(ConfigurationManager.ApplicationPaths.ArtistsPath);
  798. return new ArtistsValidator(this, _userManager, _logger).Run(progress, cancellationToken);
  799. }
  800. /// <summary>
  801. /// Validates the music genres.
  802. /// </summary>
  803. /// <param name="cancellationToken">The cancellation token.</param>
  804. /// <param name="progress">The progress.</param>
  805. /// <returns>Task.</returns>
  806. public Task ValidateMusicGenres(CancellationToken cancellationToken, IProgress<double> progress)
  807. {
  808. // Ensure the location is unavailable.
  809. Directory.CreateDirectory(ConfigurationManager.ApplicationPaths.MusicGenrePath);
  810. return new MusicGenresValidator(this, _logger).Run(progress, cancellationToken);
  811. }
  812. /// <summary>
  813. /// Validates the game genres.
  814. /// </summary>
  815. /// <param name="cancellationToken">The cancellation token.</param>
  816. /// <param name="progress">The progress.</param>
  817. /// <returns>Task.</returns>
  818. public Task ValidateGameGenres(CancellationToken cancellationToken, IProgress<double> progress)
  819. {
  820. // Ensure the location is unavailable.
  821. Directory.CreateDirectory(ConfigurationManager.ApplicationPaths.GameGenrePath);
  822. return new GameGenresValidator(this, _userManager, _logger).Run(progress, cancellationToken);
  823. }
  824. /// <summary>
  825. /// Validates the studios.
  826. /// </summary>
  827. /// <param name="cancellationToken">The cancellation token.</param>
  828. /// <param name="progress">The progress.</param>
  829. /// <returns>Task.</returns>
  830. public Task ValidateStudios(CancellationToken cancellationToken, IProgress<double> progress)
  831. {
  832. // Ensure the location is unavailable.
  833. Directory.CreateDirectory(ConfigurationManager.ApplicationPaths.StudioPath);
  834. return new StudiosValidator(this, _userManager, _logger).Run(progress, cancellationToken);
  835. }
  836. /// <summary>
  837. /// Validates the genres.
  838. /// </summary>
  839. /// <param name="cancellationToken">The cancellation token.</param>
  840. /// <param name="progress">The progress.</param>
  841. /// <returns>Task.</returns>
  842. public Task ValidateGenres(CancellationToken cancellationToken, IProgress<double> progress)
  843. {
  844. // Ensure the location is unavailable.
  845. Directory.CreateDirectory(ConfigurationManager.ApplicationPaths.GenrePath);
  846. return new GenresValidator(this, _userManager, _logger).Run(progress, cancellationToken);
  847. }
  848. /// <summary>
  849. /// Reloads the root media folder
  850. /// </summary>
  851. /// <param name="progress">The progress.</param>
  852. /// <param name="cancellationToken">The cancellation token.</param>
  853. /// <returns>Task.</returns>
  854. public Task ValidateMediaLibrary(IProgress<double> progress, CancellationToken cancellationToken)
  855. {
  856. // Just run the scheduled task so that the user can see it
  857. _taskManager.CancelIfRunningAndQueue<RefreshMediaLibraryTask>();
  858. return Task.FromResult(true);
  859. }
  860. /// <summary>
  861. /// Queues the library scan.
  862. /// </summary>
  863. public void QueueLibraryScan()
  864. {
  865. // Just run the scheduled task so that the user can see it
  866. _taskManager.QueueScheduledTask<RefreshMediaLibraryTask>();
  867. }
  868. /// <summary>
  869. /// Validates the media library internal.
  870. /// </summary>
  871. /// <param name="progress">The progress.</param>
  872. /// <param name="cancellationToken">The cancellation token.</param>
  873. /// <returns>Task.</returns>
  874. public async Task ValidateMediaLibraryInternal(IProgress<double> progress, CancellationToken cancellationToken)
  875. {
  876. _libraryMonitorFactory().Stop();
  877. try
  878. {
  879. await PerformLibraryValidation(progress, cancellationToken).ConfigureAwait(false);
  880. }
  881. finally
  882. {
  883. _libraryMonitorFactory().Start();
  884. }
  885. }
  886. private async Task PerformLibraryValidation(IProgress<double> progress, CancellationToken cancellationToken)
  887. {
  888. _logger.Info("Validating media library");
  889. await RootFolder.RefreshMetadata(cancellationToken).ConfigureAwait(false);
  890. progress.Report(.5);
  891. // Start by just validating the children of the root, but go no further
  892. await RootFolder.ValidateChildren(new Progress<double>(), cancellationToken, new MetadataRefreshOptions(), recursive: false);
  893. progress.Report(1);
  894. var userRoot = GetUserRootFolder();
  895. await userRoot.RefreshMetadata(cancellationToken).ConfigureAwait(false);
  896. await userRoot.ValidateChildren(new Progress<double>(), cancellationToken, new MetadataRefreshOptions(), recursive: false).ConfigureAwait(false);
  897. progress.Report(2);
  898. var innerProgress = new ActionableProgress<double>();
  899. innerProgress.RegisterAction(pct => progress.Report(2 + pct * .73));
  900. // Now validate the entire media library
  901. await RootFolder.ValidateChildren(innerProgress, cancellationToken, new MetadataRefreshOptions(), recursive: true).ConfigureAwait(false);
  902. progress.Report(75);
  903. innerProgress = new ActionableProgress<double>();
  904. innerProgress.RegisterAction(pct => progress.Report(75 + pct * .25));
  905. // Run post-scan tasks
  906. await RunPostScanTasks(innerProgress, cancellationToken).ConfigureAwait(false);
  907. progress.Report(100);
  908. // Bad practice, i know. But we keep a lot in memory, unfortunately.
  909. GC.Collect(2, GCCollectionMode.Forced, true);
  910. GC.Collect(2, GCCollectionMode.Forced, true);
  911. }
  912. /// <summary>
  913. /// Runs the post scan tasks.
  914. /// </summary>
  915. /// <param name="progress">The progress.</param>
  916. /// <param name="cancellationToken">The cancellation token.</param>
  917. /// <returns>Task.</returns>
  918. private async Task RunPostScanTasks(IProgress<double> progress, CancellationToken cancellationToken)
  919. {
  920. var tasks = PostscanTasks.ToList();
  921. var numComplete = 0;
  922. var numTasks = tasks.Count;
  923. foreach (var task in tasks)
  924. {
  925. var innerProgress = new ActionableProgress<double>();
  926. // Prevent access to modified closure
  927. var currentNumComplete = numComplete;
  928. innerProgress.RegisterAction(pct =>
  929. {
  930. double innerPercent = (currentNumComplete * 100) + pct;
  931. innerPercent /= numTasks;
  932. progress.Report(innerPercent);
  933. });
  934. try
  935. {
  936. await task.Run(innerProgress, cancellationToken);
  937. }
  938. catch (OperationCanceledException)
  939. {
  940. _logger.Info("Post-scan task cancelled: {0}", task.GetType().Name);
  941. }
  942. catch (Exception ex)
  943. {
  944. _logger.ErrorException("Error running postscan task", ex);
  945. }
  946. numComplete++;
  947. double percent = numComplete;
  948. percent /= numTasks;
  949. progress.Report(percent * 100);
  950. }
  951. progress.Report(100);
  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 GetDefaultVirtualFolders();
  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. }