LibraryManager.cs 54 KB

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