2
0

LibraryManager.cs 73 KB

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