LibraryManager.cs 59 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710
  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. public BaseItem ResolveItem(ItemResolveArgs args)
  408. {
  409. var item = EntityResolvers.Select(r =>
  410. {
  411. try
  412. {
  413. return r.ResolvePath(args);
  414. }
  415. catch (Exception ex)
  416. {
  417. _logger.ErrorException("Error in {0} resolving {1}", ex, r.GetType().Name, args.Path);
  418. return null;
  419. }
  420. }).FirstOrDefault(i => i != null);
  421. if (item != null)
  422. {
  423. ResolverHelper.SetInitialItemValues(item, args, _fileSystem);
  424. }
  425. return item;
  426. }
  427. public IEnumerable<BaseItem> ReplaceVideosWithPrimaryVersions(IEnumerable<BaseItem> items)
  428. {
  429. var dict = new Dictionary<Guid, BaseItem>();
  430. foreach (var item in items)
  431. {
  432. var video = item as Video;
  433. if (video != null)
  434. {
  435. if (video.PrimaryVersionId.HasValue)
  436. {
  437. var primary = GetItemById(video.PrimaryVersionId.Value) as Video;
  438. if (primary != null)
  439. {
  440. dict[primary.Id] = primary;
  441. continue;
  442. }
  443. }
  444. }
  445. dict[item.Id] = item;
  446. }
  447. return dict.Values;
  448. }
  449. /// <summary>
  450. /// Ensure supplied item has only one instance throughout
  451. /// </summary>
  452. /// <param name="item">The item.</param>
  453. /// <returns>The proper instance to the item</returns>
  454. public BaseItem GetOrAddByReferenceItem(BaseItem item)
  455. {
  456. // Add this item to our list if not there already
  457. if (!ByReferenceItems.TryAdd(item.Id, item))
  458. {
  459. // Already there - return the existing reference
  460. item = ByReferenceItems[item.Id];
  461. }
  462. return item;
  463. }
  464. public BaseItem ResolvePath(FileSystemInfo fileInfo,
  465. Folder parent = null,
  466. string collectionType = null)
  467. {
  468. return ResolvePath(fileInfo, new DirectoryService(_logger), parent, collectionType);
  469. }
  470. public BaseItem ResolvePath(FileSystemInfo fileInfo, IDirectoryService directoryService, Folder parent = null, string collectionType = null)
  471. {
  472. if (fileInfo == null)
  473. {
  474. throw new ArgumentNullException("fileInfo");
  475. }
  476. var args = new ItemResolveArgs(ConfigurationManager.ApplicationPaths, this, directoryService)
  477. {
  478. Parent = parent,
  479. Path = fileInfo.FullName,
  480. FileInfo = fileInfo,
  481. CollectionType = collectionType
  482. };
  483. // Return null if ignore rules deem that we should do so
  484. if (EntityResolutionIgnoreRules.Any(r => r.ShouldIgnore(args)))
  485. {
  486. return null;
  487. }
  488. // Gather child folder and files
  489. if (args.IsDirectory)
  490. {
  491. var isPhysicalRoot = args.IsPhysicalRoot;
  492. // When resolving the root, we need it's grandchildren (children of user views)
  493. var flattenFolderDepth = isPhysicalRoot ? 2 : 0;
  494. var fileSystemDictionary = FileData.GetFilteredFileSystemEntries(directoryService, args.Path, _fileSystem, _logger, args, flattenFolderDepth: flattenFolderDepth, resolveShortcuts: isPhysicalRoot || args.IsVf);
  495. // Need to remove subpaths that may have been resolved from shortcuts
  496. // Example: if \\server\movies exists, then strip out \\server\movies\action
  497. if (isPhysicalRoot)
  498. {
  499. var paths = NormalizeRootPathList(fileSystemDictionary.Keys);
  500. fileSystemDictionary = paths.Select(i => (FileSystemInfo)new DirectoryInfo(i)).ToDictionary(i => i.FullName);
  501. }
  502. args.FileSystemDictionary = fileSystemDictionary;
  503. }
  504. // Check to see if we should resolve based on our contents
  505. if (args.IsDirectory && !ShouldResolvePathContents(args))
  506. {
  507. return null;
  508. }
  509. return ResolveItem(args);
  510. }
  511. public IEnumerable<string> NormalizeRootPathList(IEnumerable<string> paths)
  512. {
  513. var list = paths.Select(_fileSystem.NormalizePath)
  514. .Distinct(StringComparer.OrdinalIgnoreCase)
  515. .ToList();
  516. var dupes = list.Where(subPath => !subPath.EndsWith(":\\", StringComparison.OrdinalIgnoreCase) && list.Any(i => _fileSystem.ContainsSubPath(i, subPath)))
  517. .ToList();
  518. foreach (var dupe in dupes)
  519. {
  520. _logger.Info("Found duplicate path: {0}", dupe);
  521. }
  522. return list.Except(dupes, StringComparer.OrdinalIgnoreCase);
  523. }
  524. /// <summary>
  525. /// Determines whether a path should be ignored based on its contents - called after the contents have been read
  526. /// </summary>
  527. /// <param name="args">The args.</param>
  528. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  529. private static bool ShouldResolvePathContents(ItemResolveArgs args)
  530. {
  531. // Ignore any folders containing a file called .ignore
  532. return !args.ContainsFileSystemEntryByName(".ignore");
  533. }
  534. public List<T> ResolvePaths<T>(IEnumerable<FileSystemInfo> files, IDirectoryService directoryService, Folder parent, string collectionType = null)
  535. where T : BaseItem
  536. {
  537. return files.Select(f =>
  538. {
  539. try
  540. {
  541. return ResolvePath(f, directoryService, parent, collectionType) as T;
  542. }
  543. catch (Exception ex)
  544. {
  545. _logger.ErrorException("Error resolving path {0}", ex, f.FullName);
  546. return null;
  547. }
  548. }).Where(i => i != null)
  549. .ToList();
  550. }
  551. /// <summary>
  552. /// Creates the root media folder
  553. /// </summary>
  554. /// <returns>AggregateFolder.</returns>
  555. /// <exception cref="System.InvalidOperationException">Cannot create the root folder until plugins have loaded</exception>
  556. public AggregateFolder CreateRootFolder()
  557. {
  558. var rootFolderPath = ConfigurationManager.ApplicationPaths.RootFolderPath;
  559. Directory.CreateDirectory(rootFolderPath);
  560. var rootFolder = GetItemById(rootFolderPath.GetMBId(typeof(AggregateFolder))) as AggregateFolder ?? (AggregateFolder)ResolvePath(new DirectoryInfo(rootFolderPath));
  561. // Add in the plug-in folders
  562. foreach (var child in PluginFolderCreators)
  563. {
  564. var folder = child.GetFolder();
  565. if (folder != null)
  566. {
  567. if (folder.Id == Guid.Empty)
  568. {
  569. folder.Id = (folder.Path ?? folder.GetType().Name).GetMBId(folder.GetType());
  570. }
  571. folder = GetItemById(folder.Id) as BasePluginFolder ?? folder;
  572. rootFolder.AddVirtualChild(folder);
  573. RegisterItem(folder);
  574. }
  575. }
  576. return rootFolder;
  577. }
  578. private UserRootFolder _userRootFolder;
  579. public Folder GetUserRootFolder()
  580. {
  581. if (_userRootFolder == null)
  582. {
  583. var userRootPath = ConfigurationManager.ApplicationPaths.DefaultUserViewsPath;
  584. Directory.CreateDirectory(userRootPath);
  585. _userRootFolder = GetItemById(userRootPath.GetMBId(typeof(UserRootFolder))) as UserRootFolder ??
  586. (UserRootFolder)ResolvePath(new DirectoryInfo(userRootPath));
  587. }
  588. return _userRootFolder;
  589. }
  590. /// <summary>
  591. /// Gets a Person
  592. /// </summary>
  593. /// <param name="name">The name.</param>
  594. /// <returns>Task{Person}.</returns>
  595. public Person GetPerson(string name)
  596. {
  597. return GetItemByName<Person>(ConfigurationManager.ApplicationPaths.PeoplePath, name);
  598. }
  599. /// <summary>
  600. /// Gets a Studio
  601. /// </summary>
  602. /// <param name="name">The name.</param>
  603. /// <returns>Task{Studio}.</returns>
  604. public Studio GetStudio(string name)
  605. {
  606. return GetItemByName<Studio>(ConfigurationManager.ApplicationPaths.StudioPath, name);
  607. }
  608. /// <summary>
  609. /// Gets a Genre
  610. /// </summary>
  611. /// <param name="name">The name.</param>
  612. /// <returns>Task{Genre}.</returns>
  613. public Genre GetGenre(string name)
  614. {
  615. return GetItemByName<Genre>(ConfigurationManager.ApplicationPaths.GenrePath, name);
  616. }
  617. /// <summary>
  618. /// Gets the genre.
  619. /// </summary>
  620. /// <param name="name">The name.</param>
  621. /// <returns>Task{MusicGenre}.</returns>
  622. public MusicGenre GetMusicGenre(string name)
  623. {
  624. return GetItemByName<MusicGenre>(ConfigurationManager.ApplicationPaths.MusicGenrePath, name);
  625. }
  626. /// <summary>
  627. /// Gets the game genre.
  628. /// </summary>
  629. /// <param name="name">The name.</param>
  630. /// <returns>Task{GameGenre}.</returns>
  631. public GameGenre GetGameGenre(string name)
  632. {
  633. return GetItemByName<GameGenre>(ConfigurationManager.ApplicationPaths.GameGenrePath, name);
  634. }
  635. /// <summary>
  636. /// The us culture
  637. /// </summary>
  638. private static readonly CultureInfo UsCulture = new CultureInfo("en-US");
  639. /// <summary>
  640. /// Gets a Year
  641. /// </summary>
  642. /// <param name="value">The value.</param>
  643. /// <returns>Task{Year}.</returns>
  644. /// <exception cref="System.ArgumentOutOfRangeException"></exception>
  645. public Year GetYear(int value)
  646. {
  647. if (value <= 0)
  648. {
  649. throw new ArgumentOutOfRangeException("Years less than or equal to 0 are invalid.");
  650. }
  651. return GetItemByName<Year>(ConfigurationManager.ApplicationPaths.YearPath, value.ToString(UsCulture));
  652. }
  653. /// <summary>
  654. /// Gets a Genre
  655. /// </summary>
  656. /// <param name="name">The name.</param>
  657. /// <returns>Task{Genre}.</returns>
  658. public MusicArtist GetArtist(string name)
  659. {
  660. return GetItemByName<MusicArtist>(ConfigurationManager.ApplicationPaths.ArtistsPath, name);
  661. }
  662. private T GetItemByName<T>(string path, string name)
  663. where T : BaseItem, new()
  664. {
  665. if (string.IsNullOrWhiteSpace(path))
  666. {
  667. throw new ArgumentNullException("path");
  668. }
  669. if (string.IsNullOrWhiteSpace(name))
  670. {
  671. throw new ArgumentNullException("name");
  672. }
  673. var validFilename = _fileSystem.GetValidFilename(name).Trim();
  674. string subFolderPrefix = null;
  675. var type = typeof(T);
  676. if (type == typeof(Person) && ConfigurationManager.Configuration.EnablePeoplePrefixSubFolders)
  677. {
  678. subFolderPrefix = validFilename.Substring(0, 1);
  679. }
  680. var fullPath = string.IsNullOrEmpty(subFolderPrefix) ?
  681. Path.Combine(path, validFilename) :
  682. Path.Combine(path, subFolderPrefix, validFilename);
  683. var id = fullPath.GetMBId(type);
  684. BaseItem obj;
  685. if (!_libraryItemsCache.TryGetValue(id, out obj))
  686. {
  687. obj = CreateItemByName<T>(fullPath, name, id);
  688. RegisterItem(id, obj);
  689. }
  690. return obj as T;
  691. }
  692. /// <summary>
  693. /// Creates an IBN item based on a given path
  694. /// </summary>
  695. /// <typeparam name="T"></typeparam>
  696. /// <param name="path">The path.</param>
  697. /// <param name="name">The name.</param>
  698. /// <returns>Task{``0}.</returns>
  699. /// <exception cref="System.IO.IOException">Path not created: + path</exception>
  700. private T CreateItemByName<T>(string path, string name, Guid id)
  701. where T : BaseItem, new()
  702. {
  703. var isArtist = typeof(T) == typeof(MusicArtist);
  704. if (isArtist)
  705. {
  706. var validFilename = _fileSystem.GetValidFilename(name).Trim();
  707. var existing = RootFolder.RecursiveChildren
  708. .OfType<T>()
  709. .FirstOrDefault(i => string.Equals(_fileSystem.GetValidFilename(i.Name).Trim(), validFilename, StringComparison.OrdinalIgnoreCase));
  710. if (existing != null)
  711. {
  712. return existing;
  713. }
  714. }
  715. var fileInfo = new DirectoryInfo(path);
  716. var isNew = false;
  717. if (!fileInfo.Exists)
  718. {
  719. fileInfo = Directory.CreateDirectory(path);
  720. isNew = true;
  721. }
  722. var item = isNew ? null : GetItemById(id) as T;
  723. if (item == null)
  724. {
  725. item = new T
  726. {
  727. Name = name,
  728. Id = id,
  729. DateCreated = _fileSystem.GetCreationTimeUtc(fileInfo),
  730. DateModified = _fileSystem.GetLastWriteTimeUtc(fileInfo),
  731. Path = path
  732. };
  733. }
  734. if (isArtist)
  735. {
  736. (item as MusicArtist).IsAccessedByName = true;
  737. }
  738. return item;
  739. }
  740. /// <summary>
  741. /// Validate and refresh the People sub-set of the IBN.
  742. /// The items are stored in the db but not loaded into memory until actually requested by an operation.
  743. /// </summary>
  744. /// <param name="cancellationToken">The cancellation token.</param>
  745. /// <param name="progress">The progress.</param>
  746. /// <returns>Task.</returns>
  747. public Task ValidatePeople(CancellationToken cancellationToken, IProgress<double> progress)
  748. {
  749. // Ensure the location is available.
  750. Directory.CreateDirectory(ConfigurationManager.ApplicationPaths.PeoplePath);
  751. return new PeopleValidator(this, _logger, ConfigurationManager).ValidatePeople(cancellationToken, progress);
  752. }
  753. /// <summary>
  754. /// Validates the artists.
  755. /// </summary>
  756. /// <param name="cancellationToken">The cancellation token.</param>
  757. /// <param name="progress">The progress.</param>
  758. /// <returns>Task.</returns>
  759. public Task ValidateArtists(CancellationToken cancellationToken, IProgress<double> progress)
  760. {
  761. // Ensure the location is unavailable.
  762. Directory.CreateDirectory(ConfigurationManager.ApplicationPaths.ArtistsPath);
  763. return new ArtistsValidator(this, _userManager, _logger).Run(progress, cancellationToken);
  764. }
  765. /// <summary>
  766. /// Validates the music genres.
  767. /// </summary>
  768. /// <param name="cancellationToken">The cancellation token.</param>
  769. /// <param name="progress">The progress.</param>
  770. /// <returns>Task.</returns>
  771. public Task ValidateMusicGenres(CancellationToken cancellationToken, IProgress<double> progress)
  772. {
  773. // Ensure the location is unavailable.
  774. Directory.CreateDirectory(ConfigurationManager.ApplicationPaths.MusicGenrePath);
  775. return new MusicGenresValidator(this, _logger).Run(progress, cancellationToken);
  776. }
  777. /// <summary>
  778. /// Validates the game genres.
  779. /// </summary>
  780. /// <param name="cancellationToken">The cancellation token.</param>
  781. /// <param name="progress">The progress.</param>
  782. /// <returns>Task.</returns>
  783. public Task ValidateGameGenres(CancellationToken cancellationToken, IProgress<double> progress)
  784. {
  785. // Ensure the location is unavailable.
  786. Directory.CreateDirectory(ConfigurationManager.ApplicationPaths.GameGenrePath);
  787. return new GameGenresValidator(this, _userManager, _logger).Run(progress, cancellationToken);
  788. }
  789. /// <summary>
  790. /// Validates the studios.
  791. /// </summary>
  792. /// <param name="cancellationToken">The cancellation token.</param>
  793. /// <param name="progress">The progress.</param>
  794. /// <returns>Task.</returns>
  795. public Task ValidateStudios(CancellationToken cancellationToken, IProgress<double> progress)
  796. {
  797. // Ensure the location is unavailable.
  798. Directory.CreateDirectory(ConfigurationManager.ApplicationPaths.StudioPath);
  799. return new StudiosValidator(this, _userManager, _logger).Run(progress, cancellationToken);
  800. }
  801. /// <summary>
  802. /// Validates the genres.
  803. /// </summary>
  804. /// <param name="cancellationToken">The cancellation token.</param>
  805. /// <param name="progress">The progress.</param>
  806. /// <returns>Task.</returns>
  807. public Task ValidateGenres(CancellationToken cancellationToken, IProgress<double> progress)
  808. {
  809. // Ensure the location is unavailable.
  810. Directory.CreateDirectory(ConfigurationManager.ApplicationPaths.GenrePath);
  811. return new GenresValidator(this, _userManager, _logger).Run(progress, cancellationToken);
  812. }
  813. /// <summary>
  814. /// Reloads the root media folder
  815. /// </summary>
  816. /// <param name="progress">The progress.</param>
  817. /// <param name="cancellationToken">The cancellation token.</param>
  818. /// <returns>Task.</returns>
  819. public Task ValidateMediaLibrary(IProgress<double> progress, CancellationToken cancellationToken)
  820. {
  821. // Just run the scheduled task so that the user can see it
  822. _taskManager.CancelIfRunningAndQueue<RefreshMediaLibraryTask>();
  823. return Task.FromResult(true);
  824. }
  825. /// <summary>
  826. /// Queues the library scan.
  827. /// </summary>
  828. public void QueueLibraryScan()
  829. {
  830. // Just run the scheduled task so that the user can see it
  831. _taskManager.QueueScheduledTask<RefreshMediaLibraryTask>();
  832. }
  833. /// <summary>
  834. /// Validates the media library internal.
  835. /// </summary>
  836. /// <param name="progress">The progress.</param>
  837. /// <param name="cancellationToken">The cancellation token.</param>
  838. /// <returns>Task.</returns>
  839. public async Task ValidateMediaLibraryInternal(IProgress<double> progress, CancellationToken cancellationToken)
  840. {
  841. _libraryMonitorFactory().Stop();
  842. try
  843. {
  844. await PerformLibraryValidation(progress, cancellationToken).ConfigureAwait(false);
  845. }
  846. finally
  847. {
  848. _libraryMonitorFactory().Start();
  849. }
  850. }
  851. private async Task PerformLibraryValidation(IProgress<double> progress, CancellationToken cancellationToken)
  852. {
  853. _logger.Info("Validating media library");
  854. await RootFolder.RefreshMetadata(cancellationToken).ConfigureAwait(false);
  855. progress.Report(.5);
  856. // Start by just validating the children of the root, but go no further
  857. await RootFolder.ValidateChildren(new Progress<double>(), cancellationToken, new MetadataRefreshOptions(), recursive: false);
  858. progress.Report(1);
  859. var userRoot = GetUserRootFolder();
  860. await userRoot.RefreshMetadata(cancellationToken).ConfigureAwait(false);
  861. await userRoot.ValidateChildren(new Progress<double>(), cancellationToken, new MetadataRefreshOptions(), recursive: false).ConfigureAwait(false);
  862. progress.Report(2);
  863. var innerProgress = new ActionableProgress<double>();
  864. innerProgress.RegisterAction(pct => progress.Report(2 + pct * .73));
  865. // Now validate the entire media library
  866. await RootFolder.ValidateChildren(innerProgress, cancellationToken, new MetadataRefreshOptions(), recursive: true).ConfigureAwait(false);
  867. progress.Report(75);
  868. innerProgress = new ActionableProgress<double>();
  869. innerProgress.RegisterAction(pct => progress.Report(75 + pct * .25));
  870. // Run post-scan tasks
  871. await RunPostScanTasks(innerProgress, cancellationToken).ConfigureAwait(false);
  872. progress.Report(100);
  873. // Bad practice, i know. But we keep a lot in memory, unfortunately.
  874. GC.Collect(2, GCCollectionMode.Forced, true);
  875. GC.Collect(2, GCCollectionMode.Forced, true);
  876. }
  877. /// <summary>
  878. /// Runs the post scan tasks.
  879. /// </summary>
  880. /// <param name="progress">The progress.</param>
  881. /// <param name="cancellationToken">The cancellation token.</param>
  882. /// <returns>Task.</returns>
  883. private async Task RunPostScanTasks(IProgress<double> progress, CancellationToken cancellationToken)
  884. {
  885. var tasks = PostscanTasks.ToList();
  886. var numComplete = 0;
  887. var numTasks = tasks.Count;
  888. foreach (var task in tasks)
  889. {
  890. var innerProgress = new ActionableProgress<double>();
  891. // Prevent access to modified closure
  892. var currentNumComplete = numComplete;
  893. innerProgress.RegisterAction(pct =>
  894. {
  895. double innerPercent = (currentNumComplete * 100) + pct;
  896. innerPercent /= numTasks;
  897. progress.Report(innerPercent);
  898. });
  899. try
  900. {
  901. await task.Run(innerProgress, cancellationToken);
  902. }
  903. catch (OperationCanceledException)
  904. {
  905. _logger.Info("Post-scan task cancelled: {0}", task.GetType().Name);
  906. }
  907. catch (Exception ex)
  908. {
  909. _logger.ErrorException("Error running postscan task", ex);
  910. }
  911. numComplete++;
  912. double percent = numComplete;
  913. percent /= numTasks;
  914. progress.Report(percent * 100);
  915. }
  916. progress.Report(100);
  917. }
  918. /// <summary>
  919. /// Gets the default view.
  920. /// </summary>
  921. /// <returns>IEnumerable{VirtualFolderInfo}.</returns>
  922. public IEnumerable<VirtualFolderInfo> GetDefaultVirtualFolders()
  923. {
  924. return GetView(ConfigurationManager.ApplicationPaths.DefaultUserViewsPath);
  925. }
  926. /// <summary>
  927. /// Gets the view.
  928. /// </summary>
  929. /// <param name="user">The user.</param>
  930. /// <returns>IEnumerable{VirtualFolderInfo}.</returns>
  931. public IEnumerable<VirtualFolderInfo> GetVirtualFolders(User user)
  932. {
  933. return GetDefaultVirtualFolders();
  934. }
  935. /// <summary>
  936. /// Gets the view.
  937. /// </summary>
  938. /// <param name="path">The path.</param>
  939. /// <returns>IEnumerable{VirtualFolderInfo}.</returns>
  940. private IEnumerable<VirtualFolderInfo> GetView(string path)
  941. {
  942. return Directory.EnumerateDirectories(path, "*", SearchOption.TopDirectoryOnly)
  943. .Select(dir => new VirtualFolderInfo
  944. {
  945. Name = Path.GetFileName(dir),
  946. Locations = Directory.EnumerateFiles(dir, "*.mblink", SearchOption.TopDirectoryOnly)
  947. .Select(_fileSystem.ResolveShortcut)
  948. .OrderBy(i => i)
  949. .ToList(),
  950. CollectionType = GetCollectionType(dir)
  951. });
  952. }
  953. private string GetCollectionType(string path)
  954. {
  955. return new DirectoryInfo(path).EnumerateFiles("*.collection", SearchOption.TopDirectoryOnly)
  956. .Select(i => _fileSystem.GetFileNameWithoutExtension(i))
  957. .FirstOrDefault();
  958. }
  959. /// <summary>
  960. /// Gets the item by id.
  961. /// </summary>
  962. /// <param name="id">The id.</param>
  963. /// <returns>BaseItem.</returns>
  964. /// <exception cref="System.ArgumentNullException">id</exception>
  965. public BaseItem GetItemById(Guid id)
  966. {
  967. if (id == Guid.Empty)
  968. {
  969. throw new ArgumentNullException("id");
  970. }
  971. BaseItem item;
  972. if (LibraryItemsCache.TryGetValue(id, out item))
  973. {
  974. return item;
  975. }
  976. item = RetrieveItem(id);
  977. if (item != null)
  978. {
  979. RegisterItem(item);
  980. }
  981. return item;
  982. }
  983. public BaseItem GetMemoryItemById(Guid id)
  984. {
  985. if (id == Guid.Empty)
  986. {
  987. throw new ArgumentNullException("id");
  988. }
  989. BaseItem item;
  990. LibraryItemsCache.TryGetValue(id, out item);
  991. return item;
  992. }
  993. /// <summary>
  994. /// Gets the intros.
  995. /// </summary>
  996. /// <param name="item">The item.</param>
  997. /// <param name="user">The user.</param>
  998. /// <returns>IEnumerable{System.String}.</returns>
  999. public async Task<IEnumerable<Video>> GetIntros(BaseItem item, User user)
  1000. {
  1001. var tasks = IntroProviders
  1002. .OrderBy(i => (i.GetType().Name.IndexOf("Default", StringComparison.OrdinalIgnoreCase) == -1 ? 0 : 1))
  1003. .Take(1)
  1004. .Select(i => GetIntros(i, item, user));
  1005. var items = await Task.WhenAll(tasks).ConfigureAwait(false);
  1006. return items
  1007. .SelectMany(i => i.ToArray())
  1008. .Select(ResolveIntro)
  1009. .Where(i => i != null);
  1010. }
  1011. /// <summary>
  1012. /// Gets the intros.
  1013. /// </summary>
  1014. /// <param name="provider">The provider.</param>
  1015. /// <param name="item">The item.</param>
  1016. /// <param name="user">The user.</param>
  1017. /// <returns>Task&lt;IEnumerable&lt;IntroInfo&gt;&gt;.</returns>
  1018. private async Task<IEnumerable<IntroInfo>> GetIntros(IIntroProvider provider, BaseItem item, User user)
  1019. {
  1020. try
  1021. {
  1022. return await provider.GetIntros(item, user).ConfigureAwait(false);
  1023. }
  1024. catch (Exception ex)
  1025. {
  1026. _logger.ErrorException("Error getting intros", ex);
  1027. return new List<IntroInfo>();
  1028. }
  1029. }
  1030. /// <summary>
  1031. /// Gets all intro files.
  1032. /// </summary>
  1033. /// <returns>IEnumerable{System.String}.</returns>
  1034. public IEnumerable<string> GetAllIntroFiles()
  1035. {
  1036. return IntroProviders.SelectMany(i =>
  1037. {
  1038. try
  1039. {
  1040. return i.GetAllIntroFiles().ToList();
  1041. }
  1042. catch (Exception ex)
  1043. {
  1044. _logger.ErrorException("Error getting intro files", ex);
  1045. return new List<string>();
  1046. }
  1047. });
  1048. }
  1049. /// <summary>
  1050. /// Resolves the intro.
  1051. /// </summary>
  1052. /// <param name="info">The info.</param>
  1053. /// <returns>Video.</returns>
  1054. private Video ResolveIntro(IntroInfo info)
  1055. {
  1056. Video video = null;
  1057. if (info.ItemId.HasValue)
  1058. {
  1059. // Get an existing item by Id
  1060. video = GetItemById(info.ItemId.Value) as Video;
  1061. if (video == null)
  1062. {
  1063. _logger.Error("Unable to locate item with Id {0}.", info.ItemId.Value);
  1064. }
  1065. }
  1066. else if (!string.IsNullOrEmpty(info.Path))
  1067. {
  1068. try
  1069. {
  1070. // Try to resolve the path into a video
  1071. video = ResolvePath(_fileSystem.GetFileSystemInfo(info.Path)) as Video;
  1072. if (video == null)
  1073. {
  1074. _logger.Error("Intro resolver returned null for {0}.", info.Path);
  1075. }
  1076. else
  1077. {
  1078. // Pull the saved db item that will include metadata
  1079. var dbItem = GetItemById(video.Id) as Video;
  1080. if (dbItem != null)
  1081. {
  1082. video = dbItem;
  1083. }
  1084. }
  1085. }
  1086. catch (Exception ex)
  1087. {
  1088. _logger.ErrorException("Error resolving path {0}.", ex, info.Path);
  1089. }
  1090. }
  1091. else
  1092. {
  1093. _logger.Error("IntroProvider returned an IntroInfo with null Path and ItemId.");
  1094. }
  1095. return video;
  1096. }
  1097. /// <summary>
  1098. /// Sorts the specified sort by.
  1099. /// </summary>
  1100. /// <param name="items">The items.</param>
  1101. /// <param name="user">The user.</param>
  1102. /// <param name="sortBy">The sort by.</param>
  1103. /// <param name="sortOrder">The sort order.</param>
  1104. /// <returns>IEnumerable{BaseItem}.</returns>
  1105. public IEnumerable<BaseItem> Sort(IEnumerable<BaseItem> items, User user, IEnumerable<string> sortBy, SortOrder sortOrder)
  1106. {
  1107. var isFirst = true;
  1108. IOrderedEnumerable<BaseItem> orderedItems = null;
  1109. foreach (var orderBy in sortBy.Select(o => GetComparer(o, user)).Where(c => c != null))
  1110. {
  1111. if (isFirst)
  1112. {
  1113. orderedItems = sortOrder == SortOrder.Descending ? items.OrderByDescending(i => i, orderBy) : items.OrderBy(i => i, orderBy);
  1114. }
  1115. else
  1116. {
  1117. orderedItems = sortOrder == SortOrder.Descending ? orderedItems.ThenByDescending(i => i, orderBy) : orderedItems.ThenBy(i => i, orderBy);
  1118. }
  1119. isFirst = false;
  1120. }
  1121. return orderedItems ?? items;
  1122. }
  1123. /// <summary>
  1124. /// Gets the comparer.
  1125. /// </summary>
  1126. /// <param name="name">The name.</param>
  1127. /// <param name="user">The user.</param>
  1128. /// <returns>IBaseItemComparer.</returns>
  1129. private IBaseItemComparer GetComparer(string name, User user)
  1130. {
  1131. var comparer = Comparers.FirstOrDefault(c => string.Equals(name, c.Name, StringComparison.OrdinalIgnoreCase));
  1132. if (comparer != null)
  1133. {
  1134. // If it requires a user, create a new one, and assign the user
  1135. if (comparer is IUserBaseItemComparer)
  1136. {
  1137. var userComparer = (IUserBaseItemComparer)Activator.CreateInstance(comparer.GetType());
  1138. userComparer.User = user;
  1139. userComparer.UserManager = _userManager;
  1140. userComparer.UserDataRepository = _userDataRepository;
  1141. return userComparer;
  1142. }
  1143. }
  1144. return comparer;
  1145. }
  1146. /// <summary>
  1147. /// Creates the item.
  1148. /// </summary>
  1149. /// <param name="item">The item.</param>
  1150. /// <param name="cancellationToken">The cancellation token.</param>
  1151. /// <returns>Task.</returns>
  1152. public Task CreateItem(BaseItem item, CancellationToken cancellationToken)
  1153. {
  1154. return CreateItems(new[] { item }, cancellationToken);
  1155. }
  1156. /// <summary>
  1157. /// Creates the items.
  1158. /// </summary>
  1159. /// <param name="items">The items.</param>
  1160. /// <param name="cancellationToken">The cancellation token.</param>
  1161. /// <returns>Task.</returns>
  1162. public async Task CreateItems(IEnumerable<BaseItem> items, CancellationToken cancellationToken)
  1163. {
  1164. var list = items.ToList();
  1165. await ItemRepository.SaveItems(list, cancellationToken).ConfigureAwait(false);
  1166. foreach (var item in list)
  1167. {
  1168. UpdateItemInLibraryCache(item);
  1169. }
  1170. if (ItemAdded != null)
  1171. {
  1172. foreach (var item in list)
  1173. {
  1174. try
  1175. {
  1176. ItemAdded(this, new ItemChangeEventArgs { Item = item });
  1177. }
  1178. catch (Exception ex)
  1179. {
  1180. _logger.ErrorException("Error in ItemAdded event handler", ex);
  1181. }
  1182. }
  1183. }
  1184. }
  1185. /// <summary>
  1186. /// Updates the item.
  1187. /// </summary>
  1188. /// <param name="item">The item.</param>
  1189. /// <param name="updateReason">The update reason.</param>
  1190. /// <param name="cancellationToken">The cancellation token.</param>
  1191. /// <returns>Task.</returns>
  1192. public async Task UpdateItem(BaseItem item, ItemUpdateType updateReason, CancellationToken cancellationToken)
  1193. {
  1194. var locationType = item.LocationType;
  1195. if (locationType != LocationType.Remote && locationType != LocationType.Virtual)
  1196. {
  1197. await _providerManagerFactory().SaveMetadata(item, updateReason).ConfigureAwait(false);
  1198. }
  1199. item.DateLastSaved = DateTime.UtcNow;
  1200. var logName = item.LocationType == LocationType.Remote ? item.Name ?? item.Path : item.Path ?? item.Name;
  1201. _logger.Debug("Saving {0} to database.", logName);
  1202. await ItemRepository.SaveItem(item, cancellationToken).ConfigureAwait(false);
  1203. UpdateItemInLibraryCache(item);
  1204. if (ItemUpdated != null)
  1205. {
  1206. try
  1207. {
  1208. ItemUpdated(this, new ItemChangeEventArgs
  1209. {
  1210. Item = item,
  1211. UpdateReason = updateReason
  1212. });
  1213. }
  1214. catch (Exception ex)
  1215. {
  1216. _logger.ErrorException("Error in ItemUpdated event handler", ex);
  1217. }
  1218. }
  1219. }
  1220. /// <summary>
  1221. /// Reports the item removed.
  1222. /// </summary>
  1223. /// <param name="item">The item.</param>
  1224. public void ReportItemRemoved(BaseItem item)
  1225. {
  1226. if (ItemRemoved != null)
  1227. {
  1228. try
  1229. {
  1230. ItemRemoved(this, new ItemChangeEventArgs { Item = item });
  1231. }
  1232. catch (Exception ex)
  1233. {
  1234. _logger.ErrorException("Error in ItemRemoved event handler", ex);
  1235. }
  1236. }
  1237. }
  1238. /// <summary>
  1239. /// Retrieves the item.
  1240. /// </summary>
  1241. /// <param name="id">The id.</param>
  1242. /// <returns>BaseItem.</returns>
  1243. public BaseItem RetrieveItem(Guid id)
  1244. {
  1245. return ItemRepository.RetrieveItem(id);
  1246. }
  1247. /// <summary>
  1248. /// Finds the type of the collection.
  1249. /// </summary>
  1250. /// <param name="item">The item.</param>
  1251. /// <returns>System.String.</returns>
  1252. public string FindCollectionType(BaseItem item)
  1253. {
  1254. while (!(item.Parent is AggregateFolder) && item.Parent != null)
  1255. {
  1256. item = item.Parent;
  1257. }
  1258. if (item == null)
  1259. {
  1260. return null;
  1261. }
  1262. var collectionTypes = GetUserRootFolder().Children
  1263. .OfType<ICollectionFolder>()
  1264. .Where(i => !string.IsNullOrEmpty(i.CollectionType) && (string.Equals(i.Path, item.Path, StringComparison.OrdinalIgnoreCase) || i.PhysicalLocations.Contains(item.Path)))
  1265. .Select(i => i.CollectionType)
  1266. .Distinct()
  1267. .ToList();
  1268. return collectionTypes.Count == 1 ? collectionTypes[0] : null;
  1269. }
  1270. public async Task<UserView> GetNamedView(string name,
  1271. string type,
  1272. string sortName,
  1273. CancellationToken cancellationToken)
  1274. {
  1275. var path = Path.Combine(ConfigurationManager.ApplicationPaths.ItemsByNamePath,
  1276. "views");
  1277. path = Path.Combine(path, _fileSystem.GetValidFilename(type));
  1278. var id = (path + "_namedview_" + name).GetMBId(typeof(UserView));
  1279. var item = GetItemById(id) as UserView;
  1280. var refresh = false;
  1281. if (item == null ||
  1282. !string.Equals(item.Path, path, StringComparison.OrdinalIgnoreCase))
  1283. {
  1284. Directory.CreateDirectory(path);
  1285. item = new UserView
  1286. {
  1287. Path = path,
  1288. Id = id,
  1289. DateCreated = DateTime.UtcNow,
  1290. Name = name,
  1291. ViewType = type,
  1292. ForcedSortName = sortName
  1293. };
  1294. await CreateItem(item, cancellationToken).ConfigureAwait(false);
  1295. refresh = true;
  1296. }
  1297. if (!refresh && item != null)
  1298. {
  1299. refresh = (DateTime.UtcNow - item.DateLastSaved).TotalHours >= 24;
  1300. }
  1301. if (refresh)
  1302. {
  1303. await item.RefreshMetadata(new MetadataRefreshOptions
  1304. {
  1305. ForceSave = true
  1306. }, cancellationToken).ConfigureAwait(false);
  1307. }
  1308. return item;
  1309. }
  1310. public async Task<UserView> GetSpecialFolder(User user,
  1311. string name,
  1312. string parentId,
  1313. string viewType,
  1314. string sortName,
  1315. CancellationToken cancellationToken)
  1316. {
  1317. if (string.IsNullOrWhiteSpace(name))
  1318. {
  1319. throw new ArgumentNullException("name");
  1320. }
  1321. if (string.IsNullOrWhiteSpace(parentId))
  1322. {
  1323. throw new ArgumentNullException("parentId");
  1324. }
  1325. if (string.IsNullOrWhiteSpace(viewType))
  1326. {
  1327. throw new ArgumentNullException("viewType");
  1328. }
  1329. var id = ("7_namedview_" + name + user.Id.ToString("N") + parentId).GetMBId(typeof(UserView));
  1330. var path = BaseItem.GetInternalMetadataPathForId(id);
  1331. var item = GetItemById(id) as UserView;
  1332. var refresh = false;
  1333. if (item == null)
  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 = viewType,
  1343. ForcedSortName = sortName,
  1344. UserId = user.Id,
  1345. ParentId = new Guid(parentId)
  1346. };
  1347. await CreateItem(item, cancellationToken).ConfigureAwait(false);
  1348. refresh = true;
  1349. }
  1350. if (!refresh && item != null)
  1351. {
  1352. refresh = (DateTime.UtcNow - item.DateLastSaved).TotalHours >= 24;
  1353. }
  1354. if (refresh)
  1355. {
  1356. await item.RefreshMetadata(new MetadataRefreshOptions
  1357. {
  1358. ForceSave = true
  1359. }, cancellationToken).ConfigureAwait(false);
  1360. }
  1361. return item;
  1362. }
  1363. public bool IsVideoFile(string path)
  1364. {
  1365. var resolver = new VideoResolver(new ExtendedNamingOptions(), new Naming.Logging.NullLogger());
  1366. return resolver.IsVideoFile(path);
  1367. }
  1368. public bool IsAudioFile(string path)
  1369. {
  1370. var parser = new AudioFileParser(new ExtendedNamingOptions());
  1371. return parser.IsAudioFile(path);
  1372. }
  1373. public int? GetSeasonNumberFromPath(string path)
  1374. {
  1375. return SeriesResolver.GetSeasonNumberFromPath(path);
  1376. }
  1377. public int? GetSeasonNumberFromEpisodeFile(string path)
  1378. {
  1379. return SeriesResolver.GetSeasonNumberFromEpisodeFile(path);
  1380. }
  1381. public int? GetEndingEpisodeNumberFromFile(string path)
  1382. {
  1383. return SeriesResolver.GetEndingEpisodeNumberFromFile(path);
  1384. }
  1385. public int? GetEpisodeNumberFromFile(string path, bool considerSeasonless)
  1386. {
  1387. return SeriesResolver.GetEpisodeNumberFromFile(path, considerSeasonless);
  1388. }
  1389. public ItemLookupInfo ParseName(string name)
  1390. {
  1391. var resolver = new VideoResolver(new ExtendedNamingOptions(), new Naming.Logging.NullLogger());
  1392. var result = resolver.CleanDateTime(name);
  1393. var cleanName = resolver.CleanString(result.Name);
  1394. return new ItemLookupInfo
  1395. {
  1396. Name = cleanName.Name,
  1397. Year = result.Year
  1398. };
  1399. }
  1400. public IEnumerable<FileSystemInfo> GetAdditionalParts(string file,
  1401. VideoType type,
  1402. IEnumerable<FileSystemInfo> files)
  1403. {
  1404. var resolver = new StackResolver(new ExtendedNamingOptions(), new Naming.Logging.NullLogger());
  1405. StackResult result;
  1406. List<FileSystemInfo> filteredFiles;
  1407. if (type == VideoType.BluRay || type == VideoType.Dvd)
  1408. {
  1409. filteredFiles = files.Where(i => (i.Attributes & FileAttributes.Directory) == FileAttributes.Directory)
  1410. .ToList();
  1411. result = resolver.ResolveDirectories(filteredFiles.Select(i => i.FullName));
  1412. }
  1413. else
  1414. {
  1415. filteredFiles = files.Where(i => (i.Attributes & FileAttributes.Directory) != FileAttributes.Directory)
  1416. .ToList();
  1417. result = resolver.ResolveFiles(filteredFiles.Select(i => i.FullName));
  1418. }
  1419. var stack = result.Stacks
  1420. .FirstOrDefault(i => i.Files.Contains(file, StringComparer.OrdinalIgnoreCase));
  1421. if (stack != null)
  1422. {
  1423. return stack.Files.Where(i => !string.Equals(i, file, StringComparison.OrdinalIgnoreCase))
  1424. .Select(i => filteredFiles.FirstOrDefault(f => string.Equals(i, f.FullName, StringComparison.OrdinalIgnoreCase)))
  1425. .Where(i => i != null);
  1426. }
  1427. return new List<FileSystemInfo>();
  1428. }
  1429. }
  1430. }