LibraryManager.cs 53 KB

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