LibraryManager.cs 67 KB

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