LibraryManager.cs 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451
  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 fileSystemDictionary = FileData.GetFilteredFileSystemEntries(args.Path, _fileSystem, _logger, args, flattenFolderDepth: flattenFolderDepth, resolveShortcuts: isPhysicalRoot || args.IsVf);
  434. // Need to remove subpaths that may have been resolved from shortcuts
  435. // Example: if \\server\movies exists, then strip out \\server\movies\action
  436. if (isPhysicalRoot)
  437. {
  438. var paths = NormalizeRootPathList(fileSystemDictionary.Keys);
  439. fileSystemDictionary = paths.Select(i => (FileSystemInfo)new DirectoryInfo(i)).ToDictionary(i => i.FullName);
  440. }
  441. args.FileSystemDictionary = fileSystemDictionary;
  442. }
  443. // Check to see if we should resolve based on our contents
  444. if (args.IsDirectory && !ShouldResolvePathContents(args))
  445. {
  446. return null;
  447. }
  448. return ResolveItem(args);
  449. }
  450. public IEnumerable<string> NormalizeRootPathList(IEnumerable<string> paths)
  451. {
  452. var list = paths.Select(_fileSystem.NormalizePath)
  453. .Distinct(StringComparer.OrdinalIgnoreCase)
  454. .ToList();
  455. var dupes = list.Where(subPath => !subPath.EndsWith(":\\", StringComparison.OrdinalIgnoreCase) && list.Any(i => _fileSystem.ContainsSubPath(i, subPath)))
  456. .ToList();
  457. foreach (var dupe in dupes)
  458. {
  459. _logger.Info("Found duplicate path: {0}", dupe);
  460. }
  461. return list.Except(dupes, StringComparer.OrdinalIgnoreCase);
  462. }
  463. /// <summary>
  464. /// Determines whether a path should be ignored based on its contents - called after the contents have been read
  465. /// </summary>
  466. /// <param name="args">The args.</param>
  467. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  468. private static bool ShouldResolvePathContents(ItemResolveArgs args)
  469. {
  470. // Ignore any folders containing a file called .ignore
  471. return !args.ContainsFileSystemEntryByName(".ignore");
  472. }
  473. /// <summary>
  474. /// Resolves a set of files into a list of BaseItem
  475. /// </summary>
  476. /// <typeparam name="T"></typeparam>
  477. /// <param name="files">The files.</param>
  478. /// <param name="parent">The parent.</param>
  479. /// <returns>List{``0}.</returns>
  480. public List<T> ResolvePaths<T>(IEnumerable<FileSystemInfo> files, Folder parent)
  481. where T : BaseItem
  482. {
  483. var list = new List<T>();
  484. Parallel.ForEach(files, f =>
  485. {
  486. try
  487. {
  488. var item = ResolvePath(f, parent) as T;
  489. if (item != null)
  490. {
  491. lock (list)
  492. {
  493. list.Add(item);
  494. }
  495. }
  496. }
  497. catch (Exception ex)
  498. {
  499. _logger.ErrorException("Error resolving path {0}", ex, f.FullName);
  500. }
  501. });
  502. return list;
  503. }
  504. /// <summary>
  505. /// Creates the root media folder
  506. /// </summary>
  507. /// <returns>AggregateFolder.</returns>
  508. /// <exception cref="System.InvalidOperationException">Cannot create the root folder until plugins have loaded</exception>
  509. public AggregateFolder CreateRootFolder()
  510. {
  511. var rootFolderPath = ConfigurationManager.ApplicationPaths.RootFolderPath;
  512. if (!Directory.Exists(rootFolderPath))
  513. {
  514. Directory.CreateDirectory(rootFolderPath);
  515. }
  516. var rootFolder = RetrieveItem(rootFolderPath.GetMBId(typeof(AggregateFolder))) as AggregateFolder ?? (AggregateFolder)ResolvePath(new DirectoryInfo(rootFolderPath));
  517. // Add in the plug-in folders
  518. foreach (var child in PluginFolderCreators)
  519. {
  520. var folder = child.GetFolder();
  521. if (folder.Id == Guid.Empty)
  522. {
  523. folder.Id = (folder.Path ?? folder.GetType().Name).GetMBId(folder.GetType());
  524. }
  525. rootFolder.AddVirtualChild(folder);
  526. }
  527. return rootFolder;
  528. }
  529. /// <summary>
  530. /// Gets the user root folder.
  531. /// </summary>
  532. /// <param name="userRootPath">The user root path.</param>
  533. /// <returns>UserRootFolder.</returns>
  534. public UserRootFolder GetUserRootFolder(string userRootPath)
  535. {
  536. return _userRootFolders.GetOrAdd(userRootPath, key => RetrieveItem(userRootPath.GetMBId(typeof(UserRootFolder))) as UserRootFolder ??
  537. (UserRootFolder)ResolvePath(new DirectoryInfo(userRootPath)));
  538. }
  539. public Person GetPersonSync(string name)
  540. {
  541. return GetItemByName<Person>(ConfigurationManager.ApplicationPaths.PeoplePath, name);
  542. }
  543. /// <summary>
  544. /// Gets a Person
  545. /// </summary>
  546. /// <param name="name">The name.</param>
  547. /// <returns>Task{Person}.</returns>
  548. public Person GetPerson(string name)
  549. {
  550. return GetItemByName<Person>(ConfigurationManager.ApplicationPaths.PeoplePath, name);
  551. }
  552. /// <summary>
  553. /// Gets a Studio
  554. /// </summary>
  555. /// <param name="name">The name.</param>
  556. /// <returns>Task{Studio}.</returns>
  557. public Studio GetStudio(string name)
  558. {
  559. return GetItemByName<Studio>(ConfigurationManager.ApplicationPaths.StudioPath, name);
  560. }
  561. /// <summary>
  562. /// Gets a Genre
  563. /// </summary>
  564. /// <param name="name">The name.</param>
  565. /// <returns>Task{Genre}.</returns>
  566. public Genre GetGenre(string name)
  567. {
  568. return GetItemByName<Genre>(ConfigurationManager.ApplicationPaths.GenrePath, name);
  569. }
  570. /// <summary>
  571. /// Gets the genre.
  572. /// </summary>
  573. /// <param name="name">The name.</param>
  574. /// <returns>Task{MusicGenre}.</returns>
  575. public MusicGenre GetMusicGenre(string name)
  576. {
  577. return GetItemByName<MusicGenre>(ConfigurationManager.ApplicationPaths.MusicGenrePath, name);
  578. }
  579. /// <summary>
  580. /// Gets the game genre.
  581. /// </summary>
  582. /// <param name="name">The name.</param>
  583. /// <returns>Task{GameGenre}.</returns>
  584. public GameGenre GetGameGenre(string name)
  585. {
  586. return GetItemByName<GameGenre>(ConfigurationManager.ApplicationPaths.GameGenrePath, name);
  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. /// <returns>Task{Year}.</returns>
  597. /// <exception cref="System.ArgumentOutOfRangeException"></exception>
  598. public Year GetYear(int value)
  599. {
  600. if (value <= 0)
  601. {
  602. throw new ArgumentOutOfRangeException("Years less than or equal to 0 are invalid.");
  603. }
  604. return GetItemByName<Year>(ConfigurationManager.ApplicationPaths.YearPath, value.ToString(UsCulture));
  605. }
  606. /// <summary>
  607. /// Gets a Genre
  608. /// </summary>
  609. /// <param name="name">The name.</param>
  610. /// <returns>Task{Genre}.</returns>
  611. public MusicArtist GetArtist(string name)
  612. {
  613. return GetItemByName<MusicArtist>(ConfigurationManager.ApplicationPaths.ArtistsPath, name);
  614. }
  615. /// <summary>
  616. /// The images by name item cache
  617. /// </summary>
  618. private readonly ConcurrentDictionary<string, BaseItem> _itemsByName = new ConcurrentDictionary<string, BaseItem>(StringComparer.OrdinalIgnoreCase);
  619. private T GetItemByName<T>(string path, string name)
  620. where T : BaseItem, new()
  621. {
  622. if (string.IsNullOrEmpty(path))
  623. {
  624. throw new ArgumentNullException("path");
  625. }
  626. if (string.IsNullOrEmpty(name))
  627. {
  628. throw new ArgumentNullException("name");
  629. }
  630. var validFilename = _fileSystem.GetValidFilename(name).Trim();
  631. string subFolderPrefix = null;
  632. if (typeof(T) == typeof(Person) && ConfigurationManager.Configuration.EnablePeoplePrefixSubFolders)
  633. {
  634. subFolderPrefix = validFilename.Substring(0, 1);
  635. }
  636. var key = string.IsNullOrEmpty(subFolderPrefix) ?
  637. Path.Combine(path, validFilename) :
  638. Path.Combine(path, subFolderPrefix, validFilename);
  639. BaseItem obj;
  640. if (!_itemsByName.TryGetValue(key, out obj))
  641. {
  642. var tuple = CreateItemByName<T>(key, name);
  643. obj = tuple.Item2;
  644. _itemsByName.AddOrUpdate(key, obj, (keyName, oldValue) => obj);
  645. }
  646. return obj as T;
  647. }
  648. /// <summary>
  649. /// Creates an IBN item based on a given path
  650. /// </summary>
  651. /// <typeparam name="T"></typeparam>
  652. /// <param name="path">The path.</param>
  653. /// <param name="name">The name.</param>
  654. /// <returns>Task{``0}.</returns>
  655. /// <exception cref="System.IO.IOException">Path not created: + path</exception>
  656. private Tuple<bool, T> CreateItemByName<T>(string path, string name)
  657. where T : BaseItem, new()
  658. {
  659. var isArtist = typeof(T) == typeof(MusicArtist);
  660. if (isArtist)
  661. {
  662. var existing = RootFolder.RecursiveChildren
  663. .OfType<T>()
  664. .FirstOrDefault(i => string.Equals(i.Name, name, StringComparison.OrdinalIgnoreCase));
  665. if (existing != null)
  666. {
  667. return new Tuple<bool, T>(false, existing);
  668. }
  669. }
  670. var fileInfo = new DirectoryInfo(path);
  671. var isNew = false;
  672. if (!fileInfo.Exists)
  673. {
  674. Directory.CreateDirectory(path);
  675. fileInfo = new DirectoryInfo(path);
  676. if (!fileInfo.Exists)
  677. {
  678. throw new IOException("Path not created: " + path);
  679. }
  680. isNew = true;
  681. }
  682. var type = typeof(T);
  683. var id = path.GetMBId(type);
  684. var item = isNew ? null : RetrieveItem(id) as T;
  685. if (item == null)
  686. {
  687. item = new T
  688. {
  689. Name = name,
  690. Id = id,
  691. DateCreated = _fileSystem.GetCreationTimeUtc(fileInfo),
  692. DateModified = _fileSystem.GetLastWriteTimeUtc(fileInfo),
  693. Path = path
  694. };
  695. isNew = true;
  696. }
  697. if (isArtist)
  698. {
  699. (item as MusicArtist).IsAccessedByName = true;
  700. }
  701. return new Tuple<bool, T>(isNew, item);
  702. }
  703. /// <summary>
  704. /// Validate and refresh the People sub-set of the IBN.
  705. /// The items are stored in the db but not loaded into memory until actually requested by an operation.
  706. /// </summary>
  707. /// <param name="cancellationToken">The cancellation token.</param>
  708. /// <param name="progress">The progress.</param>
  709. /// <returns>Task.</returns>
  710. public Task ValidatePeople(CancellationToken cancellationToken, IProgress<double> progress)
  711. {
  712. return new PeopleValidator(this, _logger).ValidatePeople(cancellationToken, progress);
  713. }
  714. /// <summary>
  715. /// Validates the artists.
  716. /// </summary>
  717. /// <param name="cancellationToken">The cancellation token.</param>
  718. /// <param name="progress">The progress.</param>
  719. /// <returns>Task.</returns>
  720. public Task ValidateArtists(CancellationToken cancellationToken, IProgress<double> progress)
  721. {
  722. return new ArtistsValidator(this, _userManager, _logger).Run(progress, cancellationToken);
  723. }
  724. /// <summary>
  725. /// Validates the music genres.
  726. /// </summary>
  727. /// <param name="cancellationToken">The cancellation token.</param>
  728. /// <param name="progress">The progress.</param>
  729. /// <returns>Task.</returns>
  730. public Task ValidateMusicGenres(CancellationToken cancellationToken, IProgress<double> progress)
  731. {
  732. return new MusicGenresValidator(this, _userManager, _logger).Run(progress, cancellationToken);
  733. }
  734. /// <summary>
  735. /// Validates the game genres.
  736. /// </summary>
  737. /// <param name="cancellationToken">The cancellation token.</param>
  738. /// <param name="progress">The progress.</param>
  739. /// <returns>Task.</returns>
  740. public Task ValidateGameGenres(CancellationToken cancellationToken, IProgress<double> progress)
  741. {
  742. return new GameGenresValidator(this, _userManager, _logger).Run(progress, cancellationToken);
  743. }
  744. /// <summary>
  745. /// Validates the studios.
  746. /// </summary>
  747. /// <param name="cancellationToken">The cancellation token.</param>
  748. /// <param name="progress">The progress.</param>
  749. /// <returns>Task.</returns>
  750. public Task ValidateStudios(CancellationToken cancellationToken, IProgress<double> progress)
  751. {
  752. return new StudiosValidator(this, _userManager, _logger).Run(progress, cancellationToken);
  753. }
  754. /// <summary>
  755. /// Validates the genres.
  756. /// </summary>
  757. /// <param name="cancellationToken">The cancellation token.</param>
  758. /// <param name="progress">The progress.</param>
  759. /// <returns>Task.</returns>
  760. public Task ValidateGenres(CancellationToken cancellationToken, IProgress<double> progress)
  761. {
  762. return new GenresValidator(this, _userManager, _logger).Run(progress, cancellationToken);
  763. }
  764. /// <summary>
  765. /// Reloads the root media folder
  766. /// </summary>
  767. /// <param name="progress">The progress.</param>
  768. /// <param name="cancellationToken">The cancellation token.</param>
  769. /// <returns>Task.</returns>
  770. public Task ValidateMediaLibrary(IProgress<double> progress, CancellationToken cancellationToken)
  771. {
  772. // Just run the scheduled task so that the user can see it
  773. _taskManager.CancelIfRunningAndQueue<RefreshMediaLibraryTask>();
  774. return Task.FromResult(true);
  775. }
  776. /// <summary>
  777. /// Queues the library scan.
  778. /// </summary>
  779. public void QueueLibraryScan()
  780. {
  781. // Just run the scheduled task so that the user can see it
  782. _taskManager.QueueScheduledTask<RefreshMediaLibraryTask>();
  783. }
  784. /// <summary>
  785. /// Validates the media library internal.
  786. /// </summary>
  787. /// <param name="progress">The progress.</param>
  788. /// <param name="cancellationToken">The cancellation token.</param>
  789. /// <returns>Task.</returns>
  790. public async Task ValidateMediaLibraryInternal(IProgress<double> progress, CancellationToken cancellationToken)
  791. {
  792. _libraryMonitorFactory().Stop();
  793. try
  794. {
  795. await PerformLibraryValidation(progress, cancellationToken).ConfigureAwait(false);
  796. }
  797. finally
  798. {
  799. _libraryMonitorFactory().Start();
  800. }
  801. }
  802. private async Task PerformLibraryValidation(IProgress<double> progress, CancellationToken cancellationToken)
  803. {
  804. _logger.Info("Validating media library");
  805. await RootFolder.RefreshMetadata(cancellationToken).ConfigureAwait(false);
  806. progress.Report(.5);
  807. // Start by just validating the children of the root, but go no further
  808. await RootFolder.ValidateChildren(new Progress<double>(), cancellationToken, new MetadataRefreshOptions(), recursive: false);
  809. progress.Report(1);
  810. foreach (var folder in _userManager.Users.Select(u => u.RootFolder).Distinct())
  811. {
  812. await ValidateCollectionFolders(folder, cancellationToken).ConfigureAwait(false);
  813. }
  814. progress.Report(2);
  815. var innerProgress = new ActionableProgress<double>();
  816. innerProgress.RegisterAction(pct => progress.Report(2 + pct * .13));
  817. innerProgress = new ActionableProgress<double>();
  818. innerProgress.RegisterAction(pct => progress.Report(2 + pct * .73));
  819. // Now validate the entire media library
  820. await RootFolder.ValidateChildren(innerProgress, cancellationToken, new MetadataRefreshOptions(), recursive: true).ConfigureAwait(false);
  821. progress.Report(75);
  822. innerProgress = new ActionableProgress<double>();
  823. innerProgress.RegisterAction(pct => progress.Report(75 + pct * .25));
  824. // Run post-scan tasks
  825. await RunPostScanTasks(innerProgress, cancellationToken).ConfigureAwait(false);
  826. progress.Report(100);
  827. // Bad practice, i know. But we keep a lot in memory, unfortunately.
  828. GC.Collect(2, GCCollectionMode.Forced, true);
  829. GC.Collect(2, GCCollectionMode.Forced, true);
  830. }
  831. /// <summary>
  832. /// Runs the post scan tasks.
  833. /// </summary>
  834. /// <param name="progress">The progress.</param>
  835. /// <param name="cancellationToken">The cancellation token.</param>
  836. /// <returns>Task.</returns>
  837. private async Task RunPostScanTasks(IProgress<double> progress, CancellationToken cancellationToken)
  838. {
  839. var tasks = PostscanTasks.ToList();
  840. var numComplete = 0;
  841. var numTasks = tasks.Count;
  842. foreach (var task in tasks)
  843. {
  844. var innerProgress = new ActionableProgress<double>();
  845. // Prevent access to modified closure
  846. var currentNumComplete = numComplete;
  847. innerProgress.RegisterAction(pct =>
  848. {
  849. double innerPercent = (currentNumComplete * 100) + pct;
  850. innerPercent /= numTasks;
  851. progress.Report(innerPercent);
  852. });
  853. try
  854. {
  855. await task.Run(innerProgress, cancellationToken);
  856. }
  857. catch (OperationCanceledException)
  858. {
  859. _logger.Info("Post-scan task cancelled: {0}", task.GetType().Name);
  860. }
  861. catch (Exception ex)
  862. {
  863. _logger.ErrorException("Error running postscan task", ex);
  864. }
  865. numComplete++;
  866. double percent = numComplete;
  867. percent /= numTasks;
  868. progress.Report(percent * 100);
  869. }
  870. progress.Report(100);
  871. }
  872. /// <summary>
  873. /// Validates only the collection folders for a User and goes no further
  874. /// </summary>
  875. /// <param name="userRootFolder">The user root folder.</param>
  876. /// <param name="cancellationToken">The cancellation token.</param>
  877. /// <returns>Task.</returns>
  878. private async Task ValidateCollectionFolders(UserRootFolder userRootFolder, CancellationToken cancellationToken)
  879. {
  880. _logger.Info("Validating collection folders within {0}", userRootFolder.Path);
  881. await userRootFolder.RefreshMetadata(cancellationToken).ConfigureAwait(false);
  882. cancellationToken.ThrowIfCancellationRequested();
  883. await userRootFolder.ValidateChildren(new Progress<double>(), cancellationToken, new MetadataRefreshOptions(), recursive: false).ConfigureAwait(false);
  884. }
  885. /// <summary>
  886. /// Gets the default view.
  887. /// </summary>
  888. /// <returns>IEnumerable{VirtualFolderInfo}.</returns>
  889. public IEnumerable<VirtualFolderInfo> GetDefaultVirtualFolders()
  890. {
  891. return GetView(ConfigurationManager.ApplicationPaths.DefaultUserViewsPath);
  892. }
  893. /// <summary>
  894. /// Gets the view.
  895. /// </summary>
  896. /// <param name="user">The user.</param>
  897. /// <returns>IEnumerable{VirtualFolderInfo}.</returns>
  898. public IEnumerable<VirtualFolderInfo> GetVirtualFolders(User user)
  899. {
  900. return GetView(user.RootFolderPath);
  901. }
  902. /// <summary>
  903. /// Gets the view.
  904. /// </summary>
  905. /// <param name="path">The path.</param>
  906. /// <returns>IEnumerable{VirtualFolderInfo}.</returns>
  907. private IEnumerable<VirtualFolderInfo> GetView(string path)
  908. {
  909. return Directory.EnumerateDirectories(path, "*", SearchOption.TopDirectoryOnly)
  910. .Select(dir => new VirtualFolderInfo
  911. {
  912. Name = Path.GetFileName(dir),
  913. Locations = Directory.EnumerateFiles(dir, "*.mblink", SearchOption.TopDirectoryOnly)
  914. .Select(_fileSystem.ResolveShortcut)
  915. .OrderBy(i => i)
  916. .ToList(),
  917. CollectionType = GetCollectionType(dir)
  918. });
  919. }
  920. private string GetCollectionType(string path)
  921. {
  922. return new DirectoryInfo(path).EnumerateFiles("*.collection", SearchOption.TopDirectoryOnly)
  923. .Select(i => Path.GetFileNameWithoutExtension(i.FullName))
  924. .FirstOrDefault();
  925. }
  926. /// <summary>
  927. /// Gets the item by id.
  928. /// </summary>
  929. /// <param name="id">The id.</param>
  930. /// <returns>BaseItem.</returns>
  931. /// <exception cref="System.ArgumentNullException">id</exception>
  932. public BaseItem GetItemById(Guid id)
  933. {
  934. if (id == Guid.Empty)
  935. {
  936. throw new ArgumentNullException("id");
  937. }
  938. BaseItem item;
  939. if (LibraryItemsCache.TryGetValue(id, out item))
  940. {
  941. return item;
  942. }
  943. return RetrieveItem(id);
  944. }
  945. /// <summary>
  946. /// Gets the intros.
  947. /// </summary>
  948. /// <param name="item">The item.</param>
  949. /// <param name="user">The user.</param>
  950. /// <returns>IEnumerable{System.String}.</returns>
  951. public IEnumerable<Video> GetIntros(BaseItem item, User user)
  952. {
  953. return IntroProviders.SelectMany(i => i.GetIntros(item, user))
  954. .Select(ResolveIntro)
  955. .Where(i => i != null);
  956. }
  957. /// <summary>
  958. /// Gets all intro files.
  959. /// </summary>
  960. /// <returns>IEnumerable{System.String}.</returns>
  961. public IEnumerable<string> GetAllIntroFiles()
  962. {
  963. return IntroProviders.SelectMany(i => i.GetAllIntroFiles());
  964. }
  965. /// <summary>
  966. /// Resolves the intro.
  967. /// </summary>
  968. /// <param name="info">The info.</param>
  969. /// <returns>Video.</returns>
  970. private Video ResolveIntro(IntroInfo info)
  971. {
  972. Video video = null;
  973. if (info.ItemId.HasValue)
  974. {
  975. // Get an existing item by Id
  976. video = GetItemById(info.ItemId.Value) as Video;
  977. if (video == null)
  978. {
  979. _logger.Error("Unable to locate item with Id {0}.", info.ItemId.Value);
  980. }
  981. }
  982. else if (!string.IsNullOrEmpty(info.Path))
  983. {
  984. try
  985. {
  986. // Try to resolve the path into a video
  987. video = ResolvePath(_fileSystem.GetFileSystemInfo(info.Path)) as Video;
  988. if (video == null)
  989. {
  990. _logger.Error("Intro resolver returned null for {0}.", info.Path);
  991. }
  992. else
  993. {
  994. // Pull the saved db item that will include metadata
  995. var dbItem = GetItemById(video.Id) as Video;
  996. if (dbItem != null)
  997. {
  998. video = dbItem;
  999. }
  1000. }
  1001. }
  1002. catch (Exception ex)
  1003. {
  1004. _logger.ErrorException("Error resolving path {0}.", ex, info.Path);
  1005. }
  1006. }
  1007. else
  1008. {
  1009. _logger.Error("IntroProvider returned an IntroInfo with null Path and ItemId.");
  1010. }
  1011. return video;
  1012. }
  1013. /// <summary>
  1014. /// Sorts the specified sort by.
  1015. /// </summary>
  1016. /// <param name="items">The items.</param>
  1017. /// <param name="user">The user.</param>
  1018. /// <param name="sortBy">The sort by.</param>
  1019. /// <param name="sortOrder">The sort order.</param>
  1020. /// <returns>IEnumerable{BaseItem}.</returns>
  1021. public IEnumerable<BaseItem> Sort(IEnumerable<BaseItem> items, User user, IEnumerable<string> sortBy, SortOrder sortOrder)
  1022. {
  1023. var isFirst = true;
  1024. IOrderedEnumerable<BaseItem> orderedItems = null;
  1025. foreach (var orderBy in sortBy.Select(o => GetComparer(o, user)).Where(c => c != null))
  1026. {
  1027. if (isFirst)
  1028. {
  1029. orderedItems = sortOrder == SortOrder.Descending ? items.OrderByDescending(i => i, orderBy) : items.OrderBy(i => i, orderBy);
  1030. }
  1031. else
  1032. {
  1033. orderedItems = sortOrder == SortOrder.Descending ? orderedItems.ThenByDescending(i => i, orderBy) : orderedItems.ThenBy(i => i, orderBy);
  1034. }
  1035. isFirst = false;
  1036. }
  1037. return orderedItems ?? items;
  1038. }
  1039. /// <summary>
  1040. /// Gets the comparer.
  1041. /// </summary>
  1042. /// <param name="name">The name.</param>
  1043. /// <param name="user">The user.</param>
  1044. /// <returns>IBaseItemComparer.</returns>
  1045. private IBaseItemComparer GetComparer(string name, User user)
  1046. {
  1047. var comparer = Comparers.FirstOrDefault(c => string.Equals(name, c.Name, StringComparison.OrdinalIgnoreCase));
  1048. if (comparer != null)
  1049. {
  1050. // If it requires a user, create a new one, and assign the user
  1051. if (comparer is IUserBaseItemComparer)
  1052. {
  1053. var userComparer = (IUserBaseItemComparer)Activator.CreateInstance(comparer.GetType());
  1054. userComparer.User = user;
  1055. userComparer.UserManager = _userManager;
  1056. userComparer.UserDataRepository = _userDataRepository;
  1057. return userComparer;
  1058. }
  1059. }
  1060. return comparer;
  1061. }
  1062. /// <summary>
  1063. /// Creates the item.
  1064. /// </summary>
  1065. /// <param name="item">The item.</param>
  1066. /// <param name="cancellationToken">The cancellation token.</param>
  1067. /// <returns>Task.</returns>
  1068. public Task CreateItem(BaseItem item, CancellationToken cancellationToken)
  1069. {
  1070. return CreateItems(new[] { item }, cancellationToken);
  1071. }
  1072. /// <summary>
  1073. /// Creates the items.
  1074. /// </summary>
  1075. /// <param name="items">The items.</param>
  1076. /// <param name="cancellationToken">The cancellation token.</param>
  1077. /// <returns>Task.</returns>
  1078. public async Task CreateItems(IEnumerable<BaseItem> items, CancellationToken cancellationToken)
  1079. {
  1080. var list = items.ToList();
  1081. await ItemRepository.SaveItems(list, cancellationToken).ConfigureAwait(false);
  1082. foreach (var item in list)
  1083. {
  1084. UpdateItemInLibraryCache(item);
  1085. }
  1086. UpdateCollectionFolders();
  1087. if (ItemAdded != null)
  1088. {
  1089. foreach (var item in list)
  1090. {
  1091. try
  1092. {
  1093. ItemAdded(this, new ItemChangeEventArgs { Item = item });
  1094. }
  1095. catch (Exception ex)
  1096. {
  1097. _logger.ErrorException("Error in ItemAdded event handler", ex);
  1098. }
  1099. }
  1100. }
  1101. }
  1102. /// <summary>
  1103. /// Updates the item.
  1104. /// </summary>
  1105. /// <param name="item">The item.</param>
  1106. /// <param name="updateReason">The update reason.</param>
  1107. /// <param name="cancellationToken">The cancellation token.</param>
  1108. /// <returns>Task.</returns>
  1109. public async Task UpdateItem(BaseItem item, ItemUpdateType updateReason, CancellationToken cancellationToken)
  1110. {
  1111. if (item.LocationType == LocationType.FileSystem)
  1112. {
  1113. await _providerManagerFactory().SaveMetadata(item, updateReason).ConfigureAwait(false);
  1114. }
  1115. item.DateLastSaved = DateTime.UtcNow;
  1116. _logger.Debug("Saving {0} to database.", item.Path ?? item.Name);
  1117. await ItemRepository.SaveItem(item, cancellationToken).ConfigureAwait(false);
  1118. UpdateItemInLibraryCache(item);
  1119. if (ItemUpdated != null)
  1120. {
  1121. try
  1122. {
  1123. ItemUpdated(this, new ItemChangeEventArgs
  1124. {
  1125. Item = item,
  1126. UpdateReason = updateReason
  1127. });
  1128. }
  1129. catch (Exception ex)
  1130. {
  1131. _logger.ErrorException("Error in ItemUpdated event handler", ex);
  1132. }
  1133. }
  1134. }
  1135. /// <summary>
  1136. /// Reports the item removed.
  1137. /// </summary>
  1138. /// <param name="item">The item.</param>
  1139. public void ReportItemRemoved(BaseItem item)
  1140. {
  1141. UpdateCollectionFolders();
  1142. if (ItemRemoved != null)
  1143. {
  1144. try
  1145. {
  1146. ItemRemoved(this, new ItemChangeEventArgs { Item = item });
  1147. }
  1148. catch (Exception ex)
  1149. {
  1150. _logger.ErrorException("Error in ItemRemoved event handler", ex);
  1151. }
  1152. }
  1153. }
  1154. private void UpdateCollectionFolders()
  1155. {
  1156. foreach (var folder in _userManager.Users.SelectMany(i => i.RootFolder.Children).OfType<CollectionFolder>().ToList())
  1157. {
  1158. folder.ResetDynamicChildren();
  1159. }
  1160. }
  1161. /// <summary>
  1162. /// Retrieves the item.
  1163. /// </summary>
  1164. /// <param name="id">The id.</param>
  1165. /// <returns>BaseItem.</returns>
  1166. public BaseItem RetrieveItem(Guid id)
  1167. {
  1168. return ItemRepository.RetrieveItem(id);
  1169. }
  1170. /// <summary>
  1171. /// Finds the type of the collection.
  1172. /// </summary>
  1173. /// <param name="item">The item.</param>
  1174. /// <returns>System.String.</returns>
  1175. public string FindCollectionType(BaseItem item)
  1176. {
  1177. while (!(item.Parent is AggregateFolder) && item.Parent != null)
  1178. {
  1179. item = item.Parent;
  1180. }
  1181. if (item == null)
  1182. {
  1183. return null;
  1184. }
  1185. var collectionTypes = _userManager.Users
  1186. .Select(i => i.RootFolder)
  1187. .Distinct()
  1188. .SelectMany(i => i.Children)
  1189. .OfType<CollectionFolder>()
  1190. .Where(i =>
  1191. {
  1192. var locationType = i.LocationType;
  1193. if (locationType == LocationType.Remote || locationType == LocationType.Virtual)
  1194. {
  1195. return false;
  1196. }
  1197. if (string.Equals(i.Path, item.Path, StringComparison.OrdinalIgnoreCase))
  1198. {
  1199. return true;
  1200. }
  1201. return i.PhysicalLocations.Contains(item.Path);
  1202. })
  1203. .Select(i => i.CollectionType)
  1204. .Where(i => !string.IsNullOrEmpty(i))
  1205. .Distinct()
  1206. .ToList();
  1207. return collectionTypes.Count == 1 ? collectionTypes[0] : null;
  1208. }
  1209. public IEnumerable<string> GetAllArtists()
  1210. {
  1211. return GetAllArtists(RootFolder.RecursiveChildren);
  1212. }
  1213. public IEnumerable<string> GetAllArtists(IEnumerable<BaseItem> items)
  1214. {
  1215. return items
  1216. .OfType<Audio>()
  1217. .SelectMany(i =>
  1218. {
  1219. var list = new List<string>();
  1220. if (!string.IsNullOrEmpty(i.AlbumArtist))
  1221. {
  1222. list.Add(i.AlbumArtist);
  1223. }
  1224. list.AddRange(i.Artists);
  1225. return list;
  1226. })
  1227. .Distinct(StringComparer.OrdinalIgnoreCase);
  1228. }
  1229. }
  1230. }