LibraryManager.cs 54 KB

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