LibraryManager.cs 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414
  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 (folder.Id == Guid.Empty)
  498. {
  499. folder.Id = (folder.Path ?? folder.Name ?? folder.GetType().Name).GetMBId(folder.GetType());
  500. }
  501. rootFolder.AddVirtualChild(folder);
  502. }
  503. return rootFolder;
  504. }
  505. /// <summary>
  506. /// Gets the user root folder.
  507. /// </summary>
  508. /// <param name="userRootPath">The user root path.</param>
  509. /// <returns>UserRootFolder.</returns>
  510. public UserRootFolder GetUserRootFolder(string userRootPath)
  511. {
  512. return _userRootFolders.GetOrAdd(userRootPath, key => RetrieveItem(userRootPath.GetMBId(typeof(UserRootFolder))) as UserRootFolder ?? (UserRootFolder)ResolvePath(new DirectoryInfo(userRootPath)));
  513. }
  514. /// <summary>
  515. /// Gets a Person
  516. /// </summary>
  517. /// <param name="name">The name.</param>
  518. /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param>
  519. /// <returns>Task{Person}.</returns>
  520. public Task<Person> GetPerson(string name, bool allowSlowProviders = false)
  521. {
  522. return GetPerson(name, CancellationToken.None, allowSlowProviders);
  523. }
  524. /// <summary>
  525. /// Gets a Person
  526. /// </summary>
  527. /// <param name="name">The name.</param>
  528. /// <param name="cancellationToken">The cancellation token.</param>
  529. /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param>
  530. /// <param name="forceCreation">if set to <c>true</c> [force creation].</param>
  531. /// <returns>Task{Person}.</returns>
  532. private Task<Person> GetPerson(string name, CancellationToken cancellationToken, bool allowSlowProviders = false, bool forceCreation = false)
  533. {
  534. return GetItemByName<Person>(ConfigurationManager.ApplicationPaths.PeoplePath, name, cancellationToken, allowSlowProviders, forceCreation);
  535. }
  536. /// <summary>
  537. /// Gets a Studio
  538. /// </summary>
  539. /// <param name="name">The name.</param>
  540. /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param>
  541. /// <returns>Task{Studio}.</returns>
  542. public Task<Studio> GetStudio(string name, bool allowSlowProviders = false)
  543. {
  544. return GetItemByName<Studio>(ConfigurationManager.ApplicationPaths.StudioPath, name, CancellationToken.None, allowSlowProviders);
  545. }
  546. /// <summary>
  547. /// Gets a Genre
  548. /// </summary>
  549. /// <param name="name">The name.</param>
  550. /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param>
  551. /// <returns>Task{Genre}.</returns>
  552. public Task<Genre> GetGenre(string name, bool allowSlowProviders = false)
  553. {
  554. return GetItemByName<Genre>(ConfigurationManager.ApplicationPaths.GenrePath, name, CancellationToken.None, allowSlowProviders);
  555. }
  556. /// <summary>
  557. /// Gets the genre.
  558. /// </summary>
  559. /// <param name="name">The name.</param>
  560. /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param>
  561. /// <returns>Task{MusicGenre}.</returns>
  562. public Task<MusicGenre> GetMusicGenre(string name, bool allowSlowProviders = false)
  563. {
  564. return GetItemByName<MusicGenre>(ConfigurationManager.ApplicationPaths.MusicGenrePath, name, CancellationToken.None, allowSlowProviders);
  565. }
  566. /// <summary>
  567. /// Gets a Genre
  568. /// </summary>
  569. /// <param name="name">The name.</param>
  570. /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param>
  571. /// <returns>Task{Genre}.</returns>
  572. public Task<Artist> GetArtist(string name, bool allowSlowProviders = false)
  573. {
  574. return GetArtist(name, CancellationToken.None, allowSlowProviders);
  575. }
  576. /// <summary>
  577. /// Gets the artist.
  578. /// </summary>
  579. /// <param name="name">The name.</param>
  580. /// <param name="cancellationToken">The cancellation token.</param>
  581. /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param>
  582. /// <param name="forceCreation">if set to <c>true</c> [force creation].</param>
  583. /// <returns>Task{Artist}.</returns>
  584. private Task<Artist> GetArtist(string name, CancellationToken cancellationToken, bool allowSlowProviders = false, bool forceCreation = false)
  585. {
  586. return GetItemByName<Artist>(ConfigurationManager.ApplicationPaths.ArtistsPath, name, cancellationToken, allowSlowProviders, forceCreation);
  587. }
  588. /// <summary>
  589. /// The us culture
  590. /// </summary>
  591. private static readonly CultureInfo UsCulture = new CultureInfo("en-US");
  592. /// <summary>
  593. /// Gets a Year
  594. /// </summary>
  595. /// <param name="value">The value.</param>
  596. /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param>
  597. /// <returns>Task{Year}.</returns>
  598. /// <exception cref="System.ArgumentOutOfRangeException"></exception>
  599. public Task<Year> GetYear(int value, bool allowSlowProviders = false)
  600. {
  601. if (value <= 0)
  602. {
  603. throw new ArgumentOutOfRangeException();
  604. }
  605. return GetItemByName<Year>(ConfigurationManager.ApplicationPaths.YearPath, value.ToString(UsCulture), CancellationToken.None, allowSlowProviders);
  606. }
  607. /// <summary>
  608. /// The images by name item cache
  609. /// </summary>
  610. private readonly ConcurrentDictionary<string, BaseItem> _itemsByName = new ConcurrentDictionary<string, BaseItem>(StringComparer.OrdinalIgnoreCase);
  611. /// <summary>
  612. /// Generically retrieves an IBN item
  613. /// </summary>
  614. /// <typeparam name="T"></typeparam>
  615. /// <param name="path">The path.</param>
  616. /// <param name="name">The name.</param>
  617. /// <param name="cancellationToken">The cancellation token.</param>
  618. /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param>
  619. /// <param name="forceCreation">if set to <c>true</c> [force creation].</param>
  620. /// <returns>Task{``0}.</returns>
  621. /// <exception cref="System.ArgumentNullException">
  622. /// </exception>
  623. private async Task<T> GetItemByName<T>(string path, string name, CancellationToken cancellationToken, bool allowSlowProviders = true, bool forceCreation = false)
  624. where T : BaseItem, new()
  625. {
  626. if (string.IsNullOrEmpty(path))
  627. {
  628. throw new ArgumentNullException();
  629. }
  630. if (string.IsNullOrEmpty(name))
  631. {
  632. throw new ArgumentNullException();
  633. }
  634. var key = Path.Combine(path, FileSystem.GetValidFilename(name));
  635. BaseItem obj;
  636. if (!_itemsByName.TryGetValue(key, out obj))
  637. {
  638. obj = await CreateItemByName<T>(path, name, cancellationToken, allowSlowProviders).ConfigureAwait(false);
  639. _itemsByName.AddOrUpdate(key, obj, (keyName, oldValue) => obj);
  640. }
  641. else if (forceCreation)
  642. {
  643. await obj.RefreshMetadata(cancellationToken, false, allowSlowProviders: allowSlowProviders).ConfigureAwait(false);
  644. }
  645. return obj as T;
  646. }
  647. /// <summary>
  648. /// Creates an IBN item based on a given path
  649. /// </summary>
  650. /// <typeparam name="T"></typeparam>
  651. /// <param name="path">The path.</param>
  652. /// <param name="name">The name.</param>
  653. /// <param name="cancellationToken">The cancellation token.</param>
  654. /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param>
  655. /// <returns>Task{``0}.</returns>
  656. /// <exception cref="System.IO.IOException">Path not created: + path</exception>
  657. private async Task<T> CreateItemByName<T>(string path, string name, CancellationToken cancellationToken, bool allowSlowProviders = true)
  658. where T : BaseItem, new()
  659. {
  660. cancellationToken.ThrowIfCancellationRequested();
  661. path = Path.Combine(path, FileSystem.GetValidFilename(name));
  662. var fileInfo = new DirectoryInfo(path);
  663. var isNew = false;
  664. if (!fileInfo.Exists)
  665. {
  666. Directory.CreateDirectory(path);
  667. fileInfo = new DirectoryInfo(path);
  668. if (!fileInfo.Exists)
  669. {
  670. throw new IOException("Path not created: " + path);
  671. }
  672. isNew = true;
  673. }
  674. cancellationToken.ThrowIfCancellationRequested();
  675. var id = path.GetMBId(typeof(T));
  676. var item = RetrieveItem(id) as T;
  677. if (item == null)
  678. {
  679. item = new T
  680. {
  681. Name = name,
  682. Id = id,
  683. DateCreated = fileInfo.CreationTimeUtc,
  684. DateModified = fileInfo.LastWriteTimeUtc,
  685. Path = path
  686. };
  687. isNew = true;
  688. }
  689. cancellationToken.ThrowIfCancellationRequested();
  690. // Set this now so we don't cause additional file system access during provider executions
  691. item.ResetResolveArgs(fileInfo);
  692. await item.RefreshMetadata(cancellationToken, isNew, allowSlowProviders: allowSlowProviders).ConfigureAwait(false);
  693. cancellationToken.ThrowIfCancellationRequested();
  694. return item;
  695. }
  696. /// <summary>
  697. /// Validate and refresh the People sub-set of the IBN.
  698. /// The items are stored in the db but not loaded into memory until actually requested by an operation.
  699. /// </summary>
  700. /// <param name="cancellationToken">The cancellation token.</param>
  701. /// <param name="progress">The progress.</param>
  702. /// <returns>Task.</returns>
  703. public async Task ValidatePeople(CancellationToken cancellationToken, IProgress<double> progress)
  704. {
  705. const int maxTasks = 10;
  706. var tasks = new List<Task>();
  707. var includedPersonTypes = new[] { PersonType.Actor, PersonType.Director, PersonType.GuestStar, PersonType.Writer, PersonType.Director, PersonType.Producer };
  708. var people = RootFolder.RecursiveChildren
  709. .Where(c => c.People != null)
  710. .SelectMany(c => c.People.Where(p => includedPersonTypes.Contains(p.Type)))
  711. .DistinctBy(p => p.Name, StringComparer.OrdinalIgnoreCase)
  712. .ToList();
  713. var numComplete = 0;
  714. foreach (var person in people)
  715. {
  716. if (tasks.Count > maxTasks)
  717. {
  718. await Task.WhenAll(tasks).ConfigureAwait(false);
  719. tasks.Clear();
  720. // Safe cancellation point, when there are no pending tasks
  721. cancellationToken.ThrowIfCancellationRequested();
  722. }
  723. // Avoid accessing the foreach variable within the closure
  724. var currentPerson = person;
  725. tasks.Add(Task.Run(async () =>
  726. {
  727. cancellationToken.ThrowIfCancellationRequested();
  728. try
  729. {
  730. await GetPerson(currentPerson.Name, cancellationToken, true, true).ConfigureAwait(false);
  731. }
  732. catch (IOException ex)
  733. {
  734. _logger.ErrorException("Error validating IBN entry {0}", ex, currentPerson.Name);
  735. }
  736. // Update progress
  737. lock (progress)
  738. {
  739. numComplete++;
  740. double percent = numComplete;
  741. percent /= people.Count;
  742. progress.Report(100 * percent);
  743. }
  744. }));
  745. }
  746. await Task.WhenAll(tasks).ConfigureAwait(false);
  747. progress.Report(100);
  748. _logger.Info("People validation complete");
  749. }
  750. /// <summary>
  751. /// Validates the artists.
  752. /// </summary>
  753. /// <param name="cancellationToken">The cancellation token.</param>
  754. /// <param name="progress">The progress.</param>
  755. /// <returns>Task.</returns>
  756. public async Task ValidateArtists(CancellationToken cancellationToken, IProgress<double> progress)
  757. {
  758. const int maxTasks = 25;
  759. var tasks = new List<Task>();
  760. var artists = RootFolder.RecursiveChildren
  761. .OfType<Audio>()
  762. .SelectMany(c =>
  763. {
  764. var list = new List<string>();
  765. if (!string.IsNullOrEmpty(c.AlbumArtist))
  766. {
  767. list.Add(c.AlbumArtist);
  768. }
  769. if (!string.IsNullOrEmpty(c.Artist))
  770. {
  771. list.Add(c.Artist);
  772. }
  773. return list;
  774. })
  775. .Distinct(StringComparer.OrdinalIgnoreCase)
  776. .ToList();
  777. var numComplete = 0;
  778. foreach (var artist in artists)
  779. {
  780. if (tasks.Count > maxTasks)
  781. {
  782. await Task.WhenAll(tasks).ConfigureAwait(false);
  783. tasks.Clear();
  784. // Safe cancellation point, when there are no pending tasks
  785. cancellationToken.ThrowIfCancellationRequested();
  786. }
  787. // Avoid accessing the foreach variable within the closure
  788. var currentArtist = artist;
  789. tasks.Add(Task.Run(async () =>
  790. {
  791. cancellationToken.ThrowIfCancellationRequested();
  792. try
  793. {
  794. await GetArtist(currentArtist, cancellationToken, true, true).ConfigureAwait(false);
  795. }
  796. catch (IOException ex)
  797. {
  798. _logger.ErrorException("Error validating Artist {0}", ex, currentArtist);
  799. }
  800. // Update progress
  801. lock (progress)
  802. {
  803. numComplete++;
  804. double percent = numComplete;
  805. percent /= artists.Count;
  806. progress.Report(100 * percent);
  807. }
  808. }));
  809. }
  810. await Task.WhenAll(tasks).ConfigureAwait(false);
  811. progress.Report(100);
  812. _logger.Info("Artist validation complete");
  813. }
  814. /// <summary>
  815. /// Reloads the root media folder
  816. /// </summary>
  817. /// <param name="progress">The progress.</param>
  818. /// <param name="cancellationToken">The cancellation token.</param>
  819. /// <returns>Task.</returns>
  820. public Task ValidateMediaLibrary(IProgress<double> progress, CancellationToken cancellationToken)
  821. {
  822. // Just run the scheduled task so that the user can see it
  823. return Task.Run(() => _taskManager.CancelIfRunningAndQueue<RefreshMediaLibraryTask>());
  824. }
  825. /// <summary>
  826. /// Validates the media library internal.
  827. /// </summary>
  828. /// <param name="progress">The progress.</param>
  829. /// <param name="cancellationToken">The cancellation token.</param>
  830. /// <returns>Task.</returns>
  831. public async Task ValidateMediaLibraryInternal(IProgress<double> progress, CancellationToken cancellationToken)
  832. {
  833. _logger.Info("Validating media library");
  834. await RootFolder.RefreshMetadata(cancellationToken).ConfigureAwait(false);
  835. progress.Report(.5);
  836. // Start by just validating the children of the root, but go no further
  837. await RootFolder.ValidateChildren(new Progress<double>(), cancellationToken, recursive: false);
  838. progress.Report(1);
  839. foreach (var folder in _userManager.Users.Select(u => u.RootFolder).Distinct())
  840. {
  841. await ValidateCollectionFolders(folder, cancellationToken).ConfigureAwait(false);
  842. }
  843. progress.Report(2);
  844. // Run prescan tasks
  845. await RunPrescanTasks(progress, cancellationToken).ConfigureAwait(false);
  846. progress.Report(15);
  847. var innerProgress = new ActionableProgress<double>();
  848. innerProgress.RegisterAction(pct => progress.Report(15 + pct * .65));
  849. // Now validate the entire media library
  850. await RootFolder.ValidateChildren(innerProgress, cancellationToken, recursive: true).ConfigureAwait(false);
  851. progress.Report(80);
  852. // Run post-scan tasks
  853. await RunPostScanTasks(progress, cancellationToken).ConfigureAwait(false);
  854. progress.Report(100);
  855. }
  856. /// <summary>
  857. /// Runs the prescan tasks.
  858. /// </summary>
  859. /// <param name="progress">The progress.</param>
  860. /// <param name="cancellationToken">The cancellation token.</param>
  861. /// <returns>Task.</returns>
  862. private async Task RunPrescanTasks(IProgress<double> progress, CancellationToken cancellationToken)
  863. {
  864. var prescanTasks = PrescanTasks.ToList();
  865. var progressDictionary = new Dictionary<ILibraryPrescanTask, double>();
  866. var tasks = prescanTasks.Select(i => Task.Run(async () =>
  867. {
  868. var innerProgress = new ActionableProgress<double>();
  869. innerProgress.RegisterAction(pct =>
  870. {
  871. lock (progressDictionary)
  872. {
  873. progressDictionary[i] = pct;
  874. double percent = progressDictionary.Values.Sum();
  875. percent /= prescanTasks.Count;
  876. progress.Report(2 + percent * .13);
  877. }
  878. });
  879. try
  880. {
  881. await i.Run(innerProgress, cancellationToken);
  882. }
  883. catch (Exception ex)
  884. {
  885. _logger.ErrorException("Error running prescan task", ex);
  886. }
  887. }));
  888. await Task.WhenAll(tasks).ConfigureAwait(false);
  889. }
  890. /// <summary>
  891. /// Runs the post scan tasks.
  892. /// </summary>
  893. /// <param name="progress">The progress.</param>
  894. /// <param name="cancellationToken">The cancellation token.</param>
  895. /// <returns>Task.</returns>
  896. private async Task RunPostScanTasks(IProgress<double> progress, CancellationToken cancellationToken)
  897. {
  898. var postscanTasks = PostscanTasks.ToList();
  899. var progressDictionary = new Dictionary<ILibraryPostScanTask, double>();
  900. var tasks = postscanTasks.Select(i => Task.Run(async () =>
  901. {
  902. var innerProgress = new ActionableProgress<double>();
  903. innerProgress.RegisterAction(pct =>
  904. {
  905. lock (progressDictionary)
  906. {
  907. progressDictionary[i] = pct;
  908. double percent = progressDictionary.Values.Sum();
  909. percent /= postscanTasks.Count;
  910. progress.Report(80 + percent * .2);
  911. }
  912. });
  913. try
  914. {
  915. await i.Run(innerProgress, cancellationToken);
  916. }
  917. catch (Exception ex)
  918. {
  919. _logger.ErrorException("Error running postscan task", ex);
  920. }
  921. }));
  922. await Task.WhenAll(tasks).ConfigureAwait(false);
  923. }
  924. /// <summary>
  925. /// Validates only the collection folders for a User and goes no further
  926. /// </summary>
  927. /// <param name="userRootFolder">The user root folder.</param>
  928. /// <param name="cancellationToken">The cancellation token.</param>
  929. /// <returns>Task.</returns>
  930. private async Task ValidateCollectionFolders(UserRootFolder userRootFolder, CancellationToken cancellationToken)
  931. {
  932. _logger.Info("Validating collection folders within {0}", userRootFolder.Path);
  933. await userRootFolder.RefreshMetadata(cancellationToken).ConfigureAwait(false);
  934. cancellationToken.ThrowIfCancellationRequested();
  935. await userRootFolder.ValidateChildren(new Progress<double>(), cancellationToken, recursive: false).ConfigureAwait(false);
  936. }
  937. /// <summary>
  938. /// Gets the default view.
  939. /// </summary>
  940. /// <returns>IEnumerable{VirtualFolderInfo}.</returns>
  941. public IEnumerable<VirtualFolderInfo> GetDefaultVirtualFolders()
  942. {
  943. return GetView(ConfigurationManager.ApplicationPaths.DefaultUserViewsPath);
  944. }
  945. /// <summary>
  946. /// Gets the view.
  947. /// </summary>
  948. /// <param name="user">The user.</param>
  949. /// <returns>IEnumerable{VirtualFolderInfo}.</returns>
  950. public IEnumerable<VirtualFolderInfo> GetVirtualFolders(User user)
  951. {
  952. return GetView(user.RootFolderPath);
  953. }
  954. /// <summary>
  955. /// Gets the view.
  956. /// </summary>
  957. /// <param name="path">The path.</param>
  958. /// <returns>IEnumerable{VirtualFolderInfo}.</returns>
  959. private IEnumerable<VirtualFolderInfo> GetView(string path)
  960. {
  961. return Directory.EnumerateDirectories(path, "*", SearchOption.TopDirectoryOnly)
  962. .Select(dir => new VirtualFolderInfo
  963. {
  964. Name = Path.GetFileName(dir),
  965. Locations = Directory.EnumerateFiles(dir, "*.lnk", SearchOption.TopDirectoryOnly).Select(FileSystem.ResolveShortcut).OrderBy(i => i).ToList()
  966. });
  967. }
  968. /// <summary>
  969. /// Gets the item by id.
  970. /// </summary>
  971. /// <param name="id">The id.</param>
  972. /// <returns>BaseItem.</returns>
  973. /// <exception cref="System.ArgumentNullException">id</exception>
  974. public BaseItem GetItemById(Guid id)
  975. {
  976. if (id == Guid.Empty)
  977. {
  978. throw new ArgumentNullException("id");
  979. }
  980. BaseItem item;
  981. if (LibraryItemsCache.TryGetValue(id, out item))
  982. {
  983. return item;
  984. }
  985. return ItemRepository.GetItem(id);
  986. }
  987. /// <summary>
  988. /// Gets the intros.
  989. /// </summary>
  990. /// <param name="item">The item.</param>
  991. /// <param name="user">The user.</param>
  992. /// <returns>IEnumerable{System.String}.</returns>
  993. public IEnumerable<string> GetIntros(BaseItem item, User user)
  994. {
  995. return IntroProviders.SelectMany(i => i.GetIntros(item, user));
  996. }
  997. /// <summary>
  998. /// Sorts the specified sort by.
  999. /// </summary>
  1000. /// <param name="items">The items.</param>
  1001. /// <param name="user">The user.</param>
  1002. /// <param name="sortBy">The sort by.</param>
  1003. /// <param name="sortOrder">The sort order.</param>
  1004. /// <returns>IEnumerable{BaseItem}.</returns>
  1005. public IEnumerable<BaseItem> Sort(IEnumerable<BaseItem> items, User user, IEnumerable<string> sortBy, SortOrder sortOrder)
  1006. {
  1007. var isFirst = true;
  1008. IOrderedEnumerable<BaseItem> orderedItems = null;
  1009. foreach (var orderBy in sortBy.Select(o => GetComparer(o, user)).Where(c => c != null))
  1010. {
  1011. if (isFirst)
  1012. {
  1013. orderedItems = sortOrder == SortOrder.Descending ? items.OrderByDescending(i => i, orderBy) : items.OrderBy(i => i, orderBy);
  1014. }
  1015. else
  1016. {
  1017. orderedItems = sortOrder == SortOrder.Descending ? orderedItems.ThenByDescending(i => i, orderBy) : orderedItems.ThenBy(i => i, orderBy);
  1018. }
  1019. isFirst = false;
  1020. }
  1021. return orderedItems ?? items;
  1022. }
  1023. /// <summary>
  1024. /// Gets the comparer.
  1025. /// </summary>
  1026. /// <param name="name">The name.</param>
  1027. /// <param name="user">The user.</param>
  1028. /// <returns>IBaseItemComparer.</returns>
  1029. private IBaseItemComparer GetComparer(string name, User user)
  1030. {
  1031. var comparer = Comparers.FirstOrDefault(c => string.Equals(name, c.Name, StringComparison.OrdinalIgnoreCase));
  1032. if (comparer != null)
  1033. {
  1034. // If it requires a user, create a new one, and assign the user
  1035. if (comparer is IUserBaseItemComparer)
  1036. {
  1037. var userComparer = (IUserBaseItemComparer)Activator.CreateInstance(comparer.GetType());
  1038. userComparer.User = user;
  1039. userComparer.UserManager = _userManager;
  1040. userComparer.UserDataRepository = _userDataRepository;
  1041. return userComparer;
  1042. }
  1043. }
  1044. return comparer;
  1045. }
  1046. /// <summary>
  1047. /// Creates the item.
  1048. /// </summary>
  1049. /// <param name="item">The item.</param>
  1050. /// <param name="cancellationToken">The cancellation token.</param>
  1051. /// <returns>Task.</returns>
  1052. public Task CreateItem(BaseItem item, CancellationToken cancellationToken)
  1053. {
  1054. return CreateItems(new[] { item }, cancellationToken);
  1055. }
  1056. /// <summary>
  1057. /// Creates the items.
  1058. /// </summary>
  1059. /// <param name="items">The items.</param>
  1060. /// <param name="cancellationToken">The cancellation token.</param>
  1061. /// <returns>Task.</returns>
  1062. public async Task CreateItems(IEnumerable<BaseItem> items, CancellationToken cancellationToken)
  1063. {
  1064. var list = items.ToList();
  1065. await ItemRepository.SaveItems(list, cancellationToken).ConfigureAwait(false);
  1066. foreach (var item in list)
  1067. {
  1068. UpdateItemInLibraryCache(item);
  1069. }
  1070. if (ItemAdded != null)
  1071. {
  1072. foreach (var item in list)
  1073. {
  1074. try
  1075. {
  1076. ItemAdded(this, new ItemChangeEventArgs { Item = item });
  1077. }
  1078. catch (Exception ex)
  1079. {
  1080. _logger.ErrorException("Error in ItemAdded event handler", ex);
  1081. }
  1082. }
  1083. }
  1084. }
  1085. /// <summary>
  1086. /// Updates the items.
  1087. /// </summary>
  1088. /// <param name="items">The items.</param>
  1089. /// <param name="cancellationToken">The cancellation token.</param>
  1090. /// <returns>Task.</returns>
  1091. private async Task UpdateItems(IEnumerable<BaseItem> items, CancellationToken cancellationToken)
  1092. {
  1093. var list = items.ToList();
  1094. await ItemRepository.SaveItems(list, cancellationToken).ConfigureAwait(false);
  1095. foreach (var item in list)
  1096. {
  1097. UpdateItemInLibraryCache(item);
  1098. }
  1099. foreach (var item in list)
  1100. {
  1101. await OnItemUpdated(item, CancellationToken.None).ConfigureAwait(false);
  1102. }
  1103. }
  1104. /// <summary>
  1105. /// Updates the item.
  1106. /// </summary>
  1107. /// <param name="item">The item.</param>
  1108. /// <param name="cancellationToken">The cancellation token.</param>
  1109. /// <returns>Task.</returns>
  1110. public Task UpdateItem(BaseItem item, CancellationToken cancellationToken)
  1111. {
  1112. return UpdateItems(new[] { item }, cancellationToken);
  1113. }
  1114. /// <summary>
  1115. /// Reports the item removed.
  1116. /// </summary>
  1117. /// <param name="item">The item.</param>
  1118. public void ReportItemRemoved(BaseItem item)
  1119. {
  1120. if (ItemRemoved != null)
  1121. {
  1122. try
  1123. {
  1124. ItemRemoved(this, new ItemChangeEventArgs { Item = item });
  1125. }
  1126. catch (Exception ex)
  1127. {
  1128. _logger.ErrorException("Error in ItemRemoved event handler", ex);
  1129. }
  1130. }
  1131. }
  1132. /// <summary>
  1133. /// Retrieves the item.
  1134. /// </summary>
  1135. /// <param name="id">The id.</param>
  1136. /// <returns>Task{BaseItem}.</returns>
  1137. public BaseItem RetrieveItem(Guid id)
  1138. {
  1139. return ItemRepository.GetItem(id);
  1140. }
  1141. /// <summary>
  1142. /// Saves the children.
  1143. /// </summary>
  1144. /// <param name="id">The id.</param>
  1145. /// <param name="children">The children.</param>
  1146. /// <param name="cancellationToken">The cancellation token.</param>
  1147. /// <returns>Task.</returns>
  1148. public Task SaveChildren(Guid id, IEnumerable<BaseItem> children, CancellationToken cancellationToken)
  1149. {
  1150. return ItemRepository.SaveChildren(id, children, cancellationToken);
  1151. }
  1152. /// <summary>
  1153. /// Retrieves the children.
  1154. /// </summary>
  1155. /// <param name="parent">The parent.</param>
  1156. /// <returns>IEnumerable{BaseItem}.</returns>
  1157. public IEnumerable<BaseItem> RetrieveChildren(Folder parent)
  1158. {
  1159. var children = ItemRepository.RetrieveChildren(parent).ToList();
  1160. foreach (var child in children)
  1161. {
  1162. child.Parent = parent;
  1163. }
  1164. return children;
  1165. }
  1166. /// <summary>
  1167. /// Called when [item updated].
  1168. /// </summary>
  1169. /// <param name="item">The item.</param>
  1170. /// <param name="cancellationToken">The cancellation token.</param>
  1171. /// <returns>Task.</returns>
  1172. private async Task OnItemUpdated(BaseItem item, CancellationToken cancellationToken)
  1173. {
  1174. if (ConfigurationManager.Configuration.SaveLocalMeta && item.LocationType == LocationType.FileSystem)
  1175. {
  1176. foreach (var saver in Savers.Where(i => i.Supports(item)))
  1177. {
  1178. try
  1179. {
  1180. await saver.Save(item, cancellationToken).ConfigureAwait(false);
  1181. }
  1182. catch (Exception ex)
  1183. {
  1184. _logger.ErrorException("Error in metadata saver", ex);
  1185. }
  1186. }
  1187. }
  1188. if (ItemUpdated != null)
  1189. {
  1190. try
  1191. {
  1192. ItemUpdated(this, new ItemChangeEventArgs { Item = item });
  1193. }
  1194. catch (Exception ex)
  1195. {
  1196. _logger.ErrorException("Error in ItemUpdated event handler", ex);
  1197. }
  1198. }
  1199. }
  1200. }
  1201. }