LibraryManager.cs 54 KB

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