LibraryManager.cs 54 KB

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