LibraryManager.cs 56 KB

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