LibraryManager.cs 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515
  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. }
  941. /// <summary>
  942. /// Gets the default view.
  943. /// </summary>
  944. /// <returns>IEnumerable{VirtualFolderInfo}.</returns>
  945. public IEnumerable<VirtualFolderInfo> GetDefaultVirtualFolders()
  946. {
  947. return GetView(ConfigurationManager.ApplicationPaths.DefaultUserViewsPath);
  948. }
  949. /// <summary>
  950. /// Gets the view.
  951. /// </summary>
  952. /// <param name="user">The user.</param>
  953. /// <returns>IEnumerable{VirtualFolderInfo}.</returns>
  954. public IEnumerable<VirtualFolderInfo> GetVirtualFolders(User user)
  955. {
  956. return GetView(user.RootFolderPath);
  957. }
  958. /// <summary>
  959. /// Gets the view.
  960. /// </summary>
  961. /// <param name="path">The path.</param>
  962. /// <returns>IEnumerable{VirtualFolderInfo}.</returns>
  963. private IEnumerable<VirtualFolderInfo> GetView(string path)
  964. {
  965. return Directory.EnumerateDirectories(path, "*", SearchOption.TopDirectoryOnly)
  966. .Select(dir => new VirtualFolderInfo
  967. {
  968. Name = Path.GetFileName(dir),
  969. Locations = Directory.EnumerateFiles(dir, "*.mblink", SearchOption.TopDirectoryOnly)
  970. .Select(_fileSystem.ResolveShortcut)
  971. .OrderBy(i => i)
  972. .ToList(),
  973. CollectionType = GetCollectionType(dir)
  974. });
  975. }
  976. private string GetCollectionType(string path)
  977. {
  978. return new DirectoryInfo(path).EnumerateFiles("*.collection", SearchOption.TopDirectoryOnly)
  979. .Select(i => Path.GetFileNameWithoutExtension(i.FullName))
  980. .FirstOrDefault();
  981. }
  982. /// <summary>
  983. /// Gets the item by id.
  984. /// </summary>
  985. /// <param name="id">The id.</param>
  986. /// <returns>BaseItem.</returns>
  987. /// <exception cref="System.ArgumentNullException">id</exception>
  988. public BaseItem GetItemById(Guid id)
  989. {
  990. if (id == Guid.Empty)
  991. {
  992. throw new ArgumentNullException("id");
  993. }
  994. BaseItem item;
  995. if (LibraryItemsCache.TryGetValue(id, out item))
  996. {
  997. return item;
  998. }
  999. return RetrieveItem(id);
  1000. }
  1001. /// <summary>
  1002. /// Gets the intros.
  1003. /// </summary>
  1004. /// <param name="item">The item.</param>
  1005. /// <param name="user">The user.</param>
  1006. /// <returns>IEnumerable{System.String}.</returns>
  1007. public IEnumerable<Video> GetIntros(BaseItem item, User user)
  1008. {
  1009. return IntroProviders.SelectMany(i => i.GetIntros(item, user))
  1010. .Select(ResolveIntro)
  1011. .Where(i => i != null);
  1012. }
  1013. /// <summary>
  1014. /// Gets all intro files.
  1015. /// </summary>
  1016. /// <returns>IEnumerable{System.String}.</returns>
  1017. public IEnumerable<string> GetAllIntroFiles()
  1018. {
  1019. return IntroProviders.SelectMany(i => i.GetAllIntroFiles());
  1020. }
  1021. /// <summary>
  1022. /// Resolves the intro.
  1023. /// </summary>
  1024. /// <param name="info">The info.</param>
  1025. /// <returns>Video.</returns>
  1026. private Video ResolveIntro(IntroInfo info)
  1027. {
  1028. Video video = null;
  1029. if (info.ItemId.HasValue)
  1030. {
  1031. // Get an existing item by Id
  1032. video = GetItemById(info.ItemId.Value) as Video;
  1033. if (video == null)
  1034. {
  1035. _logger.Error("Unable to locate item with Id {0}.", info.ItemId.Value);
  1036. }
  1037. }
  1038. else if (!string.IsNullOrEmpty(info.Path))
  1039. {
  1040. try
  1041. {
  1042. // Try to resolve the path into a video
  1043. video = ResolvePath(_fileSystem.GetFileSystemInfo(info.Path)) as Video;
  1044. if (video == null)
  1045. {
  1046. _logger.Error("Intro resolver returned null for {0}.", info.Path);
  1047. }
  1048. else
  1049. {
  1050. // Pull the saved db item that will include metadata
  1051. var dbItem = GetItemById(video.Id) as Video;
  1052. if (dbItem != null)
  1053. {
  1054. video = dbItem;
  1055. }
  1056. }
  1057. }
  1058. catch (Exception ex)
  1059. {
  1060. _logger.ErrorException("Error resolving path {0}.", ex, info.Path);
  1061. }
  1062. }
  1063. else
  1064. {
  1065. _logger.Error("IntroProvider returned an IntroInfo with null Path and ItemId.");
  1066. }
  1067. return video;
  1068. }
  1069. /// <summary>
  1070. /// Sorts the specified sort by.
  1071. /// </summary>
  1072. /// <param name="items">The items.</param>
  1073. /// <param name="user">The user.</param>
  1074. /// <param name="sortBy">The sort by.</param>
  1075. /// <param name="sortOrder">The sort order.</param>
  1076. /// <returns>IEnumerable{BaseItem}.</returns>
  1077. public IEnumerable<BaseItem> Sort(IEnumerable<BaseItem> items, User user, IEnumerable<string> sortBy, SortOrder sortOrder)
  1078. {
  1079. var isFirst = true;
  1080. IOrderedEnumerable<BaseItem> orderedItems = null;
  1081. foreach (var orderBy in sortBy.Select(o => GetComparer(o, user)).Where(c => c != null))
  1082. {
  1083. if (isFirst)
  1084. {
  1085. orderedItems = sortOrder == SortOrder.Descending ? items.OrderByDescending(i => i, orderBy) : items.OrderBy(i => i, orderBy);
  1086. }
  1087. else
  1088. {
  1089. orderedItems = sortOrder == SortOrder.Descending ? orderedItems.ThenByDescending(i => i, orderBy) : orderedItems.ThenBy(i => i, orderBy);
  1090. }
  1091. isFirst = false;
  1092. }
  1093. return orderedItems ?? items;
  1094. }
  1095. /// <summary>
  1096. /// Gets the comparer.
  1097. /// </summary>
  1098. /// <param name="name">The name.</param>
  1099. /// <param name="user">The user.</param>
  1100. /// <returns>IBaseItemComparer.</returns>
  1101. private IBaseItemComparer GetComparer(string name, User user)
  1102. {
  1103. var comparer = Comparers.FirstOrDefault(c => string.Equals(name, c.Name, StringComparison.OrdinalIgnoreCase));
  1104. if (comparer != null)
  1105. {
  1106. // If it requires a user, create a new one, and assign the user
  1107. if (comparer is IUserBaseItemComparer)
  1108. {
  1109. var userComparer = (IUserBaseItemComparer)Activator.CreateInstance(comparer.GetType());
  1110. userComparer.User = user;
  1111. userComparer.UserManager = _userManager;
  1112. userComparer.UserDataRepository = _userDataRepository;
  1113. return userComparer;
  1114. }
  1115. }
  1116. return comparer;
  1117. }
  1118. /// <summary>
  1119. /// Creates the item.
  1120. /// </summary>
  1121. /// <param name="item">The item.</param>
  1122. /// <param name="cancellationToken">The cancellation token.</param>
  1123. /// <returns>Task.</returns>
  1124. public Task CreateItem(BaseItem item, CancellationToken cancellationToken)
  1125. {
  1126. return CreateItems(new[] { item }, cancellationToken);
  1127. }
  1128. /// <summary>
  1129. /// Creates the items.
  1130. /// </summary>
  1131. /// <param name="items">The items.</param>
  1132. /// <param name="cancellationToken">The cancellation token.</param>
  1133. /// <returns>Task.</returns>
  1134. public async Task CreateItems(IEnumerable<BaseItem> items, CancellationToken cancellationToken)
  1135. {
  1136. var list = items.ToList();
  1137. await ItemRepository.SaveItems(list, cancellationToken).ConfigureAwait(false);
  1138. foreach (var item in list)
  1139. {
  1140. UpdateItemInLibraryCache(item);
  1141. }
  1142. UpdateCollectionFolders();
  1143. if (ItemAdded != null)
  1144. {
  1145. foreach (var item in list)
  1146. {
  1147. try
  1148. {
  1149. ItemAdded(this, new ItemChangeEventArgs { Item = item });
  1150. }
  1151. catch (Exception ex)
  1152. {
  1153. _logger.ErrorException("Error in ItemAdded event handler", ex);
  1154. }
  1155. }
  1156. }
  1157. }
  1158. /// <summary>
  1159. /// Updates the item.
  1160. /// </summary>
  1161. /// <param name="item">The item.</param>
  1162. /// <param name="updateReason">The update reason.</param>
  1163. /// <param name="cancellationToken">The cancellation token.</param>
  1164. /// <returns>Task.</returns>
  1165. public async Task UpdateItem(BaseItem item, ItemUpdateType updateReason, CancellationToken cancellationToken)
  1166. {
  1167. if (item.LocationType == LocationType.FileSystem)
  1168. {
  1169. await _providerManagerFactory().SaveMetadata(item, updateReason).ConfigureAwait(false);
  1170. }
  1171. item.DateLastSaved = DateTime.UtcNow;
  1172. _logger.Debug("Saving {0} to database.", item.Path ?? item.Name);
  1173. await ItemRepository.SaveItem(item, cancellationToken).ConfigureAwait(false);
  1174. UpdateItemInLibraryCache(item);
  1175. if (ItemUpdated != null)
  1176. {
  1177. try
  1178. {
  1179. ItemUpdated(this, new ItemChangeEventArgs
  1180. {
  1181. Item = item,
  1182. UpdateReason = updateReason
  1183. });
  1184. }
  1185. catch (Exception ex)
  1186. {
  1187. _logger.ErrorException("Error in ItemUpdated event handler", ex);
  1188. }
  1189. }
  1190. }
  1191. /// <summary>
  1192. /// Reports the item removed.
  1193. /// </summary>
  1194. /// <param name="item">The item.</param>
  1195. public void ReportItemRemoved(BaseItem item)
  1196. {
  1197. UpdateCollectionFolders();
  1198. if (ItemRemoved != null)
  1199. {
  1200. try
  1201. {
  1202. ItemRemoved(this, new ItemChangeEventArgs { Item = item });
  1203. }
  1204. catch (Exception ex)
  1205. {
  1206. _logger.ErrorException("Error in ItemRemoved event handler", ex);
  1207. }
  1208. }
  1209. }
  1210. private void UpdateCollectionFolders()
  1211. {
  1212. foreach (var folder in _userManager.Users.SelectMany(i => i.RootFolder.Children).OfType<CollectionFolder>().ToList())
  1213. {
  1214. folder.ResetDynamicChildren();
  1215. }
  1216. }
  1217. /// <summary>
  1218. /// Retrieves the item.
  1219. /// </summary>
  1220. /// <param name="id">The id.</param>
  1221. /// <returns>BaseItem.</returns>
  1222. public BaseItem RetrieveItem(Guid id)
  1223. {
  1224. return ItemRepository.RetrieveItem(id);
  1225. }
  1226. /// <summary>
  1227. /// Finds the type of the collection.
  1228. /// </summary>
  1229. /// <param name="item">The item.</param>
  1230. /// <returns>System.String.</returns>
  1231. public string FindCollectionType(BaseItem item)
  1232. {
  1233. while (!(item.Parent is AggregateFolder) && item.Parent != null)
  1234. {
  1235. item = item.Parent;
  1236. }
  1237. if (item == null)
  1238. {
  1239. return null;
  1240. }
  1241. var collectionTypes = _userManager.Users
  1242. .Select(i => i.RootFolder)
  1243. .Distinct()
  1244. .SelectMany(i => i.Children)
  1245. .OfType<CollectionFolder>()
  1246. .Where(i =>
  1247. {
  1248. var locationType = i.LocationType;
  1249. if (locationType == LocationType.Remote || locationType == LocationType.Virtual)
  1250. {
  1251. return false;
  1252. }
  1253. if (string.Equals(i.Path, item.Path, StringComparison.OrdinalIgnoreCase))
  1254. {
  1255. return true;
  1256. }
  1257. return i.PhysicalLocations.Contains(item.Path);
  1258. })
  1259. .Select(i => i.CollectionType)
  1260. .Where(i => !string.IsNullOrEmpty(i))
  1261. .Distinct()
  1262. .ToList();
  1263. return collectionTypes.Count == 1 ? collectionTypes[0] : null;
  1264. }
  1265. public IEnumerable<string> GetAllArtists()
  1266. {
  1267. return GetAllArtists(RootFolder.RecursiveChildren);
  1268. }
  1269. public IEnumerable<string> GetAllArtists(IEnumerable<BaseItem> items)
  1270. {
  1271. return items
  1272. .OfType<Audio>()
  1273. .SelectMany(i =>
  1274. {
  1275. var list = new List<string>();
  1276. if (!string.IsNullOrEmpty(i.AlbumArtist))
  1277. {
  1278. list.Add(i.AlbumArtist);
  1279. }
  1280. list.AddRange(i.Artists);
  1281. return list;
  1282. })
  1283. .Distinct(StringComparer.OrdinalIgnoreCase);
  1284. }
  1285. }
  1286. }