LibraryManager.cs 51 KB

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