2
0

LibraryManager.cs 50 KB

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