LibraryManager.cs 72 KB

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