LibraryManager.cs 52 KB

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