LibraryManager.cs 54 KB

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