LibraryManager.cs 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419
  1. using MediaBrowser.Common.Extensions;
  2. using MediaBrowser.Common.Progress;
  3. using MediaBrowser.Common.ScheduledTasks;
  4. using MediaBrowser.Controller.Configuration;
  5. using MediaBrowser.Controller.Entities;
  6. using MediaBrowser.Controller.Entities.Audio;
  7. using MediaBrowser.Controller.Entities.TV;
  8. using MediaBrowser.Controller.IO;
  9. using MediaBrowser.Controller.Library;
  10. using MediaBrowser.Controller.Persistence;
  11. using MediaBrowser.Controller.Resolvers;
  12. using MediaBrowser.Controller.Sorting;
  13. using MediaBrowser.Model.Configuration;
  14. using MediaBrowser.Model.Entities;
  15. using MediaBrowser.Model.Logging;
  16. using MediaBrowser.Server.Implementations.ScheduledTasks;
  17. using MoreLinq;
  18. using System;
  19. using System.Collections.Concurrent;
  20. using System.Collections.Generic;
  21. using System.Globalization;
  22. using System.IO;
  23. using System.Linq;
  24. using System.Threading;
  25. using System.Threading.Tasks;
  26. using SortOrder = MediaBrowser.Model.Entities.SortOrder;
  27. namespace MediaBrowser.Server.Implementations.Library
  28. {
  29. /// <summary>
  30. /// Class LibraryManager
  31. /// </summary>
  32. public class LibraryManager : ILibraryManager
  33. {
  34. /// <summary>
  35. /// Gets or sets the postscan tasks.
  36. /// </summary>
  37. /// <value>The postscan tasks.</value>
  38. private IEnumerable<ILibraryPostScanTask> PostscanTasks { get; set; }
  39. /// <summary>
  40. /// Gets or sets the prescan tasks.
  41. /// </summary>
  42. /// <value>The prescan tasks.</value>
  43. private IEnumerable<ILibraryPrescanTask> PrescanTasks { get; set; }
  44. /// <summary>
  45. /// Gets the intro providers.
  46. /// </summary>
  47. /// <value>The intro providers.</value>
  48. private IEnumerable<IIntroProvider> IntroProviders { get; set; }
  49. /// <summary>
  50. /// Gets the list of entity resolution ignore rules
  51. /// </summary>
  52. /// <value>The entity resolution ignore rules.</value>
  53. private IEnumerable<IResolverIgnoreRule> EntityResolutionIgnoreRules { get; set; }
  54. /// <summary>
  55. /// Gets the list of BasePluginFolders added by plugins
  56. /// </summary>
  57. /// <value>The plugin folders.</value>
  58. private IEnumerable<IVirtualFolderCreator> PluginFolderCreators { get; set; }
  59. /// <summary>
  60. /// Gets the list of currently registered entity resolvers
  61. /// </summary>
  62. /// <value>The entity resolvers enumerable.</value>
  63. private IEnumerable<IItemResolver> EntityResolvers { get; set; }
  64. /// <summary>
  65. /// Gets or sets the comparers.
  66. /// </summary>
  67. /// <value>The comparers.</value>
  68. private IEnumerable<IBaseItemComparer> Comparers { get; set; }
  69. /// <summary>
  70. /// Gets or sets the savers.
  71. /// </summary>
  72. /// <value>The savers.</value>
  73. private IEnumerable<IMetadataSaver> Savers { get; set; }
  74. /// <summary>
  75. /// Gets the active item repository
  76. /// </summary>
  77. /// <value>The item repository.</value>
  78. public IItemRepository ItemRepository { get; set; }
  79. /// <summary>
  80. /// Occurs when [item added].
  81. /// </summary>
  82. public event EventHandler<ItemChangeEventArgs> ItemAdded;
  83. /// <summary>
  84. /// Occurs when [item updated].
  85. /// </summary>
  86. public event EventHandler<ItemChangeEventArgs> ItemUpdated;
  87. /// <summary>
  88. /// Occurs when [item removed].
  89. /// </summary>
  90. public event EventHandler<ItemChangeEventArgs> ItemRemoved;
  91. /// <summary>
  92. /// The _logger
  93. /// </summary>
  94. private readonly ILogger _logger;
  95. /// <summary>
  96. /// The _task manager
  97. /// </summary>
  98. private readonly ITaskManager _taskManager;
  99. /// <summary>
  100. /// The _user manager
  101. /// </summary>
  102. private readonly IUserManager _userManager;
  103. /// <summary>
  104. /// The _user data repository
  105. /// </summary>
  106. private readonly IUserDataRepository _userDataRepository;
  107. /// <summary>
  108. /// Gets or sets the configuration manager.
  109. /// </summary>
  110. /// <value>The configuration manager.</value>
  111. private IServerConfigurationManager ConfigurationManager { get; set; }
  112. /// <summary>
  113. /// A collection of items that may be referenced from multiple physical places in the library
  114. /// (typically, multiple user roots). We store them here and be sure they all reference a
  115. /// single instance.
  116. /// </summary>
  117. /// <value>The by reference items.</value>
  118. private ConcurrentDictionary<Guid, BaseItem> ByReferenceItems { get; set; }
  119. /// <summary>
  120. /// The _library items cache
  121. /// </summary>
  122. private ConcurrentDictionary<Guid, BaseItem> _libraryItemsCache;
  123. /// <summary>
  124. /// The _library items cache sync lock
  125. /// </summary>
  126. private object _libraryItemsCacheSyncLock = new object();
  127. /// <summary>
  128. /// The _library items cache initialized
  129. /// </summary>
  130. private bool _libraryItemsCacheInitialized;
  131. /// <summary>
  132. /// Gets the library items cache.
  133. /// </summary>
  134. /// <value>The library items cache.</value>
  135. private ConcurrentDictionary<Guid, BaseItem> LibraryItemsCache
  136. {
  137. get
  138. {
  139. LazyInitializer.EnsureInitialized(ref _libraryItemsCache, ref _libraryItemsCacheInitialized, ref _libraryItemsCacheSyncLock, CreateLibraryItemsCache);
  140. return _libraryItemsCache;
  141. }
  142. }
  143. /// <summary>
  144. /// The _user root folders
  145. /// </summary>
  146. private readonly ConcurrentDictionary<string, UserRootFolder> _userRootFolders =
  147. new ConcurrentDictionary<string, UserRootFolder>();
  148. /// <summary>
  149. /// Initializes a new instance of the <see cref="LibraryManager" /> class.
  150. /// </summary>
  151. /// <param name="logger">The logger.</param>
  152. /// <param name="taskManager">The task manager.</param>
  153. /// <param name="userManager">The user manager.</param>
  154. /// <param name="configurationManager">The configuration manager.</param>
  155. /// <param name="userDataRepository">The user data repository.</param>
  156. public LibraryManager(ILogger logger, ITaskManager taskManager, IUserManager userManager, IServerConfigurationManager configurationManager, IUserDataRepository userDataRepository)
  157. {
  158. _logger = logger;
  159. _taskManager = taskManager;
  160. _userManager = userManager;
  161. ConfigurationManager = configurationManager;
  162. _userDataRepository = userDataRepository;
  163. ByReferenceItems = new ConcurrentDictionary<Guid, BaseItem>();
  164. ConfigurationManager.ConfigurationUpdated += ConfigurationUpdated;
  165. RecordConfigurationValues(configurationManager.Configuration);
  166. }
  167. /// <summary>
  168. /// Adds the parts.
  169. /// </summary>
  170. /// <param name="rules">The rules.</param>
  171. /// <param name="pluginFolders">The plugin folders.</param>
  172. /// <param name="resolvers">The resolvers.</param>
  173. /// <param name="introProviders">The intro providers.</param>
  174. /// <param name="itemComparers">The item comparers.</param>
  175. /// <param name="prescanTasks">The prescan tasks.</param>
  176. /// <param name="postscanTasks">The postscan tasks.</param>
  177. /// <param name="savers">The savers.</param>
  178. public void AddParts(IEnumerable<IResolverIgnoreRule> rules,
  179. IEnumerable<IVirtualFolderCreator> pluginFolders,
  180. IEnumerable<IItemResolver> resolvers,
  181. IEnumerable<IIntroProvider> introProviders,
  182. IEnumerable<IBaseItemComparer> itemComparers,
  183. IEnumerable<ILibraryPrescanTask> prescanTasks,
  184. IEnumerable<ILibraryPostScanTask> postscanTasks,
  185. IEnumerable<IMetadataSaver> savers)
  186. {
  187. EntityResolutionIgnoreRules = rules;
  188. PluginFolderCreators = pluginFolders;
  189. EntityResolvers = resolvers.OrderBy(i => i.Priority).ToArray();
  190. IntroProviders = introProviders;
  191. Comparers = itemComparers;
  192. PrescanTasks = prescanTasks;
  193. PostscanTasks = postscanTasks;
  194. Savers = savers;
  195. }
  196. /// <summary>
  197. /// The _root folder
  198. /// </summary>
  199. private AggregateFolder _rootFolder;
  200. /// <summary>
  201. /// The _root folder sync lock
  202. /// </summary>
  203. private object _rootFolderSyncLock = new object();
  204. /// <summary>
  205. /// The _root folder initialized
  206. /// </summary>
  207. private bool _rootFolderInitialized;
  208. /// <summary>
  209. /// Gets the root folder.
  210. /// </summary>
  211. /// <value>The root folder.</value>
  212. public AggregateFolder RootFolder
  213. {
  214. get
  215. {
  216. LazyInitializer.EnsureInitialized(ref _rootFolder, ref _rootFolderInitialized, ref _rootFolderSyncLock, CreateRootFolder);
  217. return _rootFolder;
  218. }
  219. private set
  220. {
  221. _rootFolder = value;
  222. if (value == null)
  223. {
  224. _rootFolderInitialized = false;
  225. }
  226. }
  227. }
  228. /// <summary>
  229. /// The _internet providers enabled
  230. /// </summary>
  231. private bool _internetProvidersEnabled;
  232. /// <summary>
  233. /// The _people image fetching enabled
  234. /// </summary>
  235. private bool _peopleImageFetchingEnabled;
  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. /// <summary>
  245. /// Records the configuration values.
  246. /// </summary>
  247. /// <param name="configuration">The configuration.</param>
  248. private void RecordConfigurationValues(ServerConfiguration configuration)
  249. {
  250. _seasonZeroDisplayName = ConfigurationManager.Configuration.SeasonZeroDisplayName;
  251. _itemsByNamePath = ConfigurationManager.ApplicationPaths.ItemsByNamePath;
  252. _internetProvidersEnabled = configuration.EnableInternetProviders;
  253. _peopleImageFetchingEnabled = configuration.InternetProviderExcludeTypes == null || !configuration.InternetProviderExcludeTypes.Contains(typeof(Person).Name, StringComparer.OrdinalIgnoreCase);
  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. // Figure out whether or not we should refresh people after the update is finished
  264. var refreshPeopleAfterUpdate = !_internetProvidersEnabled && config.EnableInternetProviders;
  265. // This is true if internet providers has just been turned on, or if People have just been removed from InternetProviderExcludeTypes
  266. if (!refreshPeopleAfterUpdate)
  267. {
  268. var newConfigurationFetchesPeopleImages = config.InternetProviderExcludeTypes == null || !config.InternetProviderExcludeTypes.Contains(typeof(Person).Name, StringComparer.OrdinalIgnoreCase);
  269. refreshPeopleAfterUpdate = newConfigurationFetchesPeopleImages && !_peopleImageFetchingEnabled;
  270. }
  271. var ibnPathChanged = !string.Equals(_itemsByNamePath, ConfigurationManager.ApplicationPaths.ItemsByNamePath, StringComparison.CurrentCulture);
  272. if (ibnPathChanged)
  273. {
  274. _itemsByName.Clear();
  275. }
  276. var newSeasonZeroName = ConfigurationManager.Configuration.SeasonZeroDisplayName;
  277. var seasonZeroNameChanged = !string.Equals(_seasonZeroDisplayName, newSeasonZeroName, StringComparison.CurrentCulture);
  278. RecordConfigurationValues(config);
  279. Task.Run(async () =>
  280. {
  281. if (seasonZeroNameChanged)
  282. {
  283. await UpdateSeasonZeroNames(newSeasonZeroName, CancellationToken.None).ConfigureAwait(false);
  284. }
  285. // Any number of configuration settings could change the way the library is refreshed, so do that now
  286. _taskManager.CancelIfRunningAndQueue<RefreshMediaLibraryTask>();
  287. if (refreshPeopleAfterUpdate)
  288. {
  289. _taskManager.CancelIfRunningAndQueue<PeopleValidationTask>();
  290. }
  291. });
  292. }
  293. /// <summary>
  294. /// Updates the season zero names.
  295. /// </summary>
  296. /// <param name="newName">The new name.</param>
  297. /// <param name="cancellationToken">The cancellation token.</param>
  298. /// <returns>Task.</returns>
  299. private Task UpdateSeasonZeroNames(string newName, CancellationToken cancellationToken)
  300. {
  301. var seasons = RootFolder.RecursiveChildren
  302. .OfType<Season>()
  303. .Where(i => i.IndexNumber.HasValue && i.IndexNumber.Value == 0 && !string.Equals(i.Name, newName, StringComparison.CurrentCulture))
  304. .ToList();
  305. foreach (var season in seasons)
  306. {
  307. season.Name = newName;
  308. }
  309. return UpdateItems(seasons, cancellationToken);
  310. }
  311. /// <summary>
  312. /// Creates the library items cache.
  313. /// </summary>
  314. /// <returns>ConcurrentDictionary{GuidBaseItem}.</returns>
  315. private ConcurrentDictionary<Guid, BaseItem> CreateLibraryItemsCache()
  316. {
  317. var items = RootFolder.RecursiveChildren.ToList();
  318. items.Add(RootFolder);
  319. // Need to use DistinctBy Id because there could be multiple instances with the same id
  320. // due to sharing the default library
  321. var userRootFolders = _userManager.Users.Select(i => i.RootFolder)
  322. .Distinct()
  323. .ToList();
  324. items.AddRange(userRootFolders);
  325. // Get all user collection folders
  326. // Skip BasePluginFolders because we already got them from RootFolder.RecursiveChildren
  327. var userFolders =
  328. userRootFolders.SelectMany(i => i.Children)
  329. .Where(i => !(i is BasePluginFolder))
  330. .ToList();
  331. items.AddRange(userFolders);
  332. return new ConcurrentDictionary<Guid, BaseItem>(items.ToDictionary(i => i.Id));
  333. }
  334. /// <summary>
  335. /// Updates the item in library cache.
  336. /// </summary>
  337. /// <param name="item">The item.</param>
  338. private void UpdateItemInLibraryCache(BaseItem item)
  339. {
  340. LibraryItemsCache.AddOrUpdate(item.Id, item, delegate { return item; });
  341. }
  342. /// <summary>
  343. /// Resolves the item.
  344. /// </summary>
  345. /// <param name="args">The args.</param>
  346. /// <returns>BaseItem.</returns>
  347. public BaseItem ResolveItem(ItemResolveArgs args)
  348. {
  349. var item = EntityResolvers.Select(r =>
  350. {
  351. try
  352. {
  353. return r.ResolvePath(args);
  354. }
  355. catch (Exception ex)
  356. {
  357. _logger.ErrorException("Error in {0} resolving {1}", ex, r.GetType().Name, args.Path);
  358. return null;
  359. }
  360. }).FirstOrDefault(i => i != null);
  361. if (item != null)
  362. {
  363. ResolverHelper.SetInitialItemValues(item, args);
  364. // Now handle the issue with posibly having the same item referenced from multiple physical
  365. // places within the library. Be sure we always end up with just one instance.
  366. if (item is IByReferenceItem)
  367. {
  368. item = GetOrAddByReferenceItem(item);
  369. }
  370. }
  371. return item;
  372. }
  373. /// <summary>
  374. /// Ensure supplied item has only one instance throughout
  375. /// </summary>
  376. /// <param name="item">The item.</param>
  377. /// <returns>The proper instance to the item</returns>
  378. public BaseItem GetOrAddByReferenceItem(BaseItem item)
  379. {
  380. // Add this item to our list if not there already
  381. if (!ByReferenceItems.TryAdd(item.Id, item))
  382. {
  383. // Already there - return the existing reference
  384. item = ByReferenceItems[item.Id];
  385. }
  386. return item;
  387. }
  388. /// <summary>
  389. /// Resolves a path into a BaseItem
  390. /// </summary>
  391. /// <param name="fileInfo">The file info.</param>
  392. /// <param name="parent">The parent.</param>
  393. /// <returns>BaseItem.</returns>
  394. /// <exception cref="System.ArgumentNullException"></exception>
  395. public BaseItem ResolvePath(FileSystemInfo fileInfo, Folder parent = null)
  396. {
  397. if (fileInfo == null)
  398. {
  399. throw new ArgumentNullException("fileInfo");
  400. }
  401. var args = new ItemResolveArgs(ConfigurationManager.ApplicationPaths)
  402. {
  403. Parent = parent,
  404. Path = fileInfo.FullName,
  405. FileInfo = fileInfo
  406. };
  407. // Return null if ignore rules deem that we should do so
  408. if (EntityResolutionIgnoreRules.Any(r => r.ShouldIgnore(args)))
  409. {
  410. return null;
  411. }
  412. // Gather child folder and files
  413. if (args.IsDirectory)
  414. {
  415. var isPhysicalRoot = args.IsPhysicalRoot;
  416. // When resolving the root, we need it's grandchildren (children of user views)
  417. var flattenFolderDepth = isPhysicalRoot ? 2 : 0;
  418. args.FileSystemDictionary = FileData.GetFilteredFileSystemEntries(args.Path, _logger, flattenFolderDepth: flattenFolderDepth, args: args, resolveShortcuts: isPhysicalRoot || args.IsVf);
  419. // Need to remove subpaths that may have been resolved from shortcuts
  420. // Example: if \\server\movies exists, then strip out \\server\movies\action
  421. if (isPhysicalRoot)
  422. {
  423. var paths = args.FileSystemDictionary.Keys.ToList();
  424. foreach (var subPath in paths
  425. .Where(subPath => !subPath.EndsWith(":\\", StringComparison.OrdinalIgnoreCase) && paths.Any(i => subPath.StartsWith(i.TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase))))
  426. {
  427. _logger.Info("Ignoring duplicate path: {0}", subPath);
  428. args.FileSystemDictionary.Remove(subPath);
  429. }
  430. }
  431. }
  432. // Check to see if we should resolve based on our contents
  433. if (args.IsDirectory && !ShouldResolvePathContents(args))
  434. {
  435. return null;
  436. }
  437. return ResolveItem(args);
  438. }
  439. /// <summary>
  440. /// Determines whether a path should be ignored based on its contents - called after the contents have been read
  441. /// </summary>
  442. /// <param name="args">The args.</param>
  443. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  444. private static bool ShouldResolvePathContents(ItemResolveArgs args)
  445. {
  446. // Ignore any folders containing a file called .ignore
  447. return !args.ContainsFileSystemEntryByName(".ignore");
  448. }
  449. /// <summary>
  450. /// Resolves a set of files into a list of BaseItem
  451. /// </summary>
  452. /// <typeparam name="T"></typeparam>
  453. /// <param name="files">The files.</param>
  454. /// <param name="parent">The parent.</param>
  455. /// <returns>List{``0}.</returns>
  456. public List<T> ResolvePaths<T>(IEnumerable<FileSystemInfo> files, Folder parent)
  457. where T : BaseItem
  458. {
  459. var list = new List<T>();
  460. Parallel.ForEach(files, f =>
  461. {
  462. try
  463. {
  464. var item = ResolvePath(f, parent) as T;
  465. if (item != null)
  466. {
  467. lock (list)
  468. {
  469. list.Add(item);
  470. }
  471. }
  472. }
  473. catch (Exception ex)
  474. {
  475. _logger.ErrorException("Error resolving path {0}", ex, f.FullName);
  476. }
  477. });
  478. return list;
  479. }
  480. /// <summary>
  481. /// Creates the root media folder
  482. /// </summary>
  483. /// <returns>AggregateFolder.</returns>
  484. /// <exception cref="System.InvalidOperationException">Cannot create the root folder until plugins have loaded</exception>
  485. public AggregateFolder CreateRootFolder()
  486. {
  487. var rootFolderPath = ConfigurationManager.ApplicationPaths.RootFolderPath;
  488. if (!Directory.Exists(rootFolderPath))
  489. {
  490. Directory.CreateDirectory(rootFolderPath);
  491. }
  492. var rootFolder = RetrieveItem(rootFolderPath.GetMBId(typeof(AggregateFolder))) as AggregateFolder ?? (AggregateFolder)ResolvePath(new DirectoryInfo(rootFolderPath));
  493. // Add in the plug-in folders
  494. foreach (var child in PluginFolderCreators)
  495. {
  496. var folder = child.GetFolder();
  497. if (string.IsNullOrEmpty(folder.DisplayMediaType))
  498. {
  499. folder.DisplayMediaType = "CollectionFolder";
  500. }
  501. if (folder.Id == Guid.Empty)
  502. {
  503. folder.Id = (folder.Path ?? folder.Name ?? folder.GetType().Name).GetMBId(folder.GetType());
  504. }
  505. rootFolder.AddVirtualChild(folder);
  506. }
  507. return rootFolder;
  508. }
  509. /// <summary>
  510. /// Gets the user root folder.
  511. /// </summary>
  512. /// <param name="userRootPath">The user root path.</param>
  513. /// <returns>UserRootFolder.</returns>
  514. public UserRootFolder GetUserRootFolder(string userRootPath)
  515. {
  516. return _userRootFolders.GetOrAdd(userRootPath, key => RetrieveItem(userRootPath.GetMBId(typeof(UserRootFolder))) as UserRootFolder ?? (UserRootFolder)ResolvePath(new DirectoryInfo(userRootPath)));
  517. }
  518. /// <summary>
  519. /// Gets a Person
  520. /// </summary>
  521. /// <param name="name">The name.</param>
  522. /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param>
  523. /// <returns>Task{Person}.</returns>
  524. public Task<Person> GetPerson(string name, bool allowSlowProviders = false)
  525. {
  526. return GetPerson(name, CancellationToken.None, allowSlowProviders);
  527. }
  528. /// <summary>
  529. /// Gets a Person
  530. /// </summary>
  531. /// <param name="name">The name.</param>
  532. /// <param name="cancellationToken">The cancellation token.</param>
  533. /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param>
  534. /// <param name="forceCreation">if set to <c>true</c> [force creation].</param>
  535. /// <returns>Task{Person}.</returns>
  536. private Task<Person> GetPerson(string name, CancellationToken cancellationToken, bool allowSlowProviders = false, bool forceCreation = false)
  537. {
  538. return GetItemByName<Person>(ConfigurationManager.ApplicationPaths.PeoplePath, name, cancellationToken, allowSlowProviders, forceCreation);
  539. }
  540. /// <summary>
  541. /// Gets a Studio
  542. /// </summary>
  543. /// <param name="name">The name.</param>
  544. /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param>
  545. /// <returns>Task{Studio}.</returns>
  546. public Task<Studio> GetStudio(string name, bool allowSlowProviders = false)
  547. {
  548. return GetItemByName<Studio>(ConfigurationManager.ApplicationPaths.StudioPath, name, CancellationToken.None, allowSlowProviders);
  549. }
  550. /// <summary>
  551. /// Gets a Genre
  552. /// </summary>
  553. /// <param name="name">The name.</param>
  554. /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param>
  555. /// <returns>Task{Genre}.</returns>
  556. public Task<Genre> GetGenre(string name, bool allowSlowProviders = false)
  557. {
  558. return GetItemByName<Genre>(ConfigurationManager.ApplicationPaths.GenrePath, name, CancellationToken.None, allowSlowProviders);
  559. }
  560. /// <summary>
  561. /// Gets the genre.
  562. /// </summary>
  563. /// <param name="name">The name.</param>
  564. /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param>
  565. /// <returns>Task{MusicGenre}.</returns>
  566. public Task<MusicGenre> GetMusicGenre(string name, bool allowSlowProviders = false)
  567. {
  568. return GetItemByName<MusicGenre>(ConfigurationManager.ApplicationPaths.MusicGenrePath, name, CancellationToken.None, allowSlowProviders);
  569. }
  570. /// <summary>
  571. /// Gets a Genre
  572. /// </summary>
  573. /// <param name="name">The name.</param>
  574. /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param>
  575. /// <returns>Task{Genre}.</returns>
  576. public Task<Artist> GetArtist(string name, bool allowSlowProviders = false)
  577. {
  578. return GetArtist(name, CancellationToken.None, allowSlowProviders);
  579. }
  580. /// <summary>
  581. /// Gets the artist.
  582. /// </summary>
  583. /// <param name="name">The name.</param>
  584. /// <param name="cancellationToken">The cancellation token.</param>
  585. /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param>
  586. /// <param name="forceCreation">if set to <c>true</c> [force creation].</param>
  587. /// <returns>Task{Artist}.</returns>
  588. private Task<Artist> GetArtist(string name, CancellationToken cancellationToken, bool allowSlowProviders = false, bool forceCreation = false)
  589. {
  590. return GetItemByName<Artist>(ConfigurationManager.ApplicationPaths.ArtistsPath, name, cancellationToken, allowSlowProviders, forceCreation);
  591. }
  592. /// <summary>
  593. /// The us culture
  594. /// </summary>
  595. private static readonly CultureInfo UsCulture = new CultureInfo("en-US");
  596. /// <summary>
  597. /// Gets a Year
  598. /// </summary>
  599. /// <param name="value">The value.</param>
  600. /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param>
  601. /// <returns>Task{Year}.</returns>
  602. /// <exception cref="System.ArgumentOutOfRangeException"></exception>
  603. public Task<Year> GetYear(int value, bool allowSlowProviders = false)
  604. {
  605. if (value <= 0)
  606. {
  607. throw new ArgumentOutOfRangeException();
  608. }
  609. return GetItemByName<Year>(ConfigurationManager.ApplicationPaths.YearPath, value.ToString(UsCulture), CancellationToken.None, allowSlowProviders);
  610. }
  611. /// <summary>
  612. /// The images by name item cache
  613. /// </summary>
  614. private readonly ConcurrentDictionary<string, BaseItem> _itemsByName = new ConcurrentDictionary<string, BaseItem>(StringComparer.OrdinalIgnoreCase);
  615. /// <summary>
  616. /// Generically retrieves an IBN item
  617. /// </summary>
  618. /// <typeparam name="T"></typeparam>
  619. /// <param name="path">The path.</param>
  620. /// <param name="name">The name.</param>
  621. /// <param name="cancellationToken">The cancellation token.</param>
  622. /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param>
  623. /// <param name="forceCreation">if set to <c>true</c> [force creation].</param>
  624. /// <returns>Task{``0}.</returns>
  625. /// <exception cref="System.ArgumentNullException">
  626. /// </exception>
  627. private async Task<T> GetItemByName<T>(string path, string name, CancellationToken cancellationToken, bool allowSlowProviders = true, bool forceCreation = false)
  628. where T : BaseItem, new()
  629. {
  630. if (string.IsNullOrEmpty(path))
  631. {
  632. throw new ArgumentNullException();
  633. }
  634. if (string.IsNullOrEmpty(name))
  635. {
  636. throw new ArgumentNullException();
  637. }
  638. var key = Path.Combine(path, FileSystem.GetValidFilename(name));
  639. BaseItem obj;
  640. if (!_itemsByName.TryGetValue(key, out obj))
  641. {
  642. obj = await CreateItemByName<T>(path, name, cancellationToken, allowSlowProviders).ConfigureAwait(false);
  643. _itemsByName.AddOrUpdate(key, obj, (keyName, oldValue) => obj);
  644. }
  645. else if (forceCreation)
  646. {
  647. await obj.RefreshMetadata(cancellationToken, false, allowSlowProviders: allowSlowProviders).ConfigureAwait(false);
  648. }
  649. return obj as T;
  650. }
  651. /// <summary>
  652. /// Creates an IBN item based on a given path
  653. /// </summary>
  654. /// <typeparam name="T"></typeparam>
  655. /// <param name="path">The path.</param>
  656. /// <param name="name">The name.</param>
  657. /// <param name="cancellationToken">The cancellation token.</param>
  658. /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param>
  659. /// <returns>Task{``0}.</returns>
  660. /// <exception cref="System.IO.IOException">Path not created: + path</exception>
  661. private async Task<T> CreateItemByName<T>(string path, string name, CancellationToken cancellationToken, bool allowSlowProviders = true)
  662. where T : BaseItem, new()
  663. {
  664. cancellationToken.ThrowIfCancellationRequested();
  665. path = Path.Combine(path, FileSystem.GetValidFilename(name));
  666. var fileInfo = new DirectoryInfo(path);
  667. var isNew = false;
  668. if (!fileInfo.Exists)
  669. {
  670. Directory.CreateDirectory(path);
  671. fileInfo = new DirectoryInfo(path);
  672. if (!fileInfo.Exists)
  673. {
  674. throw new IOException("Path not created: " + path);
  675. }
  676. isNew = true;
  677. }
  678. cancellationToken.ThrowIfCancellationRequested();
  679. var id = path.GetMBId(typeof(T));
  680. var item = RetrieveItem(id) as T;
  681. if (item == null)
  682. {
  683. item = new T
  684. {
  685. Name = name,
  686. Id = id,
  687. DateCreated = fileInfo.CreationTimeUtc,
  688. DateModified = fileInfo.LastWriteTimeUtc,
  689. Path = path
  690. };
  691. isNew = true;
  692. }
  693. cancellationToken.ThrowIfCancellationRequested();
  694. // Set this now so we don't cause additional file system access during provider executions
  695. item.ResetResolveArgs(fileInfo);
  696. await item.RefreshMetadata(cancellationToken, isNew, allowSlowProviders: allowSlowProviders).ConfigureAwait(false);
  697. cancellationToken.ThrowIfCancellationRequested();
  698. return item;
  699. }
  700. /// <summary>
  701. /// Validate and refresh the People sub-set of the IBN.
  702. /// The items are stored in the db but not loaded into memory until actually requested by an operation.
  703. /// </summary>
  704. /// <param name="cancellationToken">The cancellation token.</param>
  705. /// <param name="progress">The progress.</param>
  706. /// <returns>Task.</returns>
  707. public async Task ValidatePeople(CancellationToken cancellationToken, IProgress<double> progress)
  708. {
  709. const int maxTasks = 10;
  710. var tasks = new List<Task>();
  711. var includedPersonTypes = new[] { PersonType.Actor, PersonType.Director, PersonType.GuestStar, PersonType.Writer, PersonType.Director, PersonType.Producer };
  712. var people = RootFolder.RecursiveChildren
  713. .Where(c => c.People != null)
  714. .SelectMany(c => c.People.Where(p => includedPersonTypes.Contains(p.Type)))
  715. .DistinctBy(p => p.Name, StringComparer.OrdinalIgnoreCase)
  716. .ToList();
  717. var numComplete = 0;
  718. foreach (var person in people)
  719. {
  720. if (tasks.Count > maxTasks)
  721. {
  722. await Task.WhenAll(tasks).ConfigureAwait(false);
  723. tasks.Clear();
  724. // Safe cancellation point, when there are no pending tasks
  725. cancellationToken.ThrowIfCancellationRequested();
  726. }
  727. // Avoid accessing the foreach variable within the closure
  728. var currentPerson = person;
  729. tasks.Add(Task.Run(async () =>
  730. {
  731. cancellationToken.ThrowIfCancellationRequested();
  732. try
  733. {
  734. await GetPerson(currentPerson.Name, cancellationToken, true, true).ConfigureAwait(false);
  735. }
  736. catch (IOException ex)
  737. {
  738. _logger.ErrorException("Error validating IBN entry {0}", ex, currentPerson.Name);
  739. }
  740. // Update progress
  741. lock (progress)
  742. {
  743. numComplete++;
  744. double percent = numComplete;
  745. percent /= people.Count;
  746. progress.Report(100 * percent);
  747. }
  748. }));
  749. }
  750. await Task.WhenAll(tasks).ConfigureAwait(false);
  751. progress.Report(100);
  752. _logger.Info("People validation complete");
  753. }
  754. /// <summary>
  755. /// Validates the artists.
  756. /// </summary>
  757. /// <param name="cancellationToken">The cancellation token.</param>
  758. /// <param name="progress">The progress.</param>
  759. /// <returns>Task.</returns>
  760. public async Task ValidateArtists(CancellationToken cancellationToken, IProgress<double> progress)
  761. {
  762. const int maxTasks = 25;
  763. var tasks = new List<Task>();
  764. var artists = RootFolder.RecursiveChildren
  765. .OfType<Audio>()
  766. .SelectMany(c =>
  767. {
  768. var list = new List<string>();
  769. if (!string.IsNullOrEmpty(c.AlbumArtist))
  770. {
  771. list.Add(c.AlbumArtist);
  772. }
  773. if (!string.IsNullOrEmpty(c.Artist))
  774. {
  775. list.Add(c.Artist);
  776. }
  777. return list;
  778. })
  779. .Distinct(StringComparer.OrdinalIgnoreCase)
  780. .ToList();
  781. var numComplete = 0;
  782. foreach (var artist in artists)
  783. {
  784. if (tasks.Count > maxTasks)
  785. {
  786. await Task.WhenAll(tasks).ConfigureAwait(false);
  787. tasks.Clear();
  788. // Safe cancellation point, when there are no pending tasks
  789. cancellationToken.ThrowIfCancellationRequested();
  790. }
  791. // Avoid accessing the foreach variable within the closure
  792. var currentArtist = artist;
  793. tasks.Add(Task.Run(async () =>
  794. {
  795. cancellationToken.ThrowIfCancellationRequested();
  796. try
  797. {
  798. await GetArtist(currentArtist, cancellationToken, true, true).ConfigureAwait(false);
  799. }
  800. catch (IOException ex)
  801. {
  802. _logger.ErrorException("Error validating Artist {0}", ex, currentArtist);
  803. }
  804. // Update progress
  805. lock (progress)
  806. {
  807. numComplete++;
  808. double percent = numComplete;
  809. percent /= artists.Count;
  810. progress.Report(100 * percent);
  811. }
  812. }));
  813. }
  814. await Task.WhenAll(tasks).ConfigureAwait(false);
  815. progress.Report(100);
  816. _logger.Info("Artist validation complete");
  817. }
  818. /// <summary>
  819. /// Reloads the root media folder
  820. /// </summary>
  821. /// <param name="progress">The progress.</param>
  822. /// <param name="cancellationToken">The cancellation token.</param>
  823. /// <returns>Task.</returns>
  824. public Task ValidateMediaLibrary(IProgress<double> progress, CancellationToken cancellationToken)
  825. {
  826. // Just run the scheduled task so that the user can see it
  827. return Task.Run(() => _taskManager.CancelIfRunningAndQueue<RefreshMediaLibraryTask>());
  828. }
  829. /// <summary>
  830. /// Validates the media library internal.
  831. /// </summary>
  832. /// <param name="progress">The progress.</param>
  833. /// <param name="cancellationToken">The cancellation token.</param>
  834. /// <returns>Task.</returns>
  835. public async Task ValidateMediaLibraryInternal(IProgress<double> progress, CancellationToken cancellationToken)
  836. {
  837. _logger.Info("Validating media library");
  838. await RootFolder.RefreshMetadata(cancellationToken).ConfigureAwait(false);
  839. progress.Report(.5);
  840. // Start by just validating the children of the root, but go no further
  841. await RootFolder.ValidateChildren(new Progress<double>(), cancellationToken, recursive: false);
  842. progress.Report(1);
  843. foreach (var folder in _userManager.Users.Select(u => u.RootFolder).Distinct())
  844. {
  845. await ValidateCollectionFolders(folder, cancellationToken).ConfigureAwait(false);
  846. }
  847. progress.Report(2);
  848. // Run prescan tasks
  849. await RunPrescanTasks(progress, cancellationToken).ConfigureAwait(false);
  850. progress.Report(15);
  851. var innerProgress = new ActionableProgress<double>();
  852. innerProgress.RegisterAction(pct => progress.Report(15 + pct * .65));
  853. // Now validate the entire media library
  854. await RootFolder.ValidateChildren(innerProgress, cancellationToken, recursive: true).ConfigureAwait(false);
  855. progress.Report(80);
  856. // Run post-scan tasks
  857. await RunPostScanTasks(progress, cancellationToken).ConfigureAwait(false);
  858. progress.Report(100);
  859. }
  860. /// <summary>
  861. /// Runs the prescan tasks.
  862. /// </summary>
  863. /// <param name="progress">The progress.</param>
  864. /// <param name="cancellationToken">The cancellation token.</param>
  865. /// <returns>Task.</returns>
  866. private async Task RunPrescanTasks(IProgress<double> progress, CancellationToken cancellationToken)
  867. {
  868. var prescanTasks = PrescanTasks.ToList();
  869. var progressDictionary = new Dictionary<ILibraryPrescanTask, double>();
  870. var tasks = prescanTasks.Select(i => Task.Run(async () =>
  871. {
  872. var innerProgress = new ActionableProgress<double>();
  873. innerProgress.RegisterAction(pct =>
  874. {
  875. lock (progressDictionary)
  876. {
  877. progressDictionary[i] = pct;
  878. double percent = progressDictionary.Values.Sum();
  879. percent /= prescanTasks.Count;
  880. progress.Report(2 + percent * .13);
  881. }
  882. });
  883. try
  884. {
  885. await i.Run(innerProgress, cancellationToken);
  886. }
  887. catch (Exception ex)
  888. {
  889. _logger.ErrorException("Error running prescan task", ex);
  890. }
  891. }));
  892. await Task.WhenAll(tasks).ConfigureAwait(false);
  893. }
  894. /// <summary>
  895. /// Runs the post scan tasks.
  896. /// </summary>
  897. /// <param name="progress">The progress.</param>
  898. /// <param name="cancellationToken">The cancellation token.</param>
  899. /// <returns>Task.</returns>
  900. private async Task RunPostScanTasks(IProgress<double> progress, CancellationToken cancellationToken)
  901. {
  902. var postscanTasks = PostscanTasks.ToList();
  903. var progressDictionary = new Dictionary<ILibraryPostScanTask, double>();
  904. var tasks = postscanTasks.Select(i => Task.Run(async () =>
  905. {
  906. var innerProgress = new ActionableProgress<double>();
  907. innerProgress.RegisterAction(pct =>
  908. {
  909. lock (progressDictionary)
  910. {
  911. progressDictionary[i] = pct;
  912. double percent = progressDictionary.Values.Sum();
  913. percent /= postscanTasks.Count;
  914. progress.Report(80 + percent * .2);
  915. }
  916. });
  917. try
  918. {
  919. await i.Run(innerProgress, cancellationToken);
  920. }
  921. catch (Exception ex)
  922. {
  923. _logger.ErrorException("Error running postscan task", ex);
  924. }
  925. }));
  926. await Task.WhenAll(tasks).ConfigureAwait(false);
  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, "*.lnk", SearchOption.TopDirectoryOnly).Select(FileSystem.ResolveShortcut).OrderBy(i => i).ToList()
  970. });
  971. }
  972. /// <summary>
  973. /// Gets the item by id.
  974. /// </summary>
  975. /// <param name="id">The id.</param>
  976. /// <returns>BaseItem.</returns>
  977. /// <exception cref="System.ArgumentNullException">id</exception>
  978. public BaseItem GetItemById(Guid id)
  979. {
  980. if (id == Guid.Empty)
  981. {
  982. throw new ArgumentNullException("id");
  983. }
  984. BaseItem item;
  985. if (LibraryItemsCache.TryGetValue(id, out item))
  986. {
  987. return item;
  988. }
  989. return ItemRepository.GetItem(id);
  990. }
  991. /// <summary>
  992. /// Gets the intros.
  993. /// </summary>
  994. /// <param name="item">The item.</param>
  995. /// <param name="user">The user.</param>
  996. /// <returns>IEnumerable{System.String}.</returns>
  997. public IEnumerable<string> GetIntros(BaseItem item, User user)
  998. {
  999. return IntroProviders.SelectMany(i => i.GetIntros(item, user));
  1000. }
  1001. /// <summary>
  1002. /// Sorts the specified sort by.
  1003. /// </summary>
  1004. /// <param name="items">The items.</param>
  1005. /// <param name="user">The user.</param>
  1006. /// <param name="sortBy">The sort by.</param>
  1007. /// <param name="sortOrder">The sort order.</param>
  1008. /// <returns>IEnumerable{BaseItem}.</returns>
  1009. public IEnumerable<BaseItem> Sort(IEnumerable<BaseItem> items, User user, IEnumerable<string> sortBy, SortOrder sortOrder)
  1010. {
  1011. var isFirst = true;
  1012. IOrderedEnumerable<BaseItem> orderedItems = null;
  1013. foreach (var orderBy in sortBy.Select(o => GetComparer(o, user)).Where(c => c != null))
  1014. {
  1015. if (isFirst)
  1016. {
  1017. orderedItems = sortOrder == SortOrder.Descending ? items.OrderByDescending(i => i, orderBy) : items.OrderBy(i => i, orderBy);
  1018. }
  1019. else
  1020. {
  1021. orderedItems = sortOrder == SortOrder.Descending ? orderedItems.ThenByDescending(i => i, orderBy) : orderedItems.ThenBy(i => i, orderBy);
  1022. }
  1023. isFirst = false;
  1024. }
  1025. return orderedItems ?? items;
  1026. }
  1027. /// <summary>
  1028. /// Gets the comparer.
  1029. /// </summary>
  1030. /// <param name="name">The name.</param>
  1031. /// <param name="user">The user.</param>
  1032. /// <returns>IBaseItemComparer.</returns>
  1033. private IBaseItemComparer GetComparer(string name, User user)
  1034. {
  1035. var comparer = Comparers.FirstOrDefault(c => string.Equals(name, c.Name, StringComparison.OrdinalIgnoreCase));
  1036. if (comparer != null)
  1037. {
  1038. // If it requires a user, create a new one, and assign the user
  1039. if (comparer is IUserBaseItemComparer)
  1040. {
  1041. var userComparer = (IUserBaseItemComparer)Activator.CreateInstance(comparer.GetType());
  1042. userComparer.User = user;
  1043. userComparer.UserManager = _userManager;
  1044. userComparer.UserDataRepository = _userDataRepository;
  1045. return userComparer;
  1046. }
  1047. }
  1048. return comparer;
  1049. }
  1050. /// <summary>
  1051. /// Creates the item.
  1052. /// </summary>
  1053. /// <param name="item">The item.</param>
  1054. /// <param name="cancellationToken">The cancellation token.</param>
  1055. /// <returns>Task.</returns>
  1056. public Task CreateItem(BaseItem item, CancellationToken cancellationToken)
  1057. {
  1058. return CreateItems(new[] { item }, cancellationToken);
  1059. }
  1060. /// <summary>
  1061. /// Creates the items.
  1062. /// </summary>
  1063. /// <param name="items">The items.</param>
  1064. /// <param name="cancellationToken">The cancellation token.</param>
  1065. /// <returns>Task.</returns>
  1066. public async Task CreateItems(IEnumerable<BaseItem> items, CancellationToken cancellationToken)
  1067. {
  1068. var list = items.ToList();
  1069. await ItemRepository.SaveItems(list, cancellationToken).ConfigureAwait(false);
  1070. foreach (var item in list)
  1071. {
  1072. UpdateItemInLibraryCache(item);
  1073. }
  1074. if (ItemAdded != null)
  1075. {
  1076. foreach (var item in list)
  1077. {
  1078. try
  1079. {
  1080. ItemAdded(this, new ItemChangeEventArgs { Item = item });
  1081. }
  1082. catch (Exception ex)
  1083. {
  1084. _logger.ErrorException("Error in ItemAdded event handler", ex);
  1085. }
  1086. }
  1087. }
  1088. }
  1089. /// <summary>
  1090. /// Updates the items.
  1091. /// </summary>
  1092. /// <param name="items">The items.</param>
  1093. /// <param name="cancellationToken">The cancellation token.</param>
  1094. /// <returns>Task.</returns>
  1095. private async Task UpdateItems(IEnumerable<BaseItem> items, CancellationToken cancellationToken)
  1096. {
  1097. var list = items.ToList();
  1098. await ItemRepository.SaveItems(list, cancellationToken).ConfigureAwait(false);
  1099. foreach (var item in list)
  1100. {
  1101. UpdateItemInLibraryCache(item);
  1102. }
  1103. foreach (var item in list)
  1104. {
  1105. await OnItemUpdated(item, CancellationToken.None).ConfigureAwait(false);
  1106. }
  1107. }
  1108. /// <summary>
  1109. /// Updates the item.
  1110. /// </summary>
  1111. /// <param name="item">The item.</param>
  1112. /// <param name="cancellationToken">The cancellation token.</param>
  1113. /// <returns>Task.</returns>
  1114. public Task UpdateItem(BaseItem item, CancellationToken cancellationToken)
  1115. {
  1116. return UpdateItems(new[] { item }, cancellationToken);
  1117. }
  1118. /// <summary>
  1119. /// Reports the item removed.
  1120. /// </summary>
  1121. /// <param name="item">The item.</param>
  1122. public void ReportItemRemoved(BaseItem item)
  1123. {
  1124. if (ItemRemoved != null)
  1125. {
  1126. try
  1127. {
  1128. ItemRemoved(this, new ItemChangeEventArgs { Item = item });
  1129. }
  1130. catch (Exception ex)
  1131. {
  1132. _logger.ErrorException("Error in ItemRemoved event handler", ex);
  1133. }
  1134. }
  1135. }
  1136. /// <summary>
  1137. /// Retrieves the item.
  1138. /// </summary>
  1139. /// <param name="id">The id.</param>
  1140. /// <returns>Task{BaseItem}.</returns>
  1141. public BaseItem RetrieveItem(Guid id)
  1142. {
  1143. return ItemRepository.GetItem(id);
  1144. }
  1145. /// <summary>
  1146. /// Saves the children.
  1147. /// </summary>
  1148. /// <param name="id">The id.</param>
  1149. /// <param name="children">The children.</param>
  1150. /// <param name="cancellationToken">The cancellation token.</param>
  1151. /// <returns>Task.</returns>
  1152. public Task SaveChildren(Guid id, IEnumerable<BaseItem> children, CancellationToken cancellationToken)
  1153. {
  1154. return ItemRepository.SaveChildren(id, children, cancellationToken);
  1155. }
  1156. /// <summary>
  1157. /// Retrieves the children.
  1158. /// </summary>
  1159. /// <param name="parent">The parent.</param>
  1160. /// <returns>IEnumerable{BaseItem}.</returns>
  1161. public IEnumerable<BaseItem> RetrieveChildren(Folder parent)
  1162. {
  1163. var children = ItemRepository.RetrieveChildren(parent).ToList();
  1164. foreach (var child in children)
  1165. {
  1166. child.Parent = parent;
  1167. }
  1168. return children;
  1169. }
  1170. /// <summary>
  1171. /// Called when [item updated].
  1172. /// </summary>
  1173. /// <param name="item">The item.</param>
  1174. /// <param name="cancellationToken">The cancellation token.</param>
  1175. /// <returns>Task.</returns>
  1176. private async Task OnItemUpdated(BaseItem item, CancellationToken cancellationToken)
  1177. {
  1178. if (ConfigurationManager.Configuration.SaveLocalMeta && item.LocationType == LocationType.FileSystem)
  1179. {
  1180. foreach (var saver in Savers.Where(i => i.Supports(item)))
  1181. {
  1182. try
  1183. {
  1184. await saver.Save(item, cancellationToken).ConfigureAwait(false);
  1185. }
  1186. catch (Exception ex)
  1187. {
  1188. _logger.ErrorException("Error in metadata saver", ex);
  1189. }
  1190. }
  1191. }
  1192. if (ItemUpdated != null)
  1193. {
  1194. try
  1195. {
  1196. ItemUpdated(this, new ItemChangeEventArgs { Item = item });
  1197. }
  1198. catch (Exception ex)
  1199. {
  1200. _logger.ErrorException("Error in ItemUpdated event handler", ex);
  1201. }
  1202. }
  1203. }
  1204. }
  1205. }