LibraryManager.cs 55 KB

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