LibraryManager.cs 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554
  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. ConfigurationManager.ApplicationPaths.GetInternalMetadataPath(item.Id)
  394. };
  395. list.AddRange(children.Select(i => ConfigurationManager.ApplicationPaths.GetInternalMetadataPath(i.Id)));
  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. return items.Select(i =>
  426. {
  427. var video = i as Video;
  428. if (video != null)
  429. {
  430. if (video.PrimaryVersionId.HasValue)
  431. {
  432. var primary = GetItemById(video.PrimaryVersionId.Value) as Video;
  433. if (primary != null)
  434. {
  435. return primary;
  436. }
  437. }
  438. }
  439. return i;
  440. }).DistinctBy(i => i.Id);
  441. }
  442. /// <summary>
  443. /// Ensure supplied item has only one instance throughout
  444. /// </summary>
  445. /// <param name="item">The item.</param>
  446. /// <returns>The proper instance to the item</returns>
  447. public BaseItem GetOrAddByReferenceItem(BaseItem item)
  448. {
  449. // Add this item to our list if not there already
  450. if (!ByReferenceItems.TryAdd(item.Id, item))
  451. {
  452. // Already there - return the existing reference
  453. item = ByReferenceItems[item.Id];
  454. }
  455. return item;
  456. }
  457. public BaseItem ResolvePath(FileSystemInfo fileInfo, Folder parent = null)
  458. {
  459. return ResolvePath(fileInfo, new DirectoryService(_logger), parent);
  460. }
  461. /// <summary>
  462. /// Resolves a path into a BaseItem
  463. /// </summary>
  464. /// <param name="fileInfo">The file info.</param>
  465. /// <param name="directoryService">The directory service.</param>
  466. /// <param name="parent">The parent.</param>
  467. /// <returns>BaseItem.</returns>
  468. /// <exception cref="System.ArgumentNullException">fileInfo</exception>
  469. public BaseItem ResolvePath(FileSystemInfo fileInfo, IDirectoryService directoryService, Folder parent = null)
  470. {
  471. if (fileInfo == null)
  472. {
  473. throw new ArgumentNullException("fileInfo");
  474. }
  475. var args = new ItemResolveArgs(ConfigurationManager.ApplicationPaths, this, directoryService)
  476. {
  477. Parent = parent,
  478. Path = fileInfo.FullName,
  479. FileInfo = fileInfo
  480. };
  481. // Return null if ignore rules deem that we should do so
  482. if (EntityResolutionIgnoreRules.Any(r => r.ShouldIgnore(args)))
  483. {
  484. return null;
  485. }
  486. // Gather child folder and files
  487. if (args.IsDirectory)
  488. {
  489. var isPhysicalRoot = args.IsPhysicalRoot;
  490. // When resolving the root, we need it's grandchildren (children of user views)
  491. var flattenFolderDepth = isPhysicalRoot ? 2 : 0;
  492. var fileSystemDictionary = FileData.GetFilteredFileSystemEntries(directoryService, args.Path, _fileSystem, _logger, args, flattenFolderDepth: flattenFolderDepth, resolveShortcuts: isPhysicalRoot || args.IsVf);
  493. // Need to remove subpaths that may have been resolved from shortcuts
  494. // Example: if \\server\movies exists, then strip out \\server\movies\action
  495. if (isPhysicalRoot)
  496. {
  497. var paths = NormalizeRootPathList(fileSystemDictionary.Keys);
  498. fileSystemDictionary = paths.Select(i => (FileSystemInfo)new DirectoryInfo(i)).ToDictionary(i => i.FullName);
  499. }
  500. args.FileSystemDictionary = fileSystemDictionary;
  501. }
  502. // Check to see if we should resolve based on our contents
  503. if (args.IsDirectory && !ShouldResolvePathContents(args))
  504. {
  505. return null;
  506. }
  507. return ResolveItem(args);
  508. }
  509. public IEnumerable<string> NormalizeRootPathList(IEnumerable<string> paths)
  510. {
  511. var list = paths.Select(_fileSystem.NormalizePath)
  512. .Distinct(StringComparer.OrdinalIgnoreCase)
  513. .ToList();
  514. var dupes = list.Where(subPath => !subPath.EndsWith(":\\", StringComparison.OrdinalIgnoreCase) && list.Any(i => _fileSystem.ContainsSubPath(i, subPath)))
  515. .ToList();
  516. foreach (var dupe in dupes)
  517. {
  518. _logger.Info("Found duplicate path: {0}", dupe);
  519. }
  520. return list.Except(dupes, StringComparer.OrdinalIgnoreCase);
  521. }
  522. /// <summary>
  523. /// Determines whether a path should be ignored based on its contents - called after the contents have been read
  524. /// </summary>
  525. /// <param name="args">The args.</param>
  526. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  527. private static bool ShouldResolvePathContents(ItemResolveArgs args)
  528. {
  529. // Ignore any folders containing a file called .ignore
  530. return !args.ContainsFileSystemEntryByName(".ignore");
  531. }
  532. /// <summary>
  533. /// Resolves a set of files into a list of BaseItem
  534. /// </summary>
  535. /// <typeparam name="T"></typeparam>
  536. /// <param name="files">The files.</param>
  537. /// <param name="directoryService">The directory service.</param>
  538. /// <param name="parent">The parent.</param>
  539. /// <returns>List{``0}.</returns>
  540. public List<T> ResolvePaths<T>(IEnumerable<FileSystemInfo> files, IDirectoryService directoryService, Folder parent)
  541. where T : BaseItem
  542. {
  543. var list = new List<T>();
  544. Parallel.ForEach(files, f =>
  545. {
  546. try
  547. {
  548. var item = ResolvePath(f, directoryService, parent) as T;
  549. if (item != null)
  550. {
  551. lock (list)
  552. {
  553. list.Add(item);
  554. }
  555. }
  556. }
  557. catch (Exception ex)
  558. {
  559. _logger.ErrorException("Error resolving path {0}", ex, f.FullName);
  560. }
  561. });
  562. return list;
  563. }
  564. /// <summary>
  565. /// Creates the root media folder
  566. /// </summary>
  567. /// <returns>AggregateFolder.</returns>
  568. /// <exception cref="System.InvalidOperationException">Cannot create the root folder until plugins have loaded</exception>
  569. public AggregateFolder CreateRootFolder()
  570. {
  571. var rootFolderPath = ConfigurationManager.ApplicationPaths.RootFolderPath;
  572. Directory.CreateDirectory(rootFolderPath);
  573. var rootFolder = GetItemById(rootFolderPath.GetMBId(typeof(AggregateFolder))) as AggregateFolder ?? (AggregateFolder)ResolvePath(new DirectoryInfo(rootFolderPath));
  574. // Add in the plug-in folders
  575. foreach (var child in PluginFolderCreators)
  576. {
  577. var folder = child.GetFolder();
  578. if (folder != null)
  579. {
  580. if (folder.Id == Guid.Empty)
  581. {
  582. folder.Id = (folder.Path ?? folder.GetType().Name).GetMBId(folder.GetType());
  583. }
  584. folder = GetItemById(folder.Id) as BasePluginFolder ?? folder;
  585. rootFolder.AddVirtualChild(folder);
  586. RegisterItem(folder);
  587. }
  588. }
  589. return rootFolder;
  590. }
  591. private UserRootFolder _userRootFolder;
  592. public Folder GetUserRootFolder()
  593. {
  594. if (_userRootFolder == null)
  595. {
  596. var userRootPath = ConfigurationManager.ApplicationPaths.DefaultUserViewsPath;
  597. Directory.CreateDirectory(userRootPath);
  598. _userRootFolder = GetItemById(userRootPath.GetMBId(typeof(UserRootFolder))) as UserRootFolder ??
  599. (UserRootFolder)ResolvePath(new DirectoryInfo(userRootPath));
  600. }
  601. return _userRootFolder;
  602. }
  603. /// <summary>
  604. /// Gets a Person
  605. /// </summary>
  606. /// <param name="name">The name.</param>
  607. /// <returns>Task{Person}.</returns>
  608. public Person GetPerson(string name)
  609. {
  610. return GetItemByName<Person>(ConfigurationManager.ApplicationPaths.PeoplePath, name);
  611. }
  612. /// <summary>
  613. /// Gets a Studio
  614. /// </summary>
  615. /// <param name="name">The name.</param>
  616. /// <returns>Task{Studio}.</returns>
  617. public Studio GetStudio(string name)
  618. {
  619. return GetItemByName<Studio>(ConfigurationManager.ApplicationPaths.StudioPath, name);
  620. }
  621. /// <summary>
  622. /// Gets a Genre
  623. /// </summary>
  624. /// <param name="name">The name.</param>
  625. /// <returns>Task{Genre}.</returns>
  626. public Genre GetGenre(string name)
  627. {
  628. return GetItemByName<Genre>(ConfigurationManager.ApplicationPaths.GenrePath, name);
  629. }
  630. /// <summary>
  631. /// Gets the genre.
  632. /// </summary>
  633. /// <param name="name">The name.</param>
  634. /// <returns>Task{MusicGenre}.</returns>
  635. public MusicGenre GetMusicGenre(string name)
  636. {
  637. return GetItemByName<MusicGenre>(ConfigurationManager.ApplicationPaths.MusicGenrePath, name);
  638. }
  639. /// <summary>
  640. /// Gets the game genre.
  641. /// </summary>
  642. /// <param name="name">The name.</param>
  643. /// <returns>Task{GameGenre}.</returns>
  644. public GameGenre GetGameGenre(string name)
  645. {
  646. return GetItemByName<GameGenre>(ConfigurationManager.ApplicationPaths.GameGenrePath, name);
  647. }
  648. /// <summary>
  649. /// The us culture
  650. /// </summary>
  651. private static readonly CultureInfo UsCulture = new CultureInfo("en-US");
  652. /// <summary>
  653. /// Gets a Year
  654. /// </summary>
  655. /// <param name="value">The value.</param>
  656. /// <returns>Task{Year}.</returns>
  657. /// <exception cref="System.ArgumentOutOfRangeException"></exception>
  658. public Year GetYear(int value)
  659. {
  660. if (value <= 0)
  661. {
  662. throw new ArgumentOutOfRangeException("Years less than or equal to 0 are invalid.");
  663. }
  664. return GetItemByName<Year>(ConfigurationManager.ApplicationPaths.YearPath, value.ToString(UsCulture));
  665. }
  666. /// <summary>
  667. /// Gets a Genre
  668. /// </summary>
  669. /// <param name="name">The name.</param>
  670. /// <returns>Task{Genre}.</returns>
  671. public MusicArtist GetArtist(string name)
  672. {
  673. return GetItemByName<MusicArtist>(ConfigurationManager.ApplicationPaths.ArtistsPath, name);
  674. }
  675. private T GetItemByName<T>(string path, string name)
  676. where T : BaseItem, new()
  677. {
  678. if (string.IsNullOrWhiteSpace(path))
  679. {
  680. throw new ArgumentNullException("path");
  681. }
  682. if (string.IsNullOrWhiteSpace(name))
  683. {
  684. throw new ArgumentNullException("name");
  685. }
  686. var validFilename = _fileSystem.GetValidFilename(name).Trim();
  687. string subFolderPrefix = null;
  688. var type = typeof(T);
  689. if (type == typeof(Person) && ConfigurationManager.Configuration.EnablePeoplePrefixSubFolders)
  690. {
  691. subFolderPrefix = validFilename.Substring(0, 1);
  692. }
  693. var fullPath = string.IsNullOrEmpty(subFolderPrefix) ?
  694. Path.Combine(path, validFilename) :
  695. Path.Combine(path, subFolderPrefix, validFilename);
  696. var id = fullPath.GetMBId(type);
  697. BaseItem obj;
  698. if (!_libraryItemsCache.TryGetValue(id, out obj))
  699. {
  700. obj = CreateItemByName<T>(fullPath, name, id);
  701. RegisterItem(id, obj);
  702. }
  703. return obj as T;
  704. }
  705. /// <summary>
  706. /// Creates an IBN item based on a given path
  707. /// </summary>
  708. /// <typeparam name="T"></typeparam>
  709. /// <param name="path">The path.</param>
  710. /// <param name="name">The name.</param>
  711. /// <returns>Task{``0}.</returns>
  712. /// <exception cref="System.IO.IOException">Path not created: + path</exception>
  713. private T CreateItemByName<T>(string path, string name, Guid id)
  714. where T : BaseItem, new()
  715. {
  716. var isArtist = typeof(T) == typeof(MusicArtist);
  717. if (isArtist)
  718. {
  719. var validFilename = _fileSystem.GetValidFilename(name).Trim();
  720. var existing = RootFolder.RecursiveChildren
  721. .OfType<T>()
  722. .FirstOrDefault(i => string.Equals(_fileSystem.GetValidFilename(i.Name).Trim(), validFilename, 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. fileInfo = Directory.CreateDirectory(path);
  733. isNew = true;
  734. }
  735. var item = isNew ? null : GetItemById(id) as T;
  736. if (item == null)
  737. {
  738. item = new T
  739. {
  740. Name = name,
  741. Id = id,
  742. DateCreated = _fileSystem.GetCreationTimeUtc(fileInfo),
  743. DateModified = _fileSystem.GetLastWriteTimeUtc(fileInfo),
  744. Path = path
  745. };
  746. }
  747. if (isArtist)
  748. {
  749. (item as MusicArtist).IsAccessedByName = true;
  750. }
  751. return item;
  752. }
  753. /// <summary>
  754. /// Validate and refresh the People sub-set of the IBN.
  755. /// The items are stored in the db but not loaded into memory until actually requested by an operation.
  756. /// </summary>
  757. /// <param name="cancellationToken">The cancellation token.</param>
  758. /// <param name="progress">The progress.</param>
  759. /// <returns>Task.</returns>
  760. public Task ValidatePeople(CancellationToken cancellationToken, IProgress<double> progress)
  761. {
  762. // Ensure the location is available.
  763. Directory.CreateDirectory(ConfigurationManager.ApplicationPaths.PeoplePath);
  764. return new PeopleValidator(this, _logger, ConfigurationManager).ValidatePeople(cancellationToken, progress);
  765. }
  766. /// <summary>
  767. /// Validates the artists.
  768. /// </summary>
  769. /// <param name="cancellationToken">The cancellation token.</param>
  770. /// <param name="progress">The progress.</param>
  771. /// <returns>Task.</returns>
  772. public Task ValidateArtists(CancellationToken cancellationToken, IProgress<double> progress)
  773. {
  774. // Ensure the location is unavailable.
  775. Directory.CreateDirectory(ConfigurationManager.ApplicationPaths.ArtistsPath);
  776. return new ArtistsValidator(this, _userManager, _logger).Run(progress, cancellationToken);
  777. }
  778. /// <summary>
  779. /// Validates the music 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 ValidateMusicGenres(CancellationToken cancellationToken, IProgress<double> progress)
  785. {
  786. // Ensure the location is unavailable.
  787. Directory.CreateDirectory(ConfigurationManager.ApplicationPaths.MusicGenrePath);
  788. return new MusicGenresValidator(this, _logger).Run(progress, cancellationToken);
  789. }
  790. /// <summary>
  791. /// Validates the game genres.
  792. /// </summary>
  793. /// <param name="cancellationToken">The cancellation token.</param>
  794. /// <param name="progress">The progress.</param>
  795. /// <returns>Task.</returns>
  796. public Task ValidateGameGenres(CancellationToken cancellationToken, IProgress<double> progress)
  797. {
  798. // Ensure the location is unavailable.
  799. Directory.CreateDirectory(ConfigurationManager.ApplicationPaths.GameGenrePath);
  800. return new GameGenresValidator(this, _userManager, _logger).Run(progress, cancellationToken);
  801. }
  802. /// <summary>
  803. /// Validates the studios.
  804. /// </summary>
  805. /// <param name="cancellationToken">The cancellation token.</param>
  806. /// <param name="progress">The progress.</param>
  807. /// <returns>Task.</returns>
  808. public Task ValidateStudios(CancellationToken cancellationToken, IProgress<double> progress)
  809. {
  810. // Ensure the location is unavailable.
  811. Directory.CreateDirectory(ConfigurationManager.ApplicationPaths.StudioPath);
  812. return new StudiosValidator(this, _userManager, _logger).Run(progress, cancellationToken);
  813. }
  814. /// <summary>
  815. /// Validates the genres.
  816. /// </summary>
  817. /// <param name="cancellationToken">The cancellation token.</param>
  818. /// <param name="progress">The progress.</param>
  819. /// <returns>Task.</returns>
  820. public Task ValidateGenres(CancellationToken cancellationToken, IProgress<double> progress)
  821. {
  822. // Ensure the location is unavailable.
  823. Directory.CreateDirectory(ConfigurationManager.ApplicationPaths.GenrePath);
  824. return new GenresValidator(this, _userManager, _logger).Run(progress, cancellationToken);
  825. }
  826. /// <summary>
  827. /// Reloads the root media folder
  828. /// </summary>
  829. /// <param name="progress">The progress.</param>
  830. /// <param name="cancellationToken">The cancellation token.</param>
  831. /// <returns>Task.</returns>
  832. public Task ValidateMediaLibrary(IProgress<double> progress, CancellationToken cancellationToken)
  833. {
  834. // Just run the scheduled task so that the user can see it
  835. _taskManager.CancelIfRunningAndQueue<RefreshMediaLibraryTask>();
  836. return Task.FromResult(true);
  837. }
  838. /// <summary>
  839. /// Queues the library scan.
  840. /// </summary>
  841. public void QueueLibraryScan()
  842. {
  843. // Just run the scheduled task so that the user can see it
  844. _taskManager.QueueScheduledTask<RefreshMediaLibraryTask>();
  845. }
  846. /// <summary>
  847. /// Validates the media library internal.
  848. /// </summary>
  849. /// <param name="progress">The progress.</param>
  850. /// <param name="cancellationToken">The cancellation token.</param>
  851. /// <returns>Task.</returns>
  852. public async Task ValidateMediaLibraryInternal(IProgress<double> progress, CancellationToken cancellationToken)
  853. {
  854. _libraryMonitorFactory().Stop();
  855. try
  856. {
  857. await PerformLibraryValidation(progress, cancellationToken).ConfigureAwait(false);
  858. }
  859. finally
  860. {
  861. _libraryMonitorFactory().Start();
  862. }
  863. }
  864. private async Task PerformLibraryValidation(IProgress<double> progress, CancellationToken cancellationToken)
  865. {
  866. _logger.Info("Validating media library");
  867. await RootFolder.RefreshMetadata(cancellationToken).ConfigureAwait(false);
  868. progress.Report(.5);
  869. // Start by just validating the children of the root, but go no further
  870. await RootFolder.ValidateChildren(new Progress<double>(), cancellationToken, new MetadataRefreshOptions(), recursive: false);
  871. progress.Report(1);
  872. var userRoot = GetUserRootFolder();
  873. await userRoot.RefreshMetadata(cancellationToken).ConfigureAwait(false);
  874. await userRoot.ValidateChildren(new Progress<double>(), cancellationToken, new MetadataRefreshOptions(), recursive: false).ConfigureAwait(false);
  875. progress.Report(2);
  876. var innerProgress = new ActionableProgress<double>();
  877. innerProgress.RegisterAction(pct => progress.Report(2 + pct * .73));
  878. // Now validate the entire media library
  879. await RootFolder.ValidateChildren(innerProgress, cancellationToken, new MetadataRefreshOptions(), recursive: true).ConfigureAwait(false);
  880. progress.Report(75);
  881. innerProgress = new ActionableProgress<double>();
  882. innerProgress.RegisterAction(pct => progress.Report(75 + pct * .25));
  883. // Run post-scan tasks
  884. await RunPostScanTasks(innerProgress, cancellationToken).ConfigureAwait(false);
  885. progress.Report(100);
  886. // Bad practice, i know. But we keep a lot in memory, unfortunately.
  887. GC.Collect(2, GCCollectionMode.Forced, true);
  888. GC.Collect(2, GCCollectionMode.Forced, true);
  889. }
  890. /// <summary>
  891. /// Runs the post scan tasks.
  892. /// </summary>
  893. /// <param name="progress">The progress.</param>
  894. /// <param name="cancellationToken">The cancellation token.</param>
  895. /// <returns>Task.</returns>
  896. private async Task RunPostScanTasks(IProgress<double> progress, CancellationToken cancellationToken)
  897. {
  898. var tasks = PostscanTasks.ToList();
  899. var numComplete = 0;
  900. var numTasks = tasks.Count;
  901. foreach (var task in tasks)
  902. {
  903. var innerProgress = new ActionableProgress<double>();
  904. // Prevent access to modified closure
  905. var currentNumComplete = numComplete;
  906. innerProgress.RegisterAction(pct =>
  907. {
  908. double innerPercent = (currentNumComplete * 100) + pct;
  909. innerPercent /= numTasks;
  910. progress.Report(innerPercent);
  911. });
  912. try
  913. {
  914. await task.Run(innerProgress, cancellationToken);
  915. }
  916. catch (OperationCanceledException)
  917. {
  918. _logger.Info("Post-scan task cancelled: {0}", task.GetType().Name);
  919. }
  920. catch (Exception ex)
  921. {
  922. _logger.ErrorException("Error running postscan task", ex);
  923. }
  924. numComplete++;
  925. double percent = numComplete;
  926. percent /= numTasks;
  927. progress.Report(percent * 100);
  928. }
  929. progress.Report(100);
  930. }
  931. /// <summary>
  932. /// Gets the default view.
  933. /// </summary>
  934. /// <returns>IEnumerable{VirtualFolderInfo}.</returns>
  935. public IEnumerable<VirtualFolderInfo> GetDefaultVirtualFolders()
  936. {
  937. return GetView(ConfigurationManager.ApplicationPaths.DefaultUserViewsPath);
  938. }
  939. /// <summary>
  940. /// Gets the view.
  941. /// </summary>
  942. /// <param name="user">The user.</param>
  943. /// <returns>IEnumerable{VirtualFolderInfo}.</returns>
  944. public IEnumerable<VirtualFolderInfo> GetVirtualFolders(User user)
  945. {
  946. return GetDefaultVirtualFolders();
  947. }
  948. /// <summary>
  949. /// Gets the view.
  950. /// </summary>
  951. /// <param name="path">The path.</param>
  952. /// <returns>IEnumerable{VirtualFolderInfo}.</returns>
  953. private IEnumerable<VirtualFolderInfo> GetView(string path)
  954. {
  955. return Directory.EnumerateDirectories(path, "*", SearchOption.TopDirectoryOnly)
  956. .Select(dir => new VirtualFolderInfo
  957. {
  958. Name = Path.GetFileName(dir),
  959. Locations = Directory.EnumerateFiles(dir, "*.mblink", SearchOption.TopDirectoryOnly)
  960. .Select(_fileSystem.ResolveShortcut)
  961. .OrderBy(i => i)
  962. .ToList(),
  963. CollectionType = GetCollectionType(dir)
  964. });
  965. }
  966. private string GetCollectionType(string path)
  967. {
  968. return new DirectoryInfo(path).EnumerateFiles("*.collection", SearchOption.TopDirectoryOnly)
  969. .Select(i => _fileSystem.GetFileNameWithoutExtension(i))
  970. .FirstOrDefault();
  971. }
  972. /// <summary>
  973. /// Gets the item by id.
  974. /// </summary>
  975. /// <param name="id">The id.</param>
  976. /// <returns>BaseItem.</returns>
  977. /// <exception cref="System.ArgumentNullException">id</exception>
  978. public BaseItem GetItemById(Guid id)
  979. {
  980. if (id == Guid.Empty)
  981. {
  982. throw new ArgumentNullException("id");
  983. }
  984. BaseItem item;
  985. if (LibraryItemsCache.TryGetValue(id, out item))
  986. {
  987. return item;
  988. }
  989. item = RetrieveItem(id);
  990. if (item != null)
  991. {
  992. RegisterItem(item);
  993. }
  994. return item;
  995. }
  996. /// <summary>
  997. /// Gets the intros.
  998. /// </summary>
  999. /// <param name="item">The item.</param>
  1000. /// <param name="user">The user.</param>
  1001. /// <returns>IEnumerable{System.String}.</returns>
  1002. public async Task<IEnumerable<Video>> GetIntros(BaseItem item, User user)
  1003. {
  1004. var tasks = IntroProviders
  1005. .OrderBy(i => (i.GetType().Name.IndexOf("Default", StringComparison.OrdinalIgnoreCase) == -1 ? 1 : 0))
  1006. .Take(1)
  1007. .Select(i => GetIntros(i, item, user));
  1008. var items = await Task.WhenAll(tasks).ConfigureAwait(false);
  1009. return items
  1010. .SelectMany(i => i.ToArray())
  1011. .Select(ResolveIntro)
  1012. .Where(i => i != null);
  1013. }
  1014. /// <summary>
  1015. /// Gets the intros.
  1016. /// </summary>
  1017. /// <param name="provider">The provider.</param>
  1018. /// <param name="item">The item.</param>
  1019. /// <param name="user">The user.</param>
  1020. /// <returns>Task&lt;IEnumerable&lt;IntroInfo&gt;&gt;.</returns>
  1021. private async Task<IEnumerable<IntroInfo>> GetIntros(IIntroProvider provider, BaseItem item, User user)
  1022. {
  1023. try
  1024. {
  1025. return await provider.GetIntros(item, user).ConfigureAwait(false);
  1026. }
  1027. catch (Exception ex)
  1028. {
  1029. _logger.ErrorException("Error getting intros", ex);
  1030. return new List<IntroInfo>();
  1031. }
  1032. }
  1033. /// <summary>
  1034. /// Gets all intro files.
  1035. /// </summary>
  1036. /// <returns>IEnumerable{System.String}.</returns>
  1037. public IEnumerable<string> GetAllIntroFiles()
  1038. {
  1039. return IntroProviders.SelectMany(i =>
  1040. {
  1041. try
  1042. {
  1043. return i.GetAllIntroFiles().ToList();
  1044. }
  1045. catch (Exception ex)
  1046. {
  1047. _logger.ErrorException("Error getting intro files", ex);
  1048. return new List<string>();
  1049. }
  1050. });
  1051. }
  1052. /// <summary>
  1053. /// Resolves the intro.
  1054. /// </summary>
  1055. /// <param name="info">The info.</param>
  1056. /// <returns>Video.</returns>
  1057. private Video ResolveIntro(IntroInfo info)
  1058. {
  1059. Video video = null;
  1060. if (info.ItemId.HasValue)
  1061. {
  1062. // Get an existing item by Id
  1063. video = GetItemById(info.ItemId.Value) as Video;
  1064. if (video == null)
  1065. {
  1066. _logger.Error("Unable to locate item with Id {0}.", info.ItemId.Value);
  1067. }
  1068. }
  1069. else if (!string.IsNullOrEmpty(info.Path))
  1070. {
  1071. try
  1072. {
  1073. // Try to resolve the path into a video
  1074. video = ResolvePath(_fileSystem.GetFileSystemInfo(info.Path)) as Video;
  1075. if (video == null)
  1076. {
  1077. _logger.Error("Intro resolver returned null for {0}.", info.Path);
  1078. }
  1079. else
  1080. {
  1081. // Pull the saved db item that will include metadata
  1082. var dbItem = GetItemById(video.Id) as Video;
  1083. if (dbItem != null)
  1084. {
  1085. video = dbItem;
  1086. }
  1087. }
  1088. }
  1089. catch (Exception ex)
  1090. {
  1091. _logger.ErrorException("Error resolving path {0}.", ex, info.Path);
  1092. }
  1093. }
  1094. else
  1095. {
  1096. _logger.Error("IntroProvider returned an IntroInfo with null Path and ItemId.");
  1097. }
  1098. return video;
  1099. }
  1100. /// <summary>
  1101. /// Sorts the specified sort by.
  1102. /// </summary>
  1103. /// <param name="items">The items.</param>
  1104. /// <param name="user">The user.</param>
  1105. /// <param name="sortBy">The sort by.</param>
  1106. /// <param name="sortOrder">The sort order.</param>
  1107. /// <returns>IEnumerable{BaseItem}.</returns>
  1108. public IEnumerable<BaseItem> Sort(IEnumerable<BaseItem> items, User user, IEnumerable<string> sortBy, SortOrder sortOrder)
  1109. {
  1110. var isFirst = true;
  1111. IOrderedEnumerable<BaseItem> orderedItems = null;
  1112. foreach (var orderBy in sortBy.Select(o => GetComparer(o, user)).Where(c => c != null))
  1113. {
  1114. if (isFirst)
  1115. {
  1116. orderedItems = sortOrder == SortOrder.Descending ? items.OrderByDescending(i => i, orderBy) : items.OrderBy(i => i, orderBy);
  1117. }
  1118. else
  1119. {
  1120. orderedItems = sortOrder == SortOrder.Descending ? orderedItems.ThenByDescending(i => i, orderBy) : orderedItems.ThenBy(i => i, orderBy);
  1121. }
  1122. isFirst = false;
  1123. }
  1124. return orderedItems ?? items;
  1125. }
  1126. /// <summary>
  1127. /// Gets the comparer.
  1128. /// </summary>
  1129. /// <param name="name">The name.</param>
  1130. /// <param name="user">The user.</param>
  1131. /// <returns>IBaseItemComparer.</returns>
  1132. private IBaseItemComparer GetComparer(string name, User user)
  1133. {
  1134. var comparer = Comparers.FirstOrDefault(c => string.Equals(name, c.Name, StringComparison.OrdinalIgnoreCase));
  1135. if (comparer != null)
  1136. {
  1137. // If it requires a user, create a new one, and assign the user
  1138. if (comparer is IUserBaseItemComparer)
  1139. {
  1140. var userComparer = (IUserBaseItemComparer)Activator.CreateInstance(comparer.GetType());
  1141. userComparer.User = user;
  1142. userComparer.UserManager = _userManager;
  1143. userComparer.UserDataRepository = _userDataRepository;
  1144. return userComparer;
  1145. }
  1146. }
  1147. return comparer;
  1148. }
  1149. /// <summary>
  1150. /// Creates the item.
  1151. /// </summary>
  1152. /// <param name="item">The item.</param>
  1153. /// <param name="cancellationToken">The cancellation token.</param>
  1154. /// <returns>Task.</returns>
  1155. public Task CreateItem(BaseItem item, CancellationToken cancellationToken)
  1156. {
  1157. return CreateItems(new[] { item }, cancellationToken);
  1158. }
  1159. /// <summary>
  1160. /// Creates the items.
  1161. /// </summary>
  1162. /// <param name="items">The items.</param>
  1163. /// <param name="cancellationToken">The cancellation token.</param>
  1164. /// <returns>Task.</returns>
  1165. public async Task CreateItems(IEnumerable<BaseItem> items, CancellationToken cancellationToken)
  1166. {
  1167. var list = items.ToList();
  1168. await ItemRepository.SaveItems(list, cancellationToken).ConfigureAwait(false);
  1169. foreach (var item in list)
  1170. {
  1171. UpdateItemInLibraryCache(item);
  1172. }
  1173. if (ItemAdded != null)
  1174. {
  1175. foreach (var item in list)
  1176. {
  1177. try
  1178. {
  1179. ItemAdded(this, new ItemChangeEventArgs { Item = item });
  1180. }
  1181. catch (Exception ex)
  1182. {
  1183. _logger.ErrorException("Error in ItemAdded event handler", ex);
  1184. }
  1185. }
  1186. }
  1187. }
  1188. /// <summary>
  1189. /// Updates the item.
  1190. /// </summary>
  1191. /// <param name="item">The item.</param>
  1192. /// <param name="updateReason">The update reason.</param>
  1193. /// <param name="cancellationToken">The cancellation token.</param>
  1194. /// <returns>Task.</returns>
  1195. public async Task UpdateItem(BaseItem item, ItemUpdateType updateReason, CancellationToken cancellationToken)
  1196. {
  1197. var locationType = item.LocationType;
  1198. if (locationType != LocationType.Remote && locationType != LocationType.Virtual)
  1199. {
  1200. await _providerManagerFactory().SaveMetadata(item, updateReason).ConfigureAwait(false);
  1201. }
  1202. item.DateLastSaved = DateTime.UtcNow;
  1203. _logger.Debug("Saving {0} to database.", item.Path ?? item.Name);
  1204. await ItemRepository.SaveItem(item, cancellationToken).ConfigureAwait(false);
  1205. UpdateItemInLibraryCache(item);
  1206. if (ItemUpdated != null)
  1207. {
  1208. try
  1209. {
  1210. ItemUpdated(this, new ItemChangeEventArgs
  1211. {
  1212. Item = item,
  1213. UpdateReason = updateReason
  1214. });
  1215. }
  1216. catch (Exception ex)
  1217. {
  1218. _logger.ErrorException("Error in ItemUpdated event handler", ex);
  1219. }
  1220. }
  1221. }
  1222. /// <summary>
  1223. /// Reports the item removed.
  1224. /// </summary>
  1225. /// <param name="item">The item.</param>
  1226. public void ReportItemRemoved(BaseItem item)
  1227. {
  1228. if (ItemRemoved != null)
  1229. {
  1230. try
  1231. {
  1232. ItemRemoved(this, new ItemChangeEventArgs { Item = item });
  1233. }
  1234. catch (Exception ex)
  1235. {
  1236. _logger.ErrorException("Error in ItemRemoved event handler", ex);
  1237. }
  1238. }
  1239. }
  1240. /// <summary>
  1241. /// Retrieves the item.
  1242. /// </summary>
  1243. /// <param name="id">The id.</param>
  1244. /// <returns>BaseItem.</returns>
  1245. public BaseItem RetrieveItem(Guid id)
  1246. {
  1247. return ItemRepository.RetrieveItem(id);
  1248. }
  1249. /// <summary>
  1250. /// Finds the type of the collection.
  1251. /// </summary>
  1252. /// <param name="item">The item.</param>
  1253. /// <returns>System.String.</returns>
  1254. public string FindCollectionType(BaseItem item)
  1255. {
  1256. while (!(item.Parent is AggregateFolder) && item.Parent != null)
  1257. {
  1258. item = item.Parent;
  1259. }
  1260. if (item == null)
  1261. {
  1262. return null;
  1263. }
  1264. var collectionTypes = _userManager.Users
  1265. .Select(i => i.RootFolder)
  1266. .Distinct()
  1267. .SelectMany(i => i.Children)
  1268. .OfType<CollectionFolder>()
  1269. .Where(i => string.Equals(i.Path, item.Path, StringComparison.OrdinalIgnoreCase) || i.PhysicalLocations.Contains(item.Path))
  1270. .Select(i => i.CollectionType)
  1271. .Where(i => !string.IsNullOrEmpty(i))
  1272. .Distinct()
  1273. .ToList();
  1274. return collectionTypes.Count == 1 ? collectionTypes[0] : null;
  1275. }
  1276. public Task<UserView> GetNamedView(string name, string type, string sortName, CancellationToken cancellationToken)
  1277. {
  1278. return GetNamedView(name, null, type, sortName, cancellationToken);
  1279. }
  1280. public async Task<UserView> GetNamedView(string name, string category, string type, string sortName, CancellationToken cancellationToken)
  1281. {
  1282. var path = Path.Combine(ConfigurationManager.ApplicationPaths.ItemsByNamePath,
  1283. "views");
  1284. if (!string.IsNullOrWhiteSpace(category))
  1285. {
  1286. path = Path.Combine(path, _fileSystem.GetValidFilename(category));
  1287. }
  1288. path = Path.Combine(path, _fileSystem.GetValidFilename(type));
  1289. var id = (path + "_namedview_" + name).GetMBId(typeof(UserView));
  1290. var item = GetItemById(id) as UserView;
  1291. if (item == null ||
  1292. !string.Equals(item.Path, path, StringComparison.OrdinalIgnoreCase))
  1293. {
  1294. Directory.CreateDirectory(path);
  1295. item = new UserView
  1296. {
  1297. Path = path,
  1298. Id = id,
  1299. DateCreated = DateTime.UtcNow,
  1300. Name = name,
  1301. ViewType = type,
  1302. ForcedSortName = sortName
  1303. };
  1304. await CreateItem(item, cancellationToken).ConfigureAwait(false);
  1305. await item.RefreshMetadata(cancellationToken).ConfigureAwait(false);
  1306. }
  1307. return item;
  1308. }
  1309. }
  1310. }