LibraryManager.cs 56 KB

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