LibraryManager.cs 58 KB

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