LibraryManager.cs 51 KB

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