LibraryManager.cs 52 KB

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