LibraryManager.cs 53 KB

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