LibraryManager.cs 53 KB

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