LibraryManager.cs 60 KB

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