LibraryManager.cs 65 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860
  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.Video;
  22. using MediaBrowser.Server.Implementations.Library.Resolvers.TV;
  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. public Folder GetUserRootFolder()
  631. {
  632. if (_userRootFolder == null)
  633. {
  634. var userRootPath = ConfigurationManager.ApplicationPaths.DefaultUserViewsPath;
  635. Directory.CreateDirectory(userRootPath);
  636. _userRootFolder = GetItemById(GetNewItemId(userRootPath, typeof(UserRootFolder))) as UserRootFolder ??
  637. (UserRootFolder)ResolvePath(new DirectoryInfo(userRootPath));
  638. }
  639. return _userRootFolder;
  640. }
  641. /// <summary>
  642. /// Gets a Person
  643. /// </summary>
  644. /// <param name="name">The name.</param>
  645. /// <returns>Task{Person}.</returns>
  646. public Person GetPerson(string name)
  647. {
  648. return GetItemByName<Person>(ConfigurationManager.ApplicationPaths.PeoplePath, name);
  649. }
  650. /// <summary>
  651. /// Gets a Studio
  652. /// </summary>
  653. /// <param name="name">The name.</param>
  654. /// <returns>Task{Studio}.</returns>
  655. public Studio GetStudio(string name)
  656. {
  657. return GetItemByName<Studio>(ConfigurationManager.ApplicationPaths.StudioPath, name);
  658. }
  659. /// <summary>
  660. /// Gets a Genre
  661. /// </summary>
  662. /// <param name="name">The name.</param>
  663. /// <returns>Task{Genre}.</returns>
  664. public Genre GetGenre(string name)
  665. {
  666. return GetItemByName<Genre>(ConfigurationManager.ApplicationPaths.GenrePath, name);
  667. }
  668. /// <summary>
  669. /// Gets the genre.
  670. /// </summary>
  671. /// <param name="name">The name.</param>
  672. /// <returns>Task{MusicGenre}.</returns>
  673. public MusicGenre GetMusicGenre(string name)
  674. {
  675. return GetItemByName<MusicGenre>(ConfigurationManager.ApplicationPaths.MusicGenrePath, name);
  676. }
  677. /// <summary>
  678. /// Gets the game genre.
  679. /// </summary>
  680. /// <param name="name">The name.</param>
  681. /// <returns>Task{GameGenre}.</returns>
  682. public GameGenre GetGameGenre(string name)
  683. {
  684. return GetItemByName<GameGenre>(ConfigurationManager.ApplicationPaths.GameGenrePath, name);
  685. }
  686. /// <summary>
  687. /// The us culture
  688. /// </summary>
  689. private static readonly CultureInfo UsCulture = new CultureInfo("en-US");
  690. /// <summary>
  691. /// Gets a Year
  692. /// </summary>
  693. /// <param name="value">The value.</param>
  694. /// <returns>Task{Year}.</returns>
  695. /// <exception cref="System.ArgumentOutOfRangeException"></exception>
  696. public Year GetYear(int value)
  697. {
  698. if (value <= 0)
  699. {
  700. throw new ArgumentOutOfRangeException("Years less than or equal to 0 are invalid.");
  701. }
  702. return GetItemByName<Year>(ConfigurationManager.ApplicationPaths.YearPath, value.ToString(UsCulture));
  703. }
  704. /// <summary>
  705. /// Gets a Genre
  706. /// </summary>
  707. /// <param name="name">The name.</param>
  708. /// <returns>Task{Genre}.</returns>
  709. public MusicArtist GetArtist(string name)
  710. {
  711. return GetItemByName<MusicArtist>(ConfigurationManager.ApplicationPaths.ArtistsPath, name);
  712. }
  713. private T GetItemByName<T>(string path, string name)
  714. where T : BaseItem, new()
  715. {
  716. if (string.IsNullOrWhiteSpace(path))
  717. {
  718. throw new ArgumentNullException("path");
  719. }
  720. if (string.IsNullOrWhiteSpace(name))
  721. {
  722. throw new ArgumentNullException("name");
  723. }
  724. var validFilename = _fileSystem.GetValidFilename(name).Trim();
  725. string subFolderPrefix = null;
  726. var type = typeof(T);
  727. if (type == typeof(Person) && ConfigurationManager.Configuration.EnablePeoplePrefixSubFolders)
  728. {
  729. subFolderPrefix = validFilename.Substring(0, 1);
  730. }
  731. var fullPath = string.IsNullOrEmpty(subFolderPrefix) ?
  732. Path.Combine(path, validFilename) :
  733. Path.Combine(path, subFolderPrefix, validFilename);
  734. var id = GetNewItemId(fullPath, type);
  735. BaseItem obj;
  736. if (!_libraryItemsCache.TryGetValue(id, out obj))
  737. {
  738. obj = CreateItemByName<T>(fullPath, name, id);
  739. RegisterItem(id, obj);
  740. }
  741. return obj as T;
  742. }
  743. /// <summary>
  744. /// Creates an IBN item based on a given path
  745. /// </summary>
  746. /// <typeparam name="T"></typeparam>
  747. /// <param name="path">The path.</param>
  748. /// <param name="name">The name.</param>
  749. /// <returns>Task{``0}.</returns>
  750. /// <exception cref="System.IO.IOException">Path not created: + path</exception>
  751. private T CreateItemByName<T>(string path, string name, Guid id)
  752. where T : BaseItem, new()
  753. {
  754. var isArtist = typeof(T) == typeof(MusicArtist);
  755. if (isArtist)
  756. {
  757. var validFilename = _fileSystem.GetValidFilename(name).Trim();
  758. var existing = RootFolder.RecursiveChildren
  759. .OfType<T>()
  760. .FirstOrDefault(i => string.Equals(_fileSystem.GetValidFilename(i.Name).Trim(), validFilename, StringComparison.OrdinalIgnoreCase));
  761. if (existing != null)
  762. {
  763. return existing;
  764. }
  765. }
  766. var fileInfo = new DirectoryInfo(path);
  767. var isNew = false;
  768. if (!fileInfo.Exists)
  769. {
  770. fileInfo = Directory.CreateDirectory(path);
  771. isNew = true;
  772. }
  773. var item = isNew ? null : GetItemById(id) as T;
  774. if (item == null)
  775. {
  776. item = new T
  777. {
  778. Name = name,
  779. Id = id,
  780. DateCreated = _fileSystem.GetCreationTimeUtc(fileInfo),
  781. DateModified = _fileSystem.GetLastWriteTimeUtc(fileInfo),
  782. Path = path
  783. };
  784. }
  785. if (isArtist)
  786. {
  787. (item as MusicArtist).IsAccessedByName = true;
  788. }
  789. return item;
  790. }
  791. /// <summary>
  792. /// Validate and refresh the People sub-set of the IBN.
  793. /// The items are stored in the db but not loaded into memory until actually requested by an operation.
  794. /// </summary>
  795. /// <param name="cancellationToken">The cancellation token.</param>
  796. /// <param name="progress">The progress.</param>
  797. /// <returns>Task.</returns>
  798. public Task ValidatePeople(CancellationToken cancellationToken, IProgress<double> progress)
  799. {
  800. // Ensure the location is available.
  801. Directory.CreateDirectory(ConfigurationManager.ApplicationPaths.PeoplePath);
  802. return new PeopleValidator(this, _logger, ConfigurationManager).ValidatePeople(cancellationToken, progress);
  803. }
  804. /// <summary>
  805. /// Validates the artists.
  806. /// </summary>
  807. /// <param name="cancellationToken">The cancellation token.</param>
  808. /// <param name="progress">The progress.</param>
  809. /// <returns>Task.</returns>
  810. public Task ValidateArtists(CancellationToken cancellationToken, IProgress<double> progress)
  811. {
  812. // Ensure the location is unavailable.
  813. Directory.CreateDirectory(ConfigurationManager.ApplicationPaths.ArtistsPath);
  814. return new ArtistsValidator(this, _userManager, _logger).Run(progress, cancellationToken);
  815. }
  816. /// <summary>
  817. /// Validates the music genres.
  818. /// </summary>
  819. /// <param name="cancellationToken">The cancellation token.</param>
  820. /// <param name="progress">The progress.</param>
  821. /// <returns>Task.</returns>
  822. public Task ValidateMusicGenres(CancellationToken cancellationToken, IProgress<double> progress)
  823. {
  824. // Ensure the location is unavailable.
  825. Directory.CreateDirectory(ConfigurationManager.ApplicationPaths.MusicGenrePath);
  826. return new MusicGenresValidator(this, _logger).Run(progress, cancellationToken);
  827. }
  828. /// <summary>
  829. /// Validates the game genres.
  830. /// </summary>
  831. /// <param name="cancellationToken">The cancellation token.</param>
  832. /// <param name="progress">The progress.</param>
  833. /// <returns>Task.</returns>
  834. public Task ValidateGameGenres(CancellationToken cancellationToken, IProgress<double> progress)
  835. {
  836. // Ensure the location is unavailable.
  837. Directory.CreateDirectory(ConfigurationManager.ApplicationPaths.GameGenrePath);
  838. return new GameGenresValidator(this, _userManager, _logger).Run(progress, cancellationToken);
  839. }
  840. /// <summary>
  841. /// Validates the studios.
  842. /// </summary>
  843. /// <param name="cancellationToken">The cancellation token.</param>
  844. /// <param name="progress">The progress.</param>
  845. /// <returns>Task.</returns>
  846. public Task ValidateStudios(CancellationToken cancellationToken, IProgress<double> progress)
  847. {
  848. // Ensure the location is unavailable.
  849. Directory.CreateDirectory(ConfigurationManager.ApplicationPaths.StudioPath);
  850. return new StudiosValidator(this, _userManager, _logger).Run(progress, cancellationToken);
  851. }
  852. /// <summary>
  853. /// Validates the genres.
  854. /// </summary>
  855. /// <param name="cancellationToken">The cancellation token.</param>
  856. /// <param name="progress">The progress.</param>
  857. /// <returns>Task.</returns>
  858. public Task ValidateGenres(CancellationToken cancellationToken, IProgress<double> progress)
  859. {
  860. // Ensure the location is unavailable.
  861. Directory.CreateDirectory(ConfigurationManager.ApplicationPaths.GenrePath);
  862. return new GenresValidator(this, _userManager, _logger).Run(progress, cancellationToken);
  863. }
  864. /// <summary>
  865. /// Reloads the root media folder
  866. /// </summary>
  867. /// <param name="progress">The progress.</param>
  868. /// <param name="cancellationToken">The cancellation token.</param>
  869. /// <returns>Task.</returns>
  870. public Task ValidateMediaLibrary(IProgress<double> progress, CancellationToken cancellationToken)
  871. {
  872. // Just run the scheduled task so that the user can see it
  873. _taskManager.CancelIfRunningAndQueue<RefreshMediaLibraryTask>();
  874. return Task.FromResult(true);
  875. }
  876. /// <summary>
  877. /// Queues the library scan.
  878. /// </summary>
  879. public void QueueLibraryScan()
  880. {
  881. // Just run the scheduled task so that the user can see it
  882. _taskManager.QueueScheduledTask<RefreshMediaLibraryTask>();
  883. }
  884. /// <summary>
  885. /// Validates the media library internal.
  886. /// </summary>
  887. /// <param name="progress">The progress.</param>
  888. /// <param name="cancellationToken">The cancellation token.</param>
  889. /// <returns>Task.</returns>
  890. public async Task ValidateMediaLibraryInternal(IProgress<double> progress, CancellationToken cancellationToken)
  891. {
  892. _libraryMonitorFactory().Stop();
  893. try
  894. {
  895. await PerformLibraryValidation(progress, cancellationToken).ConfigureAwait(false);
  896. }
  897. finally
  898. {
  899. _libraryMonitorFactory().Start();
  900. }
  901. }
  902. private async Task PerformLibraryValidation(IProgress<double> progress, CancellationToken cancellationToken)
  903. {
  904. _logger.Info("Validating media library");
  905. await RootFolder.RefreshMetadata(cancellationToken).ConfigureAwait(false);
  906. progress.Report(.5);
  907. // Start by just validating the children of the root, but go no further
  908. await RootFolder.ValidateChildren(new Progress<double>(), cancellationToken, new MetadataRefreshOptions(), recursive: false);
  909. progress.Report(1);
  910. var userRoot = GetUserRootFolder();
  911. await userRoot.RefreshMetadata(cancellationToken).ConfigureAwait(false);
  912. await userRoot.ValidateChildren(new Progress<double>(), cancellationToken, new MetadataRefreshOptions(), recursive: false).ConfigureAwait(false);
  913. progress.Report(2);
  914. var innerProgress = new ActionableProgress<double>();
  915. innerProgress.RegisterAction(pct => progress.Report(2 + pct * .73));
  916. // Now validate the entire media library
  917. await RootFolder.ValidateChildren(innerProgress, cancellationToken, new MetadataRefreshOptions(), recursive: true).ConfigureAwait(false);
  918. progress.Report(75);
  919. innerProgress = new ActionableProgress<double>();
  920. innerProgress.RegisterAction(pct => progress.Report(75 + pct * .25));
  921. // Run post-scan tasks
  922. await RunPostScanTasks(innerProgress, cancellationToken).ConfigureAwait(false);
  923. progress.Report(100);
  924. // Bad practice, i know. But we keep a lot in memory, unfortunately.
  925. GC.Collect(2, GCCollectionMode.Forced, true);
  926. GC.Collect(2, GCCollectionMode.Forced, true);
  927. }
  928. /// <summary>
  929. /// Runs the post scan tasks.
  930. /// </summary>
  931. /// <param name="progress">The progress.</param>
  932. /// <param name="cancellationToken">The cancellation token.</param>
  933. /// <returns>Task.</returns>
  934. private async Task RunPostScanTasks(IProgress<double> progress, CancellationToken cancellationToken)
  935. {
  936. var tasks = PostscanTasks.ToList();
  937. var numComplete = 0;
  938. var numTasks = tasks.Count;
  939. foreach (var task in tasks)
  940. {
  941. var innerProgress = new ActionableProgress<double>();
  942. // Prevent access to modified closure
  943. var currentNumComplete = numComplete;
  944. innerProgress.RegisterAction(pct =>
  945. {
  946. double innerPercent = (currentNumComplete * 100) + pct;
  947. innerPercent /= numTasks;
  948. progress.Report(innerPercent);
  949. });
  950. try
  951. {
  952. await task.Run(innerProgress, cancellationToken);
  953. }
  954. catch (OperationCanceledException)
  955. {
  956. _logger.Info("Post-scan task cancelled: {0}", task.GetType().Name);
  957. }
  958. catch (Exception ex)
  959. {
  960. _logger.ErrorException("Error running postscan task", ex);
  961. }
  962. numComplete++;
  963. double percent = numComplete;
  964. percent /= numTasks;
  965. progress.Report(percent * 100);
  966. }
  967. progress.Report(100);
  968. }
  969. /// <summary>
  970. /// Gets the default view.
  971. /// </summary>
  972. /// <returns>IEnumerable{VirtualFolderInfo}.</returns>
  973. public IEnumerable<VirtualFolderInfo> GetDefaultVirtualFolders()
  974. {
  975. return GetView(ConfigurationManager.ApplicationPaths.DefaultUserViewsPath);
  976. }
  977. /// <summary>
  978. /// Gets the view.
  979. /// </summary>
  980. /// <param name="user">The user.</param>
  981. /// <returns>IEnumerable{VirtualFolderInfo}.</returns>
  982. public IEnumerable<VirtualFolderInfo> GetVirtualFolders(User user)
  983. {
  984. return GetDefaultVirtualFolders();
  985. }
  986. /// <summary>
  987. /// Gets the view.
  988. /// </summary>
  989. /// <param name="path">The path.</param>
  990. /// <returns>IEnumerable{VirtualFolderInfo}.</returns>
  991. private IEnumerable<VirtualFolderInfo> GetView(string path)
  992. {
  993. return Directory.EnumerateDirectories(path, "*", SearchOption.TopDirectoryOnly)
  994. .Select(dir => new VirtualFolderInfo
  995. {
  996. Name = Path.GetFileName(dir),
  997. Locations = Directory.EnumerateFiles(dir, "*.mblink", SearchOption.TopDirectoryOnly)
  998. .Select(_fileSystem.ResolveShortcut)
  999. .OrderBy(i => i)
  1000. .ToList(),
  1001. CollectionType = GetCollectionType(dir)
  1002. });
  1003. }
  1004. private string GetCollectionType(string path)
  1005. {
  1006. return new DirectoryInfo(path).EnumerateFiles("*.collection", SearchOption.TopDirectoryOnly)
  1007. .Select(i => _fileSystem.GetFileNameWithoutExtension(i))
  1008. .FirstOrDefault();
  1009. }
  1010. /// <summary>
  1011. /// Gets the item by id.
  1012. /// </summary>
  1013. /// <param name="id">The id.</param>
  1014. /// <returns>BaseItem.</returns>
  1015. /// <exception cref="System.ArgumentNullException">id</exception>
  1016. public BaseItem GetItemById(Guid id)
  1017. {
  1018. if (id == Guid.Empty)
  1019. {
  1020. throw new ArgumentNullException("id");
  1021. }
  1022. BaseItem item;
  1023. if (LibraryItemsCache.TryGetValue(id, out item))
  1024. {
  1025. return item;
  1026. }
  1027. item = RetrieveItem(id);
  1028. if (item != null)
  1029. {
  1030. RegisterItem(item);
  1031. }
  1032. return item;
  1033. }
  1034. public BaseItem GetMemoryItemById(Guid id)
  1035. {
  1036. if (id == Guid.Empty)
  1037. {
  1038. throw new ArgumentNullException("id");
  1039. }
  1040. BaseItem item;
  1041. LibraryItemsCache.TryGetValue(id, out item);
  1042. return item;
  1043. }
  1044. /// <summary>
  1045. /// Gets the intros.
  1046. /// </summary>
  1047. /// <param name="item">The item.</param>
  1048. /// <param name="user">The user.</param>
  1049. /// <returns>IEnumerable{System.String}.</returns>
  1050. public async Task<IEnumerable<Video>> GetIntros(BaseItem item, User user)
  1051. {
  1052. var tasks = IntroProviders
  1053. .OrderBy(i => (i.GetType().Name.IndexOf("Default", StringComparison.OrdinalIgnoreCase) == -1 ? 0 : 1))
  1054. .Take(1)
  1055. .Select(i => GetIntros(i, item, user));
  1056. var items = await Task.WhenAll(tasks).ConfigureAwait(false);
  1057. return items
  1058. .SelectMany(i => i.ToArray())
  1059. .Select(ResolveIntro)
  1060. .Where(i => i != null);
  1061. }
  1062. /// <summary>
  1063. /// Gets the intros.
  1064. /// </summary>
  1065. /// <param name="provider">The provider.</param>
  1066. /// <param name="item">The item.</param>
  1067. /// <param name="user">The user.</param>
  1068. /// <returns>Task&lt;IEnumerable&lt;IntroInfo&gt;&gt;.</returns>
  1069. private async Task<IEnumerable<IntroInfo>> GetIntros(IIntroProvider provider, BaseItem item, User user)
  1070. {
  1071. try
  1072. {
  1073. return await provider.GetIntros(item, user).ConfigureAwait(false);
  1074. }
  1075. catch (Exception ex)
  1076. {
  1077. _logger.ErrorException("Error getting intros", ex);
  1078. return new List<IntroInfo>();
  1079. }
  1080. }
  1081. /// <summary>
  1082. /// Gets all intro files.
  1083. /// </summary>
  1084. /// <returns>IEnumerable{System.String}.</returns>
  1085. public IEnumerable<string> GetAllIntroFiles()
  1086. {
  1087. return IntroProviders.SelectMany(i =>
  1088. {
  1089. try
  1090. {
  1091. return i.GetAllIntroFiles().ToList();
  1092. }
  1093. catch (Exception ex)
  1094. {
  1095. _logger.ErrorException("Error getting intro files", ex);
  1096. return new List<string>();
  1097. }
  1098. });
  1099. }
  1100. /// <summary>
  1101. /// Resolves the intro.
  1102. /// </summary>
  1103. /// <param name="info">The info.</param>
  1104. /// <returns>Video.</returns>
  1105. private Video ResolveIntro(IntroInfo info)
  1106. {
  1107. Video video = null;
  1108. if (info.ItemId.HasValue)
  1109. {
  1110. // Get an existing item by Id
  1111. video = GetItemById(info.ItemId.Value) as Video;
  1112. if (video == null)
  1113. {
  1114. _logger.Error("Unable to locate item with Id {0}.", info.ItemId.Value);
  1115. }
  1116. }
  1117. else if (!string.IsNullOrEmpty(info.Path))
  1118. {
  1119. try
  1120. {
  1121. // Try to resolve the path into a video
  1122. video = ResolvePath(_fileSystem.GetFileSystemInfo(info.Path)) as Video;
  1123. if (video == null)
  1124. {
  1125. _logger.Error("Intro resolver returned null for {0}.", info.Path);
  1126. }
  1127. else
  1128. {
  1129. // Pull the saved db item that will include metadata
  1130. var dbItem = GetItemById(video.Id) as Video;
  1131. if (dbItem != null)
  1132. {
  1133. video = dbItem;
  1134. }
  1135. }
  1136. }
  1137. catch (Exception ex)
  1138. {
  1139. _logger.ErrorException("Error resolving path {0}.", ex, info.Path);
  1140. }
  1141. }
  1142. else
  1143. {
  1144. _logger.Error("IntroProvider returned an IntroInfo with null Path and ItemId.");
  1145. }
  1146. return video;
  1147. }
  1148. /// <summary>
  1149. /// Sorts the specified sort by.
  1150. /// </summary>
  1151. /// <param name="items">The items.</param>
  1152. /// <param name="user">The user.</param>
  1153. /// <param name="sortBy">The sort by.</param>
  1154. /// <param name="sortOrder">The sort order.</param>
  1155. /// <returns>IEnumerable{BaseItem}.</returns>
  1156. public IEnumerable<BaseItem> Sort(IEnumerable<BaseItem> items, User user, IEnumerable<string> sortBy, SortOrder sortOrder)
  1157. {
  1158. var isFirst = true;
  1159. IOrderedEnumerable<BaseItem> orderedItems = null;
  1160. foreach (var orderBy in sortBy.Select(o => GetComparer(o, user)).Where(c => c != null))
  1161. {
  1162. if (isFirst)
  1163. {
  1164. orderedItems = sortOrder == SortOrder.Descending ? items.OrderByDescending(i => i, orderBy) : items.OrderBy(i => i, orderBy);
  1165. }
  1166. else
  1167. {
  1168. orderedItems = sortOrder == SortOrder.Descending ? orderedItems.ThenByDescending(i => i, orderBy) : orderedItems.ThenBy(i => i, orderBy);
  1169. }
  1170. isFirst = false;
  1171. }
  1172. return orderedItems ?? items;
  1173. }
  1174. /// <summary>
  1175. /// Gets the comparer.
  1176. /// </summary>
  1177. /// <param name="name">The name.</param>
  1178. /// <param name="user">The user.</param>
  1179. /// <returns>IBaseItemComparer.</returns>
  1180. private IBaseItemComparer GetComparer(string name, User user)
  1181. {
  1182. var comparer = Comparers.FirstOrDefault(c => string.Equals(name, c.Name, StringComparison.OrdinalIgnoreCase));
  1183. if (comparer != null)
  1184. {
  1185. // If it requires a user, create a new one, and assign the user
  1186. if (comparer is IUserBaseItemComparer)
  1187. {
  1188. var userComparer = (IUserBaseItemComparer)Activator.CreateInstance(comparer.GetType());
  1189. userComparer.User = user;
  1190. userComparer.UserManager = _userManager;
  1191. userComparer.UserDataRepository = _userDataRepository;
  1192. return userComparer;
  1193. }
  1194. }
  1195. return comparer;
  1196. }
  1197. /// <summary>
  1198. /// Creates the item.
  1199. /// </summary>
  1200. /// <param name="item">The item.</param>
  1201. /// <param name="cancellationToken">The cancellation token.</param>
  1202. /// <returns>Task.</returns>
  1203. public Task CreateItem(BaseItem item, CancellationToken cancellationToken)
  1204. {
  1205. return CreateItems(new[] { item }, cancellationToken);
  1206. }
  1207. /// <summary>
  1208. /// Creates the items.
  1209. /// </summary>
  1210. /// <param name="items">The items.</param>
  1211. /// <param name="cancellationToken">The cancellation token.</param>
  1212. /// <returns>Task.</returns>
  1213. public async Task CreateItems(IEnumerable<BaseItem> items, CancellationToken cancellationToken)
  1214. {
  1215. var list = items.ToList();
  1216. await ItemRepository.SaveItems(list, cancellationToken).ConfigureAwait(false);
  1217. foreach (var item in list)
  1218. {
  1219. UpdateItemInLibraryCache(item);
  1220. }
  1221. if (ItemAdded != null)
  1222. {
  1223. foreach (var item in list)
  1224. {
  1225. try
  1226. {
  1227. ItemAdded(this, new ItemChangeEventArgs { Item = item });
  1228. }
  1229. catch (Exception ex)
  1230. {
  1231. _logger.ErrorException("Error in ItemAdded event handler", ex);
  1232. }
  1233. }
  1234. }
  1235. }
  1236. /// <summary>
  1237. /// Updates the item.
  1238. /// </summary>
  1239. /// <param name="item">The item.</param>
  1240. /// <param name="updateReason">The update reason.</param>
  1241. /// <param name="cancellationToken">The cancellation token.</param>
  1242. /// <returns>Task.</returns>
  1243. public async Task UpdateItem(BaseItem item, ItemUpdateType updateReason, CancellationToken cancellationToken)
  1244. {
  1245. var locationType = item.LocationType;
  1246. if (locationType != LocationType.Remote && locationType != LocationType.Virtual)
  1247. {
  1248. await _providerManagerFactory().SaveMetadata(item, updateReason).ConfigureAwait(false);
  1249. }
  1250. item.DateLastSaved = DateTime.UtcNow;
  1251. var logName = item.LocationType == LocationType.Remote ? item.Name ?? item.Path : item.Path ?? item.Name;
  1252. _logger.Debug("Saving {0} to database.", logName);
  1253. await ItemRepository.SaveItem(item, cancellationToken).ConfigureAwait(false);
  1254. UpdateItemInLibraryCache(item);
  1255. if (ItemUpdated != null)
  1256. {
  1257. try
  1258. {
  1259. ItemUpdated(this, new ItemChangeEventArgs
  1260. {
  1261. Item = item,
  1262. UpdateReason = updateReason
  1263. });
  1264. }
  1265. catch (Exception ex)
  1266. {
  1267. _logger.ErrorException("Error in ItemUpdated event handler", ex);
  1268. }
  1269. }
  1270. }
  1271. /// <summary>
  1272. /// Reports the item removed.
  1273. /// </summary>
  1274. /// <param name="item">The item.</param>
  1275. public void ReportItemRemoved(BaseItem item)
  1276. {
  1277. if (ItemRemoved != null)
  1278. {
  1279. try
  1280. {
  1281. ItemRemoved(this, new ItemChangeEventArgs { Item = item });
  1282. }
  1283. catch (Exception ex)
  1284. {
  1285. _logger.ErrorException("Error in ItemRemoved event handler", ex);
  1286. }
  1287. }
  1288. }
  1289. /// <summary>
  1290. /// Retrieves the item.
  1291. /// </summary>
  1292. /// <param name="id">The id.</param>
  1293. /// <returns>BaseItem.</returns>
  1294. public BaseItem RetrieveItem(Guid id)
  1295. {
  1296. return ItemRepository.RetrieveItem(id);
  1297. }
  1298. /// <summary>
  1299. /// Finds the type of the collection.
  1300. /// </summary>
  1301. /// <param name="item">The item.</param>
  1302. /// <returns>System.String.</returns>
  1303. public string FindCollectionType(BaseItem item)
  1304. {
  1305. while (!(item.Parent is AggregateFolder) && item.Parent != null)
  1306. {
  1307. item = item.Parent;
  1308. }
  1309. if (item == null)
  1310. {
  1311. return null;
  1312. }
  1313. var collectionTypes = GetUserRootFolder().Children
  1314. .OfType<ICollectionFolder>()
  1315. .Where(i => !string.IsNullOrEmpty(i.CollectionType) && (string.Equals(i.Path, item.Path, StringComparison.OrdinalIgnoreCase) || i.PhysicalLocations.Contains(item.Path)))
  1316. .Select(i => i.CollectionType)
  1317. .Distinct()
  1318. .ToList();
  1319. return collectionTypes.Count == 1 ? collectionTypes[0] : null;
  1320. }
  1321. public async Task<UserView> GetNamedView(string name,
  1322. string type,
  1323. string sortName,
  1324. CancellationToken cancellationToken)
  1325. {
  1326. var path = Path.Combine(ConfigurationManager.ApplicationPaths.ItemsByNamePath,
  1327. "views");
  1328. path = Path.Combine(path, _fileSystem.GetValidFilename(type));
  1329. var id = GetNewItemId(path + "_namedview_" + name, typeof(UserView));
  1330. var item = GetItemById(id) as UserView;
  1331. var refresh = false;
  1332. if (item == null ||
  1333. !string.Equals(item.Path, path, StringComparison.OrdinalIgnoreCase))
  1334. {
  1335. Directory.CreateDirectory(path);
  1336. item = new UserView
  1337. {
  1338. Path = path,
  1339. Id = id,
  1340. DateCreated = DateTime.UtcNow,
  1341. Name = name,
  1342. ViewType = type,
  1343. ForcedSortName = sortName
  1344. };
  1345. await CreateItem(item, cancellationToken).ConfigureAwait(false);
  1346. refresh = true;
  1347. }
  1348. if (!refresh && item != null)
  1349. {
  1350. refresh = (DateTime.UtcNow - item.DateLastSaved).TotalHours >= 24;
  1351. }
  1352. if (refresh)
  1353. {
  1354. await item.RefreshMetadata(new MetadataRefreshOptions
  1355. {
  1356. ForceSave = true
  1357. }, cancellationToken).ConfigureAwait(false);
  1358. }
  1359. return item;
  1360. }
  1361. public async Task<UserView> GetSpecialFolder(User user,
  1362. string name,
  1363. string parentId,
  1364. string viewType,
  1365. string sortName,
  1366. CancellationToken cancellationToken)
  1367. {
  1368. if (string.IsNullOrWhiteSpace(name))
  1369. {
  1370. throw new ArgumentNullException("name");
  1371. }
  1372. if (string.IsNullOrWhiteSpace(parentId))
  1373. {
  1374. throw new ArgumentNullException("parentId");
  1375. }
  1376. if (string.IsNullOrWhiteSpace(viewType))
  1377. {
  1378. throw new ArgumentNullException("viewType");
  1379. }
  1380. var id = GetNewItemId("7_namedview_" + name + user.Id.ToString("N") + parentId, typeof(UserView));
  1381. var path = BaseItem.GetInternalMetadataPathForId(id);
  1382. var item = GetItemById(id) as UserView;
  1383. var refresh = false;
  1384. if (item == null)
  1385. {
  1386. Directory.CreateDirectory(path);
  1387. item = new UserView
  1388. {
  1389. Path = path,
  1390. Id = id,
  1391. DateCreated = DateTime.UtcNow,
  1392. Name = name,
  1393. ViewType = viewType,
  1394. ForcedSortName = sortName,
  1395. UserId = user.Id,
  1396. ParentId = new Guid(parentId)
  1397. };
  1398. await CreateItem(item, cancellationToken).ConfigureAwait(false);
  1399. refresh = true;
  1400. }
  1401. if (!refresh && item != null)
  1402. {
  1403. refresh = (DateTime.UtcNow - item.DateLastSaved).TotalHours >= 24;
  1404. }
  1405. if (refresh)
  1406. {
  1407. await item.RefreshMetadata(new MetadataRefreshOptions
  1408. {
  1409. ForceSave = true
  1410. }, cancellationToken).ConfigureAwait(false);
  1411. }
  1412. return item;
  1413. }
  1414. public bool IsVideoFile(string path)
  1415. {
  1416. var resolver = new VideoResolver(new ExtendedNamingOptions(), new Naming.Logging.NullLogger());
  1417. return resolver.IsVideoFile(path);
  1418. }
  1419. public bool IsAudioFile(string path)
  1420. {
  1421. var parser = new AudioFileParser(new ExtendedNamingOptions());
  1422. return parser.IsAudioFile(path);
  1423. }
  1424. public int? GetSeasonNumberFromPath(string path)
  1425. {
  1426. return SeriesResolver.GetSeasonNumberFromPath(path);
  1427. }
  1428. public int? GetSeasonNumberFromEpisodeFile(string path)
  1429. {
  1430. return SeriesResolver.GetSeasonNumberFromEpisodeFile(path);
  1431. }
  1432. public int? GetEndingEpisodeNumberFromFile(string path)
  1433. {
  1434. return SeriesResolver.GetEndingEpisodeNumberFromFile(path);
  1435. }
  1436. public int? GetEpisodeNumberFromFile(string path, bool considerSeasonless)
  1437. {
  1438. return SeriesResolver.GetEpisodeNumberFromFile(path, considerSeasonless);
  1439. }
  1440. public ItemLookupInfo ParseName(string name)
  1441. {
  1442. var resolver = new VideoResolver(new ExtendedNamingOptions(), new Naming.Logging.NullLogger());
  1443. var result = resolver.CleanDateTime(name);
  1444. var cleanName = resolver.CleanString(result.Name);
  1445. return new ItemLookupInfo
  1446. {
  1447. Name = cleanName.Name,
  1448. Year = result.Year
  1449. };
  1450. }
  1451. public IEnumerable<Video> FindTrailers(BaseItem owner, List<FileSystemInfo> fileSystemChildren, IDirectoryService directoryService)
  1452. {
  1453. var files = fileSystemChildren.OfType<DirectoryInfo>()
  1454. .Where(i => string.Equals(i.Name, BaseItem.TrailerFolderName, StringComparison.OrdinalIgnoreCase))
  1455. .SelectMany(i => i.EnumerateFiles("*", SearchOption.TopDirectoryOnly))
  1456. .ToList();
  1457. var videoListResolver = new VideoListResolver(new ExtendedNamingOptions(), new Naming.Logging.NullLogger());
  1458. var videos = videoListResolver.Resolve(fileSystemChildren.Select(i => new PortableFileInfo
  1459. {
  1460. FullName = i.FullName,
  1461. Type = GetFileType(i)
  1462. }).ToList());
  1463. var currentVideo = videos.FirstOrDefault(i => string.Equals(owner.Path, i.Files.First().Path, StringComparison.OrdinalIgnoreCase));
  1464. if (currentVideo != null)
  1465. {
  1466. files.AddRange(currentVideo.Extras.Where(i => string.Equals(i.ExtraType, "trailer", StringComparison.OrdinalIgnoreCase)).Select(i => new FileInfo(i.Path)));
  1467. }
  1468. return ResolvePaths(files, directoryService, null, null)
  1469. .OfType<Video>()
  1470. .Select(video =>
  1471. {
  1472. // Try to retrieve it from the db. If we don't find it, use the resolved version
  1473. var dbItem = GetItemById(video.Id) as Video;
  1474. if (dbItem != null)
  1475. {
  1476. video = dbItem;
  1477. }
  1478. video.ExtraType = ExtraType.Trailer;
  1479. return video;
  1480. // Sort them so that the list can be easily compared for changes
  1481. }).OrderBy(i => i.Path).ToList();
  1482. }
  1483. private FileInfoType GetFileType(FileSystemInfo info)
  1484. {
  1485. if ((info.Attributes & FileAttributes.Directory) == FileAttributes.Directory)
  1486. {
  1487. return FileInfoType.Directory;
  1488. }
  1489. return FileInfoType.File;
  1490. }
  1491. public IEnumerable<Video> FindExtras(BaseItem owner, List<FileSystemInfo> fileSystemChildren, IDirectoryService directoryService)
  1492. {
  1493. var files = fileSystemChildren.OfType<DirectoryInfo>()
  1494. .Where(i => string.Equals(i.Name, "extras", StringComparison.OrdinalIgnoreCase) || string.Equals(i.Name, "specials", StringComparison.OrdinalIgnoreCase))
  1495. .SelectMany(i => i.EnumerateFiles("*", SearchOption.TopDirectoryOnly))
  1496. .ToList();
  1497. var videoListResolver = new VideoListResolver(new ExtendedNamingOptions(), new Naming.Logging.NullLogger());
  1498. var videos = videoListResolver.Resolve(fileSystemChildren.Select(i => new PortableFileInfo
  1499. {
  1500. FullName = i.FullName,
  1501. Type = GetFileType(i)
  1502. }).ToList());
  1503. var currentVideo = videos.FirstOrDefault(i => string.Equals(owner.Path, i.Files.First().Path, StringComparison.OrdinalIgnoreCase));
  1504. if (currentVideo != null)
  1505. {
  1506. files.AddRange(currentVideo.Extras.Where(i => !string.Equals(i.ExtraType, "trailer", StringComparison.OrdinalIgnoreCase)).Select(i => new FileInfo(i.Path)));
  1507. }
  1508. return ResolvePaths(files, directoryService, null, null)
  1509. .OfType<Video>()
  1510. .Select(video =>
  1511. {
  1512. // Try to retrieve it from the db. If we don't find it, use the resolved version
  1513. var dbItem = GetItemById(video.Id) as Video;
  1514. if (dbItem != null)
  1515. {
  1516. video = dbItem;
  1517. }
  1518. SetExtraTypeFromFilename(video);
  1519. return video;
  1520. // Sort them so that the list can be easily compared for changes
  1521. }).OrderBy(i => i.Path).ToList();
  1522. }
  1523. private void SetExtraTypeFromFilename(Video item)
  1524. {
  1525. var resolver = new ExtraResolver(new ExtendedNamingOptions(), new Naming.Logging.NullLogger(), new RegexProvider());
  1526. var result = resolver.GetExtraInfo(item.Path);
  1527. if (string.Equals(result.ExtraType, "deletedscene", StringComparison.OrdinalIgnoreCase))
  1528. {
  1529. item.ExtraType = ExtraType.DeletedScene;
  1530. }
  1531. else if (string.Equals(result.ExtraType, "behindthescenes", StringComparison.OrdinalIgnoreCase))
  1532. {
  1533. item.ExtraType = ExtraType.BehindTheScenes;
  1534. }
  1535. else if (string.Equals(result.ExtraType, "interview", StringComparison.OrdinalIgnoreCase))
  1536. {
  1537. item.ExtraType = ExtraType.Interview;
  1538. }
  1539. else if (string.Equals(result.ExtraType, "scene", StringComparison.OrdinalIgnoreCase))
  1540. {
  1541. item.ExtraType = ExtraType.Scene;
  1542. }
  1543. else if (string.Equals(result.ExtraType, "sample", StringComparison.OrdinalIgnoreCase))
  1544. {
  1545. item.ExtraType = ExtraType.Sample;
  1546. }
  1547. else
  1548. {
  1549. item.ExtraType = ExtraType.Clip;
  1550. }
  1551. }
  1552. }
  1553. }