LibraryManager.cs 53 KB

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