LibraryManager.cs 54 KB

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