LibraryManager.cs 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632
  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,
  461. Folder parent = null,
  462. string collectionType = null)
  463. {
  464. return ResolvePath(fileInfo, new DirectoryService(_logger), parent, collectionType);
  465. }
  466. public BaseItem ResolvePath(FileSystemInfo fileInfo, IDirectoryService directoryService, Folder parent = null, string collectionType = null)
  467. {
  468. if (fileInfo == null)
  469. {
  470. throw new ArgumentNullException("fileInfo");
  471. }
  472. var args = new ItemResolveArgs(ConfigurationManager.ApplicationPaths, this, directoryService)
  473. {
  474. Parent = parent,
  475. Path = fileInfo.FullName,
  476. FileInfo = fileInfo,
  477. CollectionType = collectionType
  478. };
  479. // Return null if ignore rules deem that we should do so
  480. if (EntityResolutionIgnoreRules.Any(r => r.ShouldIgnore(args)))
  481. {
  482. return null;
  483. }
  484. // Gather child folder and files
  485. if (args.IsDirectory)
  486. {
  487. var isPhysicalRoot = args.IsPhysicalRoot;
  488. // When resolving the root, we need it's grandchildren (children of user views)
  489. var flattenFolderDepth = isPhysicalRoot ? 2 : 0;
  490. var fileSystemDictionary = FileData.GetFilteredFileSystemEntries(directoryService, args.Path, _fileSystem, _logger, args, flattenFolderDepth: flattenFolderDepth, resolveShortcuts: isPhysicalRoot || args.IsVf);
  491. // Need to remove subpaths that may have been resolved from shortcuts
  492. // Example: if \\server\movies exists, then strip out \\server\movies\action
  493. if (isPhysicalRoot)
  494. {
  495. var paths = NormalizeRootPathList(fileSystemDictionary.Keys);
  496. fileSystemDictionary = paths.Select(i => (FileSystemInfo)new DirectoryInfo(i)).ToDictionary(i => i.FullName);
  497. }
  498. args.FileSystemDictionary = fileSystemDictionary;
  499. }
  500. // Check to see if we should resolve based on our contents
  501. if (args.IsDirectory && !ShouldResolvePathContents(args))
  502. {
  503. return null;
  504. }
  505. return ResolveItem(args);
  506. }
  507. public IEnumerable<string> NormalizeRootPathList(IEnumerable<string> paths)
  508. {
  509. var list = paths.Select(_fileSystem.NormalizePath)
  510. .Distinct(StringComparer.OrdinalIgnoreCase)
  511. .ToList();
  512. var dupes = list.Where(subPath => !subPath.EndsWith(":\\", StringComparison.OrdinalIgnoreCase) && list.Any(i => _fileSystem.ContainsSubPath(i, subPath)))
  513. .ToList();
  514. foreach (var dupe in dupes)
  515. {
  516. _logger.Info("Found duplicate path: {0}", dupe);
  517. }
  518. return list.Except(dupes, StringComparer.OrdinalIgnoreCase);
  519. }
  520. /// <summary>
  521. /// Determines whether a path should be ignored based on its contents - called after the contents have been read
  522. /// </summary>
  523. /// <param name="args">The args.</param>
  524. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  525. private static bool ShouldResolvePathContents(ItemResolveArgs args)
  526. {
  527. // Ignore any folders containing a file called .ignore
  528. return !args.ContainsFileSystemEntryByName(".ignore");
  529. }
  530. public List<T> ResolvePaths<T>(IEnumerable<FileSystemInfo> files, IDirectoryService directoryService, Folder parent, string collectionType = null)
  531. where T : BaseItem
  532. {
  533. var list = new List<T>();
  534. Parallel.ForEach(files, f =>
  535. {
  536. try
  537. {
  538. var item = ResolvePath(f, directoryService, parent, collectionType) as T;
  539. if (item != null)
  540. {
  541. lock (list)
  542. {
  543. list.Add(item);
  544. }
  545. }
  546. }
  547. catch (Exception ex)
  548. {
  549. _logger.ErrorException("Error resolving path {0}", ex, f.FullName);
  550. }
  551. });
  552. return list;
  553. }
  554. /// <summary>
  555. /// Creates the root media folder
  556. /// </summary>
  557. /// <returns>AggregateFolder.</returns>
  558. /// <exception cref="System.InvalidOperationException">Cannot create the root folder until plugins have loaded</exception>
  559. public AggregateFolder CreateRootFolder()
  560. {
  561. var rootFolderPath = ConfigurationManager.ApplicationPaths.RootFolderPath;
  562. Directory.CreateDirectory(rootFolderPath);
  563. var rootFolder = GetItemById(rootFolderPath.GetMBId(typeof(AggregateFolder))) as AggregateFolder ?? (AggregateFolder)ResolvePath(new DirectoryInfo(rootFolderPath));
  564. // Add in the plug-in folders
  565. foreach (var child in PluginFolderCreators)
  566. {
  567. var folder = child.GetFolder();
  568. if (folder != null)
  569. {
  570. if (folder.Id == Guid.Empty)
  571. {
  572. folder.Id = (folder.Path ?? folder.GetType().Name).GetMBId(folder.GetType());
  573. }
  574. folder = GetItemById(folder.Id) as BasePluginFolder ?? folder;
  575. rootFolder.AddVirtualChild(folder);
  576. RegisterItem(folder);
  577. }
  578. }
  579. return rootFolder;
  580. }
  581. private UserRootFolder _userRootFolder;
  582. public Folder GetUserRootFolder()
  583. {
  584. if (_userRootFolder == null)
  585. {
  586. var userRootPath = ConfigurationManager.ApplicationPaths.DefaultUserViewsPath;
  587. Directory.CreateDirectory(userRootPath);
  588. _userRootFolder = GetItemById(userRootPath.GetMBId(typeof(UserRootFolder))) as UserRootFolder ??
  589. (UserRootFolder)ResolvePath(new DirectoryInfo(userRootPath));
  590. }
  591. return _userRootFolder;
  592. }
  593. /// <summary>
  594. /// Gets a Person
  595. /// </summary>
  596. /// <param name="name">The name.</param>
  597. /// <returns>Task{Person}.</returns>
  598. public Person GetPerson(string name)
  599. {
  600. return GetItemByName<Person>(ConfigurationManager.ApplicationPaths.PeoplePath, name);
  601. }
  602. /// <summary>
  603. /// Gets a Studio
  604. /// </summary>
  605. /// <param name="name">The name.</param>
  606. /// <returns>Task{Studio}.</returns>
  607. public Studio GetStudio(string name)
  608. {
  609. return GetItemByName<Studio>(ConfigurationManager.ApplicationPaths.StudioPath, name);
  610. }
  611. /// <summary>
  612. /// Gets a Genre
  613. /// </summary>
  614. /// <param name="name">The name.</param>
  615. /// <returns>Task{Genre}.</returns>
  616. public Genre GetGenre(string name)
  617. {
  618. return GetItemByName<Genre>(ConfigurationManager.ApplicationPaths.GenrePath, name);
  619. }
  620. /// <summary>
  621. /// Gets the genre.
  622. /// </summary>
  623. /// <param name="name">The name.</param>
  624. /// <returns>Task{MusicGenre}.</returns>
  625. public MusicGenre GetMusicGenre(string name)
  626. {
  627. return GetItemByName<MusicGenre>(ConfigurationManager.ApplicationPaths.MusicGenrePath, name);
  628. }
  629. /// <summary>
  630. /// Gets the game genre.
  631. /// </summary>
  632. /// <param name="name">The name.</param>
  633. /// <returns>Task{GameGenre}.</returns>
  634. public GameGenre GetGameGenre(string name)
  635. {
  636. return GetItemByName<GameGenre>(ConfigurationManager.ApplicationPaths.GameGenrePath, name);
  637. }
  638. /// <summary>
  639. /// The us culture
  640. /// </summary>
  641. private static readonly CultureInfo UsCulture = new CultureInfo("en-US");
  642. /// <summary>
  643. /// Gets a Year
  644. /// </summary>
  645. /// <param name="value">The value.</param>
  646. /// <returns>Task{Year}.</returns>
  647. /// <exception cref="System.ArgumentOutOfRangeException"></exception>
  648. public Year GetYear(int value)
  649. {
  650. if (value <= 0)
  651. {
  652. throw new ArgumentOutOfRangeException("Years less than or equal to 0 are invalid.");
  653. }
  654. return GetItemByName<Year>(ConfigurationManager.ApplicationPaths.YearPath, value.ToString(UsCulture));
  655. }
  656. /// <summary>
  657. /// Gets a Genre
  658. /// </summary>
  659. /// <param name="name">The name.</param>
  660. /// <returns>Task{Genre}.</returns>
  661. public MusicArtist GetArtist(string name)
  662. {
  663. return GetItemByName<MusicArtist>(ConfigurationManager.ApplicationPaths.ArtistsPath, name);
  664. }
  665. private T GetItemByName<T>(string path, string name)
  666. where T : BaseItem, new()
  667. {
  668. if (string.IsNullOrWhiteSpace(path))
  669. {
  670. throw new ArgumentNullException("path");
  671. }
  672. if (string.IsNullOrWhiteSpace(name))
  673. {
  674. throw new ArgumentNullException("name");
  675. }
  676. var validFilename = _fileSystem.GetValidFilename(name).Trim();
  677. string subFolderPrefix = null;
  678. var type = typeof(T);
  679. if (type == typeof(Person) && ConfigurationManager.Configuration.EnablePeoplePrefixSubFolders)
  680. {
  681. subFolderPrefix = validFilename.Substring(0, 1);
  682. }
  683. var fullPath = string.IsNullOrEmpty(subFolderPrefix) ?
  684. Path.Combine(path, validFilename) :
  685. Path.Combine(path, subFolderPrefix, validFilename);
  686. var id = fullPath.GetMBId(type);
  687. BaseItem obj;
  688. if (!_libraryItemsCache.TryGetValue(id, out obj))
  689. {
  690. obj = CreateItemByName<T>(fullPath, name, id);
  691. RegisterItem(id, obj);
  692. }
  693. return obj as T;
  694. }
  695. /// <summary>
  696. /// Creates an IBN item based on a given path
  697. /// </summary>
  698. /// <typeparam name="T"></typeparam>
  699. /// <param name="path">The path.</param>
  700. /// <param name="name">The name.</param>
  701. /// <returns>Task{``0}.</returns>
  702. /// <exception cref="System.IO.IOException">Path not created: + path</exception>
  703. private T CreateItemByName<T>(string path, string name, Guid id)
  704. where T : BaseItem, new()
  705. {
  706. var isArtist = typeof(T) == typeof(MusicArtist);
  707. if (isArtist)
  708. {
  709. var validFilename = _fileSystem.GetValidFilename(name).Trim();
  710. var existing = RootFolder.RecursiveChildren
  711. .OfType<T>()
  712. .FirstOrDefault(i => string.Equals(_fileSystem.GetValidFilename(i.Name).Trim(), validFilename, StringComparison.OrdinalIgnoreCase));
  713. if (existing != null)
  714. {
  715. return existing;
  716. }
  717. }
  718. var fileInfo = new DirectoryInfo(path);
  719. var isNew = false;
  720. if (!fileInfo.Exists)
  721. {
  722. fileInfo = Directory.CreateDirectory(path);
  723. isNew = true;
  724. }
  725. var item = isNew ? null : GetItemById(id) as T;
  726. if (item == null)
  727. {
  728. item = new T
  729. {
  730. Name = name,
  731. Id = id,
  732. DateCreated = _fileSystem.GetCreationTimeUtc(fileInfo),
  733. DateModified = _fileSystem.GetLastWriteTimeUtc(fileInfo),
  734. Path = path
  735. };
  736. }
  737. if (isArtist)
  738. {
  739. (item as MusicArtist).IsAccessedByName = true;
  740. }
  741. return item;
  742. }
  743. /// <summary>
  744. /// Validate and refresh the People sub-set of the IBN.
  745. /// The items are stored in the db but not loaded into memory until actually requested by an operation.
  746. /// </summary>
  747. /// <param name="cancellationToken">The cancellation token.</param>
  748. /// <param name="progress">The progress.</param>
  749. /// <returns>Task.</returns>
  750. public Task ValidatePeople(CancellationToken cancellationToken, IProgress<double> progress)
  751. {
  752. // Ensure the location is available.
  753. Directory.CreateDirectory(ConfigurationManager.ApplicationPaths.PeoplePath);
  754. return new PeopleValidator(this, _logger, ConfigurationManager).ValidatePeople(cancellationToken, progress);
  755. }
  756. /// <summary>
  757. /// Validates the artists.
  758. /// </summary>
  759. /// <param name="cancellationToken">The cancellation token.</param>
  760. /// <param name="progress">The progress.</param>
  761. /// <returns>Task.</returns>
  762. public Task ValidateArtists(CancellationToken cancellationToken, IProgress<double> progress)
  763. {
  764. // Ensure the location is unavailable.
  765. Directory.CreateDirectory(ConfigurationManager.ApplicationPaths.ArtistsPath);
  766. return new ArtistsValidator(this, _userManager, _logger).Run(progress, cancellationToken);
  767. }
  768. /// <summary>
  769. /// Validates the music genres.
  770. /// </summary>
  771. /// <param name="cancellationToken">The cancellation token.</param>
  772. /// <param name="progress">The progress.</param>
  773. /// <returns>Task.</returns>
  774. public Task ValidateMusicGenres(CancellationToken cancellationToken, IProgress<double> progress)
  775. {
  776. // Ensure the location is unavailable.
  777. Directory.CreateDirectory(ConfigurationManager.ApplicationPaths.MusicGenrePath);
  778. return new MusicGenresValidator(this, _logger).Run(progress, cancellationToken);
  779. }
  780. /// <summary>
  781. /// Validates the game genres.
  782. /// </summary>
  783. /// <param name="cancellationToken">The cancellation token.</param>
  784. /// <param name="progress">The progress.</param>
  785. /// <returns>Task.</returns>
  786. public Task ValidateGameGenres(CancellationToken cancellationToken, IProgress<double> progress)
  787. {
  788. // Ensure the location is unavailable.
  789. Directory.CreateDirectory(ConfigurationManager.ApplicationPaths.GameGenrePath);
  790. return new GameGenresValidator(this, _userManager, _logger).Run(progress, cancellationToken);
  791. }
  792. /// <summary>
  793. /// Validates the studios.
  794. /// </summary>
  795. /// <param name="cancellationToken">The cancellation token.</param>
  796. /// <param name="progress">The progress.</param>
  797. /// <returns>Task.</returns>
  798. public Task ValidateStudios(CancellationToken cancellationToken, IProgress<double> progress)
  799. {
  800. // Ensure the location is unavailable.
  801. Directory.CreateDirectory(ConfigurationManager.ApplicationPaths.StudioPath);
  802. return new StudiosValidator(this, _userManager, _logger).Run(progress, cancellationToken);
  803. }
  804. /// <summary>
  805. /// Validates the genres.
  806. /// </summary>
  807. /// <param name="cancellationToken">The cancellation token.</param>
  808. /// <param name="progress">The progress.</param>
  809. /// <returns>Task.</returns>
  810. public Task ValidateGenres(CancellationToken cancellationToken, IProgress<double> progress)
  811. {
  812. // Ensure the location is unavailable.
  813. Directory.CreateDirectory(ConfigurationManager.ApplicationPaths.GenrePath);
  814. return new GenresValidator(this, _userManager, _logger).Run(progress, cancellationToken);
  815. }
  816. /// <summary>
  817. /// Reloads the root media folder
  818. /// </summary>
  819. /// <param name="progress">The progress.</param>
  820. /// <param name="cancellationToken">The cancellation token.</param>
  821. /// <returns>Task.</returns>
  822. public Task ValidateMediaLibrary(IProgress<double> progress, CancellationToken cancellationToken)
  823. {
  824. // Just run the scheduled task so that the user can see it
  825. _taskManager.CancelIfRunningAndQueue<RefreshMediaLibraryTask>();
  826. return Task.FromResult(true);
  827. }
  828. /// <summary>
  829. /// Queues the library scan.
  830. /// </summary>
  831. public void QueueLibraryScan()
  832. {
  833. // Just run the scheduled task so that the user can see it
  834. _taskManager.QueueScheduledTask<RefreshMediaLibraryTask>();
  835. }
  836. /// <summary>
  837. /// Validates the media library internal.
  838. /// </summary>
  839. /// <param name="progress">The progress.</param>
  840. /// <param name="cancellationToken">The cancellation token.</param>
  841. /// <returns>Task.</returns>
  842. public async Task ValidateMediaLibraryInternal(IProgress<double> progress, CancellationToken cancellationToken)
  843. {
  844. _libraryMonitorFactory().Stop();
  845. try
  846. {
  847. await PerformLibraryValidation(progress, cancellationToken).ConfigureAwait(false);
  848. }
  849. finally
  850. {
  851. _libraryMonitorFactory().Start();
  852. }
  853. }
  854. private async Task PerformLibraryValidation(IProgress<double> progress, CancellationToken cancellationToken)
  855. {
  856. _logger.Info("Validating media library");
  857. await RootFolder.RefreshMetadata(cancellationToken).ConfigureAwait(false);
  858. progress.Report(.5);
  859. // Start by just validating the children of the root, but go no further
  860. await RootFolder.ValidateChildren(new Progress<double>(), cancellationToken, new MetadataRefreshOptions(), recursive: false);
  861. progress.Report(1);
  862. var userRoot = GetUserRootFolder();
  863. await userRoot.RefreshMetadata(cancellationToken).ConfigureAwait(false);
  864. await userRoot.ValidateChildren(new Progress<double>(), cancellationToken, new MetadataRefreshOptions(), recursive: false).ConfigureAwait(false);
  865. progress.Report(2);
  866. var innerProgress = new ActionableProgress<double>();
  867. innerProgress.RegisterAction(pct => progress.Report(2 + pct * .73));
  868. // Now validate the entire media library
  869. await RootFolder.ValidateChildren(innerProgress, cancellationToken, new MetadataRefreshOptions(), recursive: true).ConfigureAwait(false);
  870. progress.Report(75);
  871. innerProgress = new ActionableProgress<double>();
  872. innerProgress.RegisterAction(pct => progress.Report(75 + pct * .25));
  873. // Run post-scan tasks
  874. await RunPostScanTasks(innerProgress, cancellationToken).ConfigureAwait(false);
  875. progress.Report(100);
  876. // Bad practice, i know. But we keep a lot in memory, unfortunately.
  877. GC.Collect(2, GCCollectionMode.Forced, true);
  878. GC.Collect(2, GCCollectionMode.Forced, true);
  879. }
  880. /// <summary>
  881. /// Runs the post scan tasks.
  882. /// </summary>
  883. /// <param name="progress">The progress.</param>
  884. /// <param name="cancellationToken">The cancellation token.</param>
  885. /// <returns>Task.</returns>
  886. private async Task RunPostScanTasks(IProgress<double> progress, CancellationToken cancellationToken)
  887. {
  888. var tasks = PostscanTasks.ToList();
  889. var numComplete = 0;
  890. var numTasks = tasks.Count;
  891. foreach (var task in tasks)
  892. {
  893. var innerProgress = new ActionableProgress<double>();
  894. // Prevent access to modified closure
  895. var currentNumComplete = numComplete;
  896. innerProgress.RegisterAction(pct =>
  897. {
  898. double innerPercent = (currentNumComplete * 100) + pct;
  899. innerPercent /= numTasks;
  900. progress.Report(innerPercent);
  901. });
  902. try
  903. {
  904. await task.Run(innerProgress, cancellationToken);
  905. }
  906. catch (OperationCanceledException)
  907. {
  908. _logger.Info("Post-scan task cancelled: {0}", task.GetType().Name);
  909. }
  910. catch (Exception ex)
  911. {
  912. _logger.ErrorException("Error running postscan task", ex);
  913. }
  914. numComplete++;
  915. double percent = numComplete;
  916. percent /= numTasks;
  917. progress.Report(percent * 100);
  918. }
  919. progress.Report(100);
  920. }
  921. /// <summary>
  922. /// Gets the default view.
  923. /// </summary>
  924. /// <returns>IEnumerable{VirtualFolderInfo}.</returns>
  925. public IEnumerable<VirtualFolderInfo> GetDefaultVirtualFolders()
  926. {
  927. return GetView(ConfigurationManager.ApplicationPaths.DefaultUserViewsPath);
  928. }
  929. /// <summary>
  930. /// Gets the view.
  931. /// </summary>
  932. /// <param name="user">The user.</param>
  933. /// <returns>IEnumerable{VirtualFolderInfo}.</returns>
  934. public IEnumerable<VirtualFolderInfo> GetVirtualFolders(User user)
  935. {
  936. return GetDefaultVirtualFolders();
  937. }
  938. /// <summary>
  939. /// Gets the view.
  940. /// </summary>
  941. /// <param name="path">The path.</param>
  942. /// <returns>IEnumerable{VirtualFolderInfo}.</returns>
  943. private IEnumerable<VirtualFolderInfo> GetView(string path)
  944. {
  945. return Directory.EnumerateDirectories(path, "*", SearchOption.TopDirectoryOnly)
  946. .Select(dir => new VirtualFolderInfo
  947. {
  948. Name = Path.GetFileName(dir),
  949. Locations = Directory.EnumerateFiles(dir, "*.mblink", SearchOption.TopDirectoryOnly)
  950. .Select(_fileSystem.ResolveShortcut)
  951. .OrderBy(i => i)
  952. .ToList(),
  953. CollectionType = GetCollectionType(dir)
  954. });
  955. }
  956. private string GetCollectionType(string path)
  957. {
  958. return new DirectoryInfo(path).EnumerateFiles("*.collection", SearchOption.TopDirectoryOnly)
  959. .Select(i => _fileSystem.GetFileNameWithoutExtension(i))
  960. .FirstOrDefault();
  961. }
  962. /// <summary>
  963. /// Gets the item by id.
  964. /// </summary>
  965. /// <param name="id">The id.</param>
  966. /// <returns>BaseItem.</returns>
  967. /// <exception cref="System.ArgumentNullException">id</exception>
  968. public BaseItem GetItemById(Guid id)
  969. {
  970. if (id == Guid.Empty)
  971. {
  972. throw new ArgumentNullException("id");
  973. }
  974. BaseItem item;
  975. if (LibraryItemsCache.TryGetValue(id, out item))
  976. {
  977. return item;
  978. }
  979. item = RetrieveItem(id);
  980. if (item != null)
  981. {
  982. RegisterItem(item);
  983. }
  984. return item;
  985. }
  986. public BaseItem GetMemoryItemById(Guid id)
  987. {
  988. if (id == Guid.Empty)
  989. {
  990. throw new ArgumentNullException("id");
  991. }
  992. BaseItem item;
  993. LibraryItemsCache.TryGetValue(id, out item);
  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 ? 0 : 1))
  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. var logName = item.LocationType == LocationType.Remote ? item.Name ?? item.Path : item.Path ?? item.Name;
  1204. _logger.Debug("Saving {0} to database.", logName);
  1205. await ItemRepository.SaveItem(item, cancellationToken).ConfigureAwait(false);
  1206. UpdateItemInLibraryCache(item);
  1207. if (ItemUpdated != null)
  1208. {
  1209. try
  1210. {
  1211. ItemUpdated(this, new ItemChangeEventArgs
  1212. {
  1213. Item = item,
  1214. UpdateReason = updateReason
  1215. });
  1216. }
  1217. catch (Exception ex)
  1218. {
  1219. _logger.ErrorException("Error in ItemUpdated event handler", ex);
  1220. }
  1221. }
  1222. }
  1223. /// <summary>
  1224. /// Reports the item removed.
  1225. /// </summary>
  1226. /// <param name="item">The item.</param>
  1227. public void ReportItemRemoved(BaseItem item)
  1228. {
  1229. if (ItemRemoved != null)
  1230. {
  1231. try
  1232. {
  1233. ItemRemoved(this, new ItemChangeEventArgs { Item = item });
  1234. }
  1235. catch (Exception ex)
  1236. {
  1237. _logger.ErrorException("Error in ItemRemoved event handler", ex);
  1238. }
  1239. }
  1240. }
  1241. /// <summary>
  1242. /// Retrieves the item.
  1243. /// </summary>
  1244. /// <param name="id">The id.</param>
  1245. /// <returns>BaseItem.</returns>
  1246. public BaseItem RetrieveItem(Guid id)
  1247. {
  1248. return ItemRepository.RetrieveItem(id);
  1249. }
  1250. /// <summary>
  1251. /// Finds the type of the collection.
  1252. /// </summary>
  1253. /// <param name="item">The item.</param>
  1254. /// <returns>System.String.</returns>
  1255. public string FindCollectionType(BaseItem item)
  1256. {
  1257. while (!(item.Parent is AggregateFolder) && item.Parent != null)
  1258. {
  1259. item = item.Parent;
  1260. }
  1261. if (item == null)
  1262. {
  1263. return null;
  1264. }
  1265. var collectionTypes = GetUserRootFolder().Children
  1266. .OfType<ICollectionFolder>()
  1267. .Where(i => !string.IsNullOrEmpty(i.CollectionType) && (string.Equals(i.Path, item.Path, StringComparison.OrdinalIgnoreCase) || i.PhysicalLocations.Contains(item.Path)))
  1268. .Select(i => i.CollectionType)
  1269. .Distinct()
  1270. .ToList();
  1271. return collectionTypes.Count == 1 ? collectionTypes[0] : null;
  1272. }
  1273. public async Task<UserView> GetNamedView(string name,
  1274. string type,
  1275. string sortName,
  1276. CancellationToken cancellationToken)
  1277. {
  1278. var path = Path.Combine(ConfigurationManager.ApplicationPaths.ItemsByNamePath,
  1279. "views");
  1280. path = Path.Combine(path, _fileSystem.GetValidFilename(type));
  1281. var id = (path + "_namedview_" + name).GetMBId(typeof(UserView));
  1282. var item = GetItemById(id) as UserView;
  1283. var refresh = false;
  1284. if (item == null ||
  1285. !string.Equals(item.Path, path, StringComparison.OrdinalIgnoreCase))
  1286. {
  1287. Directory.CreateDirectory(path);
  1288. item = new UserView
  1289. {
  1290. Path = path,
  1291. Id = id,
  1292. DateCreated = DateTime.UtcNow,
  1293. Name = name,
  1294. ViewType = type,
  1295. ForcedSortName = sortName
  1296. };
  1297. await CreateItem(item, cancellationToken).ConfigureAwait(false);
  1298. refresh = true;
  1299. }
  1300. if (!refresh && item != null)
  1301. {
  1302. refresh = (DateTime.UtcNow - item.DateLastSaved).TotalHours >= 24;
  1303. }
  1304. if (refresh)
  1305. {
  1306. await item.RefreshMetadata(new MetadataRefreshOptions
  1307. {
  1308. ForceSave = true
  1309. }, cancellationToken).ConfigureAwait(false);
  1310. }
  1311. return item;
  1312. }
  1313. public async Task<UserView> GetSpecialFolder(User user,
  1314. string name,
  1315. string parentId,
  1316. string viewType,
  1317. string sortName,
  1318. CancellationToken cancellationToken)
  1319. {
  1320. if (string.IsNullOrWhiteSpace(name))
  1321. {
  1322. throw new ArgumentNullException("name");
  1323. }
  1324. if (string.IsNullOrWhiteSpace(parentId))
  1325. {
  1326. throw new ArgumentNullException("parentId");
  1327. }
  1328. if (string.IsNullOrWhiteSpace(viewType))
  1329. {
  1330. throw new ArgumentNullException("viewType");
  1331. }
  1332. var id = ("7_namedview_" + name + user.Id.ToString("N") + parentId).GetMBId(typeof(UserView));
  1333. var path = BaseItem.GetInternalMetadataPathForId(id);
  1334. var item = GetItemById(id) as UserView;
  1335. var refresh = false;
  1336. if (item == null)
  1337. {
  1338. Directory.CreateDirectory(path);
  1339. item = new UserView
  1340. {
  1341. Path = path,
  1342. Id = id,
  1343. DateCreated = DateTime.UtcNow,
  1344. Name = name,
  1345. ViewType = viewType,
  1346. ForcedSortName = sortName,
  1347. UserId = user.Id,
  1348. ParentId = new Guid(parentId)
  1349. };
  1350. await CreateItem(item, cancellationToken).ConfigureAwait(false);
  1351. refresh = true;
  1352. }
  1353. if (!refresh && item != null)
  1354. {
  1355. refresh = (DateTime.UtcNow - item.DateLastSaved).TotalHours >= 24;
  1356. }
  1357. if (refresh)
  1358. {
  1359. await item.RefreshMetadata(new MetadataRefreshOptions
  1360. {
  1361. ForceSave = true
  1362. }, cancellationToken).ConfigureAwait(false);
  1363. }
  1364. return item;
  1365. }
  1366. }
  1367. }