LibraryManager.cs 55 KB

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