LibraryManager.cs 53 KB

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