2
0

LibraryManager.cs 53 KB

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