LibraryManager.cs 51 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.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 Distinct 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 dictionary = new ConcurrentDictionary<Guid, BaseItem>();
  316. foreach (var item in items)
  317. {
  318. dictionary[item.Id] = item;
  319. }
  320. return dictionary;
  321. }
  322. /// <summary>
  323. /// Updates the item in library cache.
  324. /// </summary>
  325. /// <param name="item">The item.</param>
  326. private void UpdateItemInLibraryCache(BaseItem item)
  327. {
  328. if (!(item is IItemByName))
  329. {
  330. LibraryItemsCache.AddOrUpdate(item.Id, item, delegate { return item; });
  331. }
  332. }
  333. /// <summary>
  334. /// Resolves the item.
  335. /// </summary>
  336. /// <param name="args">The args.</param>
  337. /// <returns>BaseItem.</returns>
  338. public BaseItem ResolveItem(ItemResolveArgs args)
  339. {
  340. var item = EntityResolvers.Select(r =>
  341. {
  342. try
  343. {
  344. return r.ResolvePath(args);
  345. }
  346. catch (Exception ex)
  347. {
  348. _logger.ErrorException("Error in {0} resolving {1}", ex, r.GetType().Name, args.Path);
  349. return null;
  350. }
  351. }).FirstOrDefault(i => i != null);
  352. if (item != null)
  353. {
  354. ResolverHelper.SetInitialItemValues(item, args);
  355. // Now handle the issue with posibly having the same item referenced from multiple physical
  356. // places within the library. Be sure we always end up with just one instance.
  357. if (item is IByReferenceItem)
  358. {
  359. item = GetOrAddByReferenceItem(item);
  360. }
  361. }
  362. return item;
  363. }
  364. /// <summary>
  365. /// Ensure supplied item has only one instance throughout
  366. /// </summary>
  367. /// <param name="item">The item.</param>
  368. /// <returns>The proper instance to the item</returns>
  369. public BaseItem GetOrAddByReferenceItem(BaseItem item)
  370. {
  371. // Add this item to our list if not there already
  372. if (!ByReferenceItems.TryAdd(item.Id, item))
  373. {
  374. // Already there - return the existing reference
  375. item = ByReferenceItems[item.Id];
  376. }
  377. return item;
  378. }
  379. /// <summary>
  380. /// Resolves a path into a BaseItem
  381. /// </summary>
  382. /// <param name="fileInfo">The file info.</param>
  383. /// <param name="parent">The parent.</param>
  384. /// <returns>BaseItem.</returns>
  385. /// <exception cref="System.ArgumentNullException"></exception>
  386. public BaseItem ResolvePath(FileSystemInfo fileInfo, Folder parent = null)
  387. {
  388. if (fileInfo == null)
  389. {
  390. throw new ArgumentNullException("fileInfo");
  391. }
  392. var args = new ItemResolveArgs(ConfigurationManager.ApplicationPaths, this)
  393. {
  394. Parent = parent,
  395. Path = fileInfo.FullName,
  396. FileInfo = fileInfo
  397. };
  398. // Return null if ignore rules deem that we should do so
  399. if (EntityResolutionIgnoreRules.Any(r => r.ShouldIgnore(args)))
  400. {
  401. return null;
  402. }
  403. // Gather child folder and files
  404. if (args.IsDirectory)
  405. {
  406. var isPhysicalRoot = args.IsPhysicalRoot;
  407. // When resolving the root, we need it's grandchildren (children of user views)
  408. var flattenFolderDepth = isPhysicalRoot ? 2 : 0;
  409. args.FileSystemDictionary = FileData.GetFilteredFileSystemEntries(args.Path, _logger, args, flattenFolderDepth: flattenFolderDepth, resolveShortcuts: isPhysicalRoot || args.IsVf);
  410. // Need to remove subpaths that may have been resolved from shortcuts
  411. // Example: if \\server\movies exists, then strip out \\server\movies\action
  412. if (isPhysicalRoot)
  413. {
  414. var paths = args.FileSystemDictionary.Keys.ToList();
  415. foreach (var subPath in paths
  416. .Where(subPath => !subPath.EndsWith(":\\", StringComparison.OrdinalIgnoreCase) && paths.Any(i => subPath.StartsWith(i.TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase))))
  417. {
  418. _logger.Info("Ignoring duplicate path: {0}", subPath);
  419. args.FileSystemDictionary.Remove(subPath);
  420. }
  421. }
  422. }
  423. // Check to see if we should resolve based on our contents
  424. if (args.IsDirectory && !ShouldResolvePathContents(args))
  425. {
  426. return null;
  427. }
  428. return ResolveItem(args);
  429. }
  430. /// <summary>
  431. /// Determines whether a path should be ignored based on its contents - called after the contents have been read
  432. /// </summary>
  433. /// <param name="args">The args.</param>
  434. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  435. private static bool ShouldResolvePathContents(ItemResolveArgs args)
  436. {
  437. // Ignore any folders containing a file called .ignore
  438. return !args.ContainsFileSystemEntryByName(".ignore");
  439. }
  440. /// <summary>
  441. /// Resolves a set of files into a list of BaseItem
  442. /// </summary>
  443. /// <typeparam name="T"></typeparam>
  444. /// <param name="files">The files.</param>
  445. /// <param name="parent">The parent.</param>
  446. /// <returns>List{``0}.</returns>
  447. public List<T> ResolvePaths<T>(IEnumerable<FileSystemInfo> files, Folder parent)
  448. where T : BaseItem
  449. {
  450. var list = new List<T>();
  451. Parallel.ForEach(files, f =>
  452. {
  453. try
  454. {
  455. if (f.Exists)
  456. {
  457. var item = ResolvePath(f, parent) as T;
  458. if (item != null)
  459. {
  460. lock (list)
  461. {
  462. list.Add(item);
  463. }
  464. }
  465. }
  466. }
  467. catch (Exception ex)
  468. {
  469. _logger.ErrorException("Error resolving path {0}", ex, f.FullName);
  470. }
  471. });
  472. return list;
  473. }
  474. /// <summary>
  475. /// Creates the root media folder
  476. /// </summary>
  477. /// <returns>AggregateFolder.</returns>
  478. /// <exception cref="System.InvalidOperationException">Cannot create the root folder until plugins have loaded</exception>
  479. public AggregateFolder CreateRootFolder()
  480. {
  481. var rootFolderPath = ConfigurationManager.ApplicationPaths.RootFolderPath;
  482. if (!Directory.Exists(rootFolderPath))
  483. {
  484. Directory.CreateDirectory(rootFolderPath);
  485. }
  486. var rootFolder = RetrieveItem(rootFolderPath.GetMBId(typeof(AggregateFolder))) as AggregateFolder ?? (AggregateFolder)ResolvePath(new DirectoryInfo(rootFolderPath));
  487. // Add in the plug-in folders
  488. foreach (var child in PluginFolderCreators)
  489. {
  490. var folder = child.GetFolder();
  491. if (folder.Id == Guid.Empty)
  492. {
  493. folder.Id = (folder.Path ?? folder.GetType().Name).GetMBId(folder.GetType());
  494. }
  495. rootFolder.AddVirtualChild(folder);
  496. }
  497. return rootFolder;
  498. }
  499. /// <summary>
  500. /// Gets the user root folder.
  501. /// </summary>
  502. /// <param name="userRootPath">The user root path.</param>
  503. /// <returns>UserRootFolder.</returns>
  504. public UserRootFolder GetUserRootFolder(string userRootPath)
  505. {
  506. return _userRootFolders.GetOrAdd(userRootPath, key => RetrieveItem(userRootPath.GetMBId(typeof(UserRootFolder))) as UserRootFolder ??
  507. (UserRootFolder)ResolvePath(new DirectoryInfo(userRootPath)));
  508. }
  509. public Person GetPersonSync(string name)
  510. {
  511. return GetItemByName<Person>(ConfigurationManager.ApplicationPaths.PeoplePath, name);
  512. }
  513. /// <summary>
  514. /// Gets a Person
  515. /// </summary>
  516. /// <param name="name">The name.</param>
  517. /// <returns>Task{Person}.</returns>
  518. public Person GetPerson(string name)
  519. {
  520. return GetItemByName<Person>(ConfigurationManager.ApplicationPaths.PeoplePath, name);
  521. }
  522. /// <summary>
  523. /// Gets a Studio
  524. /// </summary>
  525. /// <param name="name">The name.</param>
  526. /// <returns>Task{Studio}.</returns>
  527. public Studio GetStudio(string name)
  528. {
  529. return GetItemByName<Studio>(ConfigurationManager.ApplicationPaths.StudioPath, name);
  530. }
  531. /// <summary>
  532. /// Gets a Genre
  533. /// </summary>
  534. /// <param name="name">The name.</param>
  535. /// <returns>Task{Genre}.</returns>
  536. public Genre GetGenre(string name)
  537. {
  538. return GetItemByName<Genre>(ConfigurationManager.ApplicationPaths.GenrePath, name);
  539. }
  540. /// <summary>
  541. /// Gets the genre.
  542. /// </summary>
  543. /// <param name="name">The name.</param>
  544. /// <returns>Task{MusicGenre}.</returns>
  545. public MusicGenre GetMusicGenre(string name)
  546. {
  547. return GetItemByName<MusicGenre>(ConfigurationManager.ApplicationPaths.MusicGenrePath, name);
  548. }
  549. /// <summary>
  550. /// Gets the game genre.
  551. /// </summary>
  552. /// <param name="name">The name.</param>
  553. /// <returns>Task{GameGenre}.</returns>
  554. public GameGenre GetGameGenre(string name)
  555. {
  556. return GetItemByName<GameGenre>(ConfigurationManager.ApplicationPaths.GameGenrePath, name);
  557. }
  558. /// <summary>
  559. /// Gets a Genre
  560. /// </summary>
  561. /// <param name="name">The name.</param>
  562. /// <returns>Task{Genre}.</returns>
  563. public Artist GetArtist(string name)
  564. {
  565. return GetItemByName<Artist>(ConfigurationManager.ApplicationPaths.ArtistsPath, name);
  566. }
  567. /// <summary>
  568. /// The us culture
  569. /// </summary>
  570. private static readonly CultureInfo UsCulture = new CultureInfo("en-US");
  571. /// <summary>
  572. /// Gets a Year
  573. /// </summary>
  574. /// <param name="value">The value.</param>
  575. /// <returns>Task{Year}.</returns>
  576. /// <exception cref="System.ArgumentOutOfRangeException"></exception>
  577. public Year GetYear(int value)
  578. {
  579. if (value <= 0)
  580. {
  581. throw new ArgumentOutOfRangeException();
  582. }
  583. return GetItemByName<Year>(ConfigurationManager.ApplicationPaths.YearPath, value.ToString(UsCulture));
  584. }
  585. /// <summary>
  586. /// The images by name item cache
  587. /// </summary>
  588. private readonly ConcurrentDictionary<string, BaseItem> _itemsByName = new ConcurrentDictionary<string, BaseItem>(StringComparer.OrdinalIgnoreCase);
  589. private T GetItemByName<T>(string path, string name)
  590. where T : BaseItem, new()
  591. {
  592. if (string.IsNullOrEmpty(path))
  593. {
  594. throw new ArgumentNullException();
  595. }
  596. if (string.IsNullOrEmpty(name))
  597. {
  598. throw new ArgumentNullException();
  599. }
  600. var validFilename = FileSystem.GetValidFilename(name);
  601. var key = Path.Combine(path, validFilename);
  602. BaseItem obj;
  603. if (!_itemsByName.TryGetValue(key, out obj))
  604. {
  605. var tuple = CreateItemByName<T>(key, name);
  606. obj = tuple.Item2;
  607. _itemsByName.AddOrUpdate(key, obj, (keyName, oldValue) => obj);
  608. }
  609. return obj as T;
  610. }
  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="refreshMetadata">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 refreshMetadata = 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 validFilename = FileSystem.GetValidFilename(name);
  635. var key = Path.Combine(path, validFilename);
  636. BaseItem obj;
  637. if (!_itemsByName.TryGetValue(key, out obj))
  638. {
  639. var tuple = CreateItemByName<T>(key, name);
  640. obj = tuple.Item2;
  641. _itemsByName.AddOrUpdate(key, obj, (keyName, oldValue) => obj);
  642. try
  643. {
  644. await obj.RefreshMetadata(cancellationToken, tuple.Item1, allowSlowProviders: allowSlowProviders).ConfigureAwait(false);
  645. }
  646. catch (OperationCanceledException)
  647. {
  648. BaseItem removed;
  649. _itemsByName.TryRemove(key, out removed);
  650. throw;
  651. }
  652. }
  653. else if (refreshMetadata)
  654. {
  655. await obj.RefreshMetadata(cancellationToken, false, allowSlowProviders: allowSlowProviders).ConfigureAwait(false);
  656. }
  657. return obj as T;
  658. }
  659. /// <summary>
  660. /// Creates an IBN item based on a given path
  661. /// </summary>
  662. /// <typeparam name="T"></typeparam>
  663. /// <param name="path">The path.</param>
  664. /// <param name="name">The name.</param>
  665. /// <returns>Task{``0}.</returns>
  666. /// <exception cref="System.IO.IOException">Path not created: + path</exception>
  667. private Tuple<bool, T> CreateItemByName<T>(string path, string name)
  668. where T : BaseItem, new()
  669. {
  670. var fileInfo = new DirectoryInfo(path);
  671. var isNew = false;
  672. if (!fileInfo.Exists)
  673. {
  674. Directory.CreateDirectory(path);
  675. fileInfo = new DirectoryInfo(path);
  676. if (!fileInfo.Exists)
  677. {
  678. throw new IOException("Path not created: " + path);
  679. }
  680. isNew = true;
  681. }
  682. var type = typeof(T);
  683. var id = path.GetMBId(type);
  684. var item = RetrieveItem(id) as T;
  685. if (item == null)
  686. {
  687. item = new T
  688. {
  689. Name = name,
  690. Id = id,
  691. DateCreated = fileInfo.CreationTimeUtc,
  692. DateModified = fileInfo.LastWriteTimeUtc,
  693. Path = path
  694. };
  695. isNew = true;
  696. }
  697. // Set this now so we don't cause additional file system access during provider executions
  698. item.ResetResolveArgs(fileInfo);
  699. return new Tuple<bool, T>(isNew, item);
  700. }
  701. /// <summary>
  702. /// Validate and refresh the People sub-set of the IBN.
  703. /// The items are stored in the db but not loaded into memory until actually requested by an operation.
  704. /// </summary>
  705. /// <param name="cancellationToken">The cancellation token.</param>
  706. /// <param name="progress">The progress.</param>
  707. /// <returns>Task.</returns>
  708. public async Task ValidatePeople(CancellationToken cancellationToken, IProgress<double> progress)
  709. {
  710. var people = RootFolder.RecursiveChildren
  711. .SelectMany(c => c.People)
  712. .DistinctBy(p => p.Name, StringComparer.OrdinalIgnoreCase)
  713. .ToList();
  714. var numComplete = 0;
  715. foreach (var person in people)
  716. {
  717. cancellationToken.ThrowIfCancellationRequested();
  718. try
  719. {
  720. var item = GetPerson(person.Name);
  721. await item.RefreshMetadata(cancellationToken).ConfigureAwait(false);
  722. }
  723. catch (IOException ex)
  724. {
  725. _logger.ErrorException("Error validating IBN entry {0}", ex, person.Name);
  726. }
  727. // Update progress
  728. numComplete++;
  729. double percent = numComplete;
  730. percent /= people.Count;
  731. progress.Report(100 * percent);
  732. }
  733. progress.Report(100);
  734. _logger.Info("People validation complete");
  735. // Bad practice, i know. But we keep a lot in memory, unfortunately.
  736. GC.Collect(2, GCCollectionMode.Forced, true);
  737. GC.Collect(2, GCCollectionMode.Forced, true);
  738. }
  739. /// <summary>
  740. /// Validates the artists.
  741. /// </summary>
  742. /// <param name="cancellationToken">The cancellation token.</param>
  743. /// <param name="progress">The progress.</param>
  744. /// <returns>Task.</returns>
  745. public Task ValidateArtists(CancellationToken cancellationToken, IProgress<double> progress)
  746. {
  747. return new ArtistsValidator(this, _userManager, _logger).Run(progress, cancellationToken);
  748. }
  749. /// <summary>
  750. /// Validates the music genres.
  751. /// </summary>
  752. /// <param name="cancellationToken">The cancellation token.</param>
  753. /// <param name="progress">The progress.</param>
  754. /// <returns>Task.</returns>
  755. public Task ValidateMusicGenres(CancellationToken cancellationToken, IProgress<double> progress)
  756. {
  757. return new MusicGenresValidator(this, _userManager, _logger).Run(progress, cancellationToken);
  758. }
  759. /// <summary>
  760. /// Validates the game genres.
  761. /// </summary>
  762. /// <param name="cancellationToken">The cancellation token.</param>
  763. /// <param name="progress">The progress.</param>
  764. /// <returns>Task.</returns>
  765. public Task ValidateGameGenres(CancellationToken cancellationToken, IProgress<double> progress)
  766. {
  767. return new GameGenresValidator(this, _userManager, _logger).Run(progress, cancellationToken);
  768. }
  769. /// <summary>
  770. /// Validates the studios.
  771. /// </summary>
  772. /// <param name="cancellationToken">The cancellation token.</param>
  773. /// <param name="progress">The progress.</param>
  774. /// <returns>Task.</returns>
  775. public Task ValidateStudios(CancellationToken cancellationToken, IProgress<double> progress)
  776. {
  777. return new StudiosValidator(this, _userManager, _logger).Run(progress, cancellationToken);
  778. }
  779. /// <summary>
  780. /// Validates the genres.
  781. /// </summary>
  782. /// <param name="cancellationToken">The cancellation token.</param>
  783. /// <param name="progress">The progress.</param>
  784. /// <returns>Task.</returns>
  785. public Task ValidateGenres(CancellationToken cancellationToken, IProgress<double> progress)
  786. {
  787. return new GenresValidator(this, _userManager, _logger).Run(progress, cancellationToken);
  788. }
  789. /// <summary>
  790. /// Reloads the root media folder
  791. /// </summary>
  792. /// <param name="progress">The progress.</param>
  793. /// <param name="cancellationToken">The cancellation token.</param>
  794. /// <returns>Task.</returns>
  795. public Task ValidateMediaLibrary(IProgress<double> progress, CancellationToken cancellationToken)
  796. {
  797. // Just run the scheduled task so that the user can see it
  798. _taskManager.CancelIfRunningAndQueue<RefreshMediaLibraryTask>();
  799. return Task.FromResult(true);
  800. }
  801. /// <summary>
  802. /// Validates the media library internal.
  803. /// </summary>
  804. /// <param name="progress">The progress.</param>
  805. /// <param name="cancellationToken">The cancellation token.</param>
  806. /// <returns>Task.</returns>
  807. public async Task ValidateMediaLibraryInternal(IProgress<double> progress, CancellationToken cancellationToken)
  808. {
  809. _logger.Info("Validating media library");
  810. await RootFolder.RefreshMetadata(cancellationToken).ConfigureAwait(false);
  811. progress.Report(.5);
  812. // Start by just validating the children of the root, but go no further
  813. await RootFolder.ValidateChildren(new Progress<double>(), cancellationToken, recursive: false);
  814. progress.Report(1);
  815. foreach (var folder in _userManager.Users.Select(u => u.RootFolder).Distinct())
  816. {
  817. await ValidateCollectionFolders(folder, cancellationToken).ConfigureAwait(false);
  818. }
  819. progress.Report(2);
  820. // Run prescan tasks
  821. await RunPrescanTasks(progress, cancellationToken).ConfigureAwait(false);
  822. progress.Report(15);
  823. var innerProgress = new ActionableProgress<double>();
  824. innerProgress.RegisterAction(pct => progress.Report(15 + pct * .6));
  825. // Now validate the entire media library
  826. await RootFolder.ValidateChildren(innerProgress, cancellationToken, recursive: true).ConfigureAwait(false);
  827. progress.Report(75);
  828. // Run post-scan tasks
  829. await RunPostScanTasks(progress, cancellationToken).ConfigureAwait(false);
  830. progress.Report(100);
  831. // Bad practice, i know. But we keep a lot in memory, unfortunately.
  832. GC.Collect(2, GCCollectionMode.Forced, true);
  833. GC.Collect(2, GCCollectionMode.Forced, true);
  834. }
  835. /// <summary>
  836. /// Runs the prescan tasks.
  837. /// </summary>
  838. /// <param name="progress">The progress.</param>
  839. /// <param name="cancellationToken">The cancellation token.</param>
  840. /// <returns>Task.</returns>
  841. private async Task RunPrescanTasks(IProgress<double> progress, CancellationToken cancellationToken)
  842. {
  843. var prescanTasks = PrescanTasks.ToList();
  844. var progressDictionary = new Dictionary<ILibraryPrescanTask, double>();
  845. var tasks = prescanTasks.Select(i => Task.Run(async () =>
  846. {
  847. var innerProgress = new ActionableProgress<double>();
  848. innerProgress.RegisterAction(pct =>
  849. {
  850. lock (progressDictionary)
  851. {
  852. progressDictionary[i] = pct;
  853. double percent = progressDictionary.Values.Sum();
  854. percent /= prescanTasks.Count;
  855. progress.Report(2 + percent * .13);
  856. }
  857. });
  858. try
  859. {
  860. await i.Run(innerProgress, cancellationToken);
  861. }
  862. catch (OperationCanceledException)
  863. {
  864. _logger.Info("Pre-scan task cancelled: {0}", i.GetType().Name);
  865. }
  866. catch (Exception ex)
  867. {
  868. _logger.ErrorException("Error running prescan task", ex);
  869. }
  870. }));
  871. await Task.WhenAll(tasks).ConfigureAwait(false);
  872. }
  873. /// <summary>
  874. /// Runs the post scan tasks.
  875. /// </summary>
  876. /// <param name="progress">The progress.</param>
  877. /// <param name="cancellationToken">The cancellation token.</param>
  878. /// <returns>Task.</returns>
  879. private async Task RunPostScanTasks(IProgress<double> progress, CancellationToken cancellationToken)
  880. {
  881. var postscanTasks = PostscanTasks.ToList();
  882. var progressDictionary = new Dictionary<ILibraryPostScanTask, double>();
  883. var tasks = postscanTasks.Select(i => Task.Run(async () =>
  884. {
  885. var innerProgress = new ActionableProgress<double>();
  886. innerProgress.RegisterAction(pct =>
  887. {
  888. lock (progressDictionary)
  889. {
  890. progressDictionary[i] = pct;
  891. double percent = progressDictionary.Values.Sum();
  892. percent /= postscanTasks.Count;
  893. progress.Report(75 + percent * .25);
  894. }
  895. });
  896. try
  897. {
  898. await i.Run(innerProgress, cancellationToken);
  899. }
  900. catch (OperationCanceledException)
  901. {
  902. _logger.Info("Post-scan task cancelled: {0}", i.GetType().Name);
  903. }
  904. catch (Exception ex)
  905. {
  906. _logger.ErrorException("Error running postscan task", ex);
  907. }
  908. }));
  909. await Task.WhenAll(tasks).ConfigureAwait(false);
  910. }
  911. /// <summary>
  912. /// Validates only the collection folders for a User and goes no further
  913. /// </summary>
  914. /// <param name="userRootFolder">The user root folder.</param>
  915. /// <param name="cancellationToken">The cancellation token.</param>
  916. /// <returns>Task.</returns>
  917. private async Task ValidateCollectionFolders(UserRootFolder userRootFolder, CancellationToken cancellationToken)
  918. {
  919. _logger.Info("Validating collection folders within {0}", userRootFolder.Path);
  920. await userRootFolder.RefreshMetadata(cancellationToken).ConfigureAwait(false);
  921. cancellationToken.ThrowIfCancellationRequested();
  922. await userRootFolder.ValidateChildren(new Progress<double>(), cancellationToken, recursive: false).ConfigureAwait(false);
  923. }
  924. /// <summary>
  925. /// Gets the default view.
  926. /// </summary>
  927. /// <returns>IEnumerable{VirtualFolderInfo}.</returns>
  928. public IEnumerable<VirtualFolderInfo> GetDefaultVirtualFolders()
  929. {
  930. return GetView(ConfigurationManager.ApplicationPaths.DefaultUserViewsPath);
  931. }
  932. /// <summary>
  933. /// Gets the view.
  934. /// </summary>
  935. /// <param name="user">The user.</param>
  936. /// <returns>IEnumerable{VirtualFolderInfo}.</returns>
  937. public IEnumerable<VirtualFolderInfo> GetVirtualFolders(User user)
  938. {
  939. return GetView(user.RootFolderPath);
  940. }
  941. /// <summary>
  942. /// Gets the view.
  943. /// </summary>
  944. /// <param name="path">The path.</param>
  945. /// <returns>IEnumerable{VirtualFolderInfo}.</returns>
  946. private IEnumerable<VirtualFolderInfo> GetView(string path)
  947. {
  948. return Directory.EnumerateDirectories(path, "*", SearchOption.TopDirectoryOnly)
  949. .Select(dir => new VirtualFolderInfo
  950. {
  951. Name = Path.GetFileName(dir),
  952. Locations = Directory.EnumerateFiles(dir, "*.lnk", SearchOption.TopDirectoryOnly)
  953. .Select(FileSystem.ResolveShortcut)
  954. .OrderBy(i => i)
  955. .ToList(),
  956. CollectionType = GetCollectionType(dir)
  957. });
  958. }
  959. private string GetCollectionType(string path)
  960. {
  961. return new DirectoryInfo(path).EnumerateFiles("*.collection", SearchOption.TopDirectoryOnly)
  962. .Select(i => Path.GetFileNameWithoutExtension(i.FullName))
  963. .FirstOrDefault();
  964. }
  965. /// <summary>
  966. /// Gets the item by id.
  967. /// </summary>
  968. /// <param name="id">The id.</param>
  969. /// <returns>BaseItem.</returns>
  970. /// <exception cref="System.ArgumentNullException">id</exception>
  971. public BaseItem GetItemById(Guid id)
  972. {
  973. if (id == Guid.Empty)
  974. {
  975. throw new ArgumentNullException("id");
  976. }
  977. BaseItem item;
  978. if (LibraryItemsCache.TryGetValue(id, out item))
  979. {
  980. return item;
  981. }
  982. return RetrieveItem(id);
  983. }
  984. /// <summary>
  985. /// Gets the intros.
  986. /// </summary>
  987. /// <param name="item">The item.</param>
  988. /// <param name="user">The user.</param>
  989. /// <returns>IEnumerable{System.String}.</returns>
  990. public IEnumerable<string> GetIntros(BaseItem item, User user)
  991. {
  992. return IntroProviders.SelectMany(i => i.GetIntros(item, user));
  993. }
  994. /// <summary>
  995. /// Sorts the specified sort by.
  996. /// </summary>
  997. /// <param name="items">The items.</param>
  998. /// <param name="user">The user.</param>
  999. /// <param name="sortBy">The sort by.</param>
  1000. /// <param name="sortOrder">The sort order.</param>
  1001. /// <returns>IEnumerable{BaseItem}.</returns>
  1002. public IEnumerable<BaseItem> Sort(IEnumerable<BaseItem> items, User user, IEnumerable<string> sortBy, SortOrder sortOrder)
  1003. {
  1004. var isFirst = true;
  1005. IOrderedEnumerable<BaseItem> orderedItems = null;
  1006. foreach (var orderBy in sortBy.Select(o => GetComparer(o, user)).Where(c => c != null))
  1007. {
  1008. if (isFirst)
  1009. {
  1010. orderedItems = sortOrder == SortOrder.Descending ? items.OrderByDescending(i => i, orderBy) : items.OrderBy(i => i, orderBy);
  1011. }
  1012. else
  1013. {
  1014. orderedItems = sortOrder == SortOrder.Descending ? orderedItems.ThenByDescending(i => i, orderBy) : orderedItems.ThenBy(i => i, orderBy);
  1015. }
  1016. isFirst = false;
  1017. }
  1018. return orderedItems ?? items;
  1019. }
  1020. /// <summary>
  1021. /// Gets the comparer.
  1022. /// </summary>
  1023. /// <param name="name">The name.</param>
  1024. /// <param name="user">The user.</param>
  1025. /// <returns>IBaseItemComparer.</returns>
  1026. private IBaseItemComparer GetComparer(string name, User user)
  1027. {
  1028. var comparer = Comparers.FirstOrDefault(c => string.Equals(name, c.Name, StringComparison.OrdinalIgnoreCase));
  1029. if (comparer != null)
  1030. {
  1031. // If it requires a user, create a new one, and assign the user
  1032. if (comparer is IUserBaseItemComparer)
  1033. {
  1034. var userComparer = (IUserBaseItemComparer)Activator.CreateInstance(comparer.GetType());
  1035. userComparer.User = user;
  1036. userComparer.UserManager = _userManager;
  1037. userComparer.UserDataRepository = _userDataRepository;
  1038. return userComparer;
  1039. }
  1040. }
  1041. return comparer;
  1042. }
  1043. /// <summary>
  1044. /// Creates the item.
  1045. /// </summary>
  1046. /// <param name="item">The item.</param>
  1047. /// <param name="cancellationToken">The cancellation token.</param>
  1048. /// <returns>Task.</returns>
  1049. public Task CreateItem(BaseItem item, CancellationToken cancellationToken)
  1050. {
  1051. return CreateItems(new[] { item }, cancellationToken);
  1052. }
  1053. /// <summary>
  1054. /// Creates the items.
  1055. /// </summary>
  1056. /// <param name="items">The items.</param>
  1057. /// <param name="cancellationToken">The cancellation token.</param>
  1058. /// <returns>Task.</returns>
  1059. public async Task CreateItems(IEnumerable<BaseItem> items, CancellationToken cancellationToken)
  1060. {
  1061. var list = items.ToList();
  1062. await ItemRepository.SaveItems(list, cancellationToken).ConfigureAwait(false);
  1063. foreach (var item in list)
  1064. {
  1065. UpdateItemInLibraryCache(item);
  1066. }
  1067. UpdateCollectionFolders();
  1068. if (ItemAdded != null)
  1069. {
  1070. foreach (var item in list)
  1071. {
  1072. try
  1073. {
  1074. ItemAdded(this, new ItemChangeEventArgs { Item = item });
  1075. }
  1076. catch (Exception ex)
  1077. {
  1078. _logger.ErrorException("Error in ItemAdded event handler", ex);
  1079. }
  1080. }
  1081. }
  1082. }
  1083. /// <summary>
  1084. /// Updates the item.
  1085. /// </summary>
  1086. /// <param name="item">The item.</param>
  1087. /// <param name="updateReason">The update reason.</param>
  1088. /// <param name="cancellationToken">The cancellation token.</param>
  1089. /// <returns>Task.</returns>
  1090. public async Task UpdateItem(BaseItem item, ItemUpdateType updateReason, CancellationToken cancellationToken)
  1091. {
  1092. if (item.LocationType == LocationType.FileSystem)
  1093. {
  1094. await SaveMetadata(item, updateReason).ConfigureAwait(false);
  1095. }
  1096. await ItemRepository.SaveItem(item, cancellationToken).ConfigureAwait(false);
  1097. UpdateItemInLibraryCache(item);
  1098. if (ItemUpdated != null)
  1099. {
  1100. try
  1101. {
  1102. ItemUpdated(this, new ItemChangeEventArgs { Item = item });
  1103. }
  1104. catch (Exception ex)
  1105. {
  1106. _logger.ErrorException("Error in ItemUpdated event handler", ex);
  1107. }
  1108. }
  1109. }
  1110. /// <summary>
  1111. /// Reports the item removed.
  1112. /// </summary>
  1113. /// <param name="item">The item.</param>
  1114. public void ReportItemRemoved(BaseItem item)
  1115. {
  1116. UpdateCollectionFolders();
  1117. if (ItemRemoved != null)
  1118. {
  1119. try
  1120. {
  1121. ItemRemoved(this, new ItemChangeEventArgs { Item = item });
  1122. }
  1123. catch (Exception ex)
  1124. {
  1125. _logger.ErrorException("Error in ItemRemoved event handler", ex);
  1126. }
  1127. }
  1128. }
  1129. private void UpdateCollectionFolders()
  1130. {
  1131. foreach (var folder in _userManager.Users.SelectMany(i => i.RootFolder.Children).OfType<CollectionFolder>().ToList())
  1132. {
  1133. folder.ResetDynamicChildren();
  1134. }
  1135. }
  1136. /// <summary>
  1137. /// Retrieves the item.
  1138. /// </summary>
  1139. /// <param name="id">The id.</param>
  1140. /// <returns>BaseItem.</returns>
  1141. public BaseItem RetrieveItem(Guid id)
  1142. {
  1143. var item = ItemRepository.RetrieveItem(id);
  1144. var folder = item as Folder;
  1145. if (folder != null)
  1146. {
  1147. folder.LoadSavedChildren();
  1148. }
  1149. return item;
  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. }