LibraryManager.cs 71 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053
  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. Directory.Delete(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. Directory.Delete(path, true);
  370. }
  371. else if (File.Exists(path))
  372. {
  373. _logger.Debug("Deleting path {0}", path);
  374. File.Delete(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))
  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 a Genre
  722. /// </summary>
  723. /// <param name="name">The name.</param>
  724. /// <returns>Task{Genre}.</returns>
  725. public MusicArtist GetArtist(string name)
  726. {
  727. return GetItemByName<MusicArtist>(ConfigurationManager.ApplicationPaths.ArtistsPath, name);
  728. }
  729. private T GetItemByName<T>(string path, string name)
  730. where T : BaseItem, new()
  731. {
  732. if (string.IsNullOrWhiteSpace(path))
  733. {
  734. throw new ArgumentNullException("path");
  735. }
  736. if (string.IsNullOrWhiteSpace(name))
  737. {
  738. throw new ArgumentNullException("name");
  739. }
  740. var validFilename = _fileSystem.GetValidFilename(name).Trim();
  741. string subFolderPrefix = null;
  742. var type = typeof(T);
  743. if (type == typeof(Person))
  744. {
  745. subFolderPrefix = validFilename.Substring(0, 1);
  746. }
  747. var fullPath = string.IsNullOrEmpty(subFolderPrefix) ?
  748. Path.Combine(path, validFilename) :
  749. Path.Combine(path, subFolderPrefix, validFilename);
  750. var id = GetNewItemId(fullPath, type);
  751. BaseItem obj;
  752. if (!_libraryItemsCache.TryGetValue(id, out obj))
  753. {
  754. obj = CreateItemByName<T>(fullPath, name, id);
  755. RegisterItem(id, obj);
  756. }
  757. return obj as T;
  758. }
  759. /// <summary>
  760. /// Creates an IBN item based on a given path
  761. /// </summary>
  762. /// <typeparam name="T"></typeparam>
  763. /// <param name="path">The path.</param>
  764. /// <param name="name">The name.</param>
  765. /// <returns>Task{``0}.</returns>
  766. /// <exception cref="System.IO.IOException">Path not created: + path</exception>
  767. private T CreateItemByName<T>(string path, string name, Guid id)
  768. where T : BaseItem, new()
  769. {
  770. var isArtist = typeof(T) == typeof(MusicArtist);
  771. if (isArtist)
  772. {
  773. var validFilename = _fileSystem.GetValidFilename(name).Trim();
  774. var existing = RootFolder.RecursiveChildren
  775. .OfType<T>()
  776. .FirstOrDefault(i => string.Equals(_fileSystem.GetValidFilename(i.Name).Trim(), validFilename, StringComparison.OrdinalIgnoreCase));
  777. if (existing != null)
  778. {
  779. return existing;
  780. }
  781. }
  782. var fileInfo = new DirectoryInfo(path);
  783. var isNew = false;
  784. if (!fileInfo.Exists)
  785. {
  786. fileInfo = Directory.CreateDirectory(path);
  787. isNew = true;
  788. }
  789. var item = isNew ? null : GetItemById(id) as T;
  790. if (item == null)
  791. {
  792. item = new T
  793. {
  794. Name = name,
  795. Id = id,
  796. DateCreated = _fileSystem.GetCreationTimeUtc(fileInfo),
  797. DateModified = _fileSystem.GetLastWriteTimeUtc(fileInfo),
  798. Path = path
  799. };
  800. }
  801. if (isArtist)
  802. {
  803. (item as MusicArtist).IsAccessedByName = true;
  804. }
  805. return item;
  806. }
  807. /// <summary>
  808. /// Validate and refresh the People sub-set of the IBN.
  809. /// The items are stored in the db but not loaded into memory until actually requested by an operation.
  810. /// </summary>
  811. /// <param name="cancellationToken">The cancellation token.</param>
  812. /// <param name="progress">The progress.</param>
  813. /// <returns>Task.</returns>
  814. public Task ValidatePeople(CancellationToken cancellationToken, IProgress<double> progress)
  815. {
  816. // Ensure the location is available.
  817. Directory.CreateDirectory(ConfigurationManager.ApplicationPaths.PeoplePath);
  818. return new PeopleValidator(this, _logger, ConfigurationManager).ValidatePeople(cancellationToken, progress);
  819. }
  820. /// <summary>
  821. /// Validates the artists.
  822. /// </summary>
  823. /// <param name="cancellationToken">The cancellation token.</param>
  824. /// <param name="progress">The progress.</param>
  825. /// <returns>Task.</returns>
  826. public Task ValidateArtists(CancellationToken cancellationToken, IProgress<double> progress)
  827. {
  828. // Ensure the location is unavailable.
  829. Directory.CreateDirectory(ConfigurationManager.ApplicationPaths.ArtistsPath);
  830. return new ArtistsValidator(this, _userManager, _logger).Run(progress, cancellationToken);
  831. }
  832. /// <summary>
  833. /// Validates the music genres.
  834. /// </summary>
  835. /// <param name="cancellationToken">The cancellation token.</param>
  836. /// <param name="progress">The progress.</param>
  837. /// <returns>Task.</returns>
  838. public Task ValidateMusicGenres(CancellationToken cancellationToken, IProgress<double> progress)
  839. {
  840. // Ensure the location is unavailable.
  841. Directory.CreateDirectory(ConfigurationManager.ApplicationPaths.MusicGenrePath);
  842. return new MusicGenresValidator(this, _logger).Run(progress, cancellationToken);
  843. }
  844. /// <summary>
  845. /// Validates the game genres.
  846. /// </summary>
  847. /// <param name="cancellationToken">The cancellation token.</param>
  848. /// <param name="progress">The progress.</param>
  849. /// <returns>Task.</returns>
  850. public Task ValidateGameGenres(CancellationToken cancellationToken, IProgress<double> progress)
  851. {
  852. // Ensure the location is unavailable.
  853. Directory.CreateDirectory(ConfigurationManager.ApplicationPaths.GameGenrePath);
  854. return new GameGenresValidator(this, _userManager, _logger).Run(progress, cancellationToken);
  855. }
  856. /// <summary>
  857. /// Validates the studios.
  858. /// </summary>
  859. /// <param name="cancellationToken">The cancellation token.</param>
  860. /// <param name="progress">The progress.</param>
  861. /// <returns>Task.</returns>
  862. public Task ValidateStudios(CancellationToken cancellationToken, IProgress<double> progress)
  863. {
  864. // Ensure the location is unavailable.
  865. Directory.CreateDirectory(ConfigurationManager.ApplicationPaths.StudioPath);
  866. return new StudiosValidator(this, _userManager, _logger).Run(progress, cancellationToken);
  867. }
  868. /// <summary>
  869. /// Validates the genres.
  870. /// </summary>
  871. /// <param name="cancellationToken">The cancellation token.</param>
  872. /// <param name="progress">The progress.</param>
  873. /// <returns>Task.</returns>
  874. public Task ValidateGenres(CancellationToken cancellationToken, IProgress<double> progress)
  875. {
  876. // Ensure the location is unavailable.
  877. Directory.CreateDirectory(ConfigurationManager.ApplicationPaths.GenrePath);
  878. return new GenresValidator(this, _userManager, _logger).Run(progress, cancellationToken);
  879. }
  880. /// <summary>
  881. /// Reloads the root media folder
  882. /// </summary>
  883. /// <param name="progress">The progress.</param>
  884. /// <param name="cancellationToken">The cancellation token.</param>
  885. /// <returns>Task.</returns>
  886. public Task ValidateMediaLibrary(IProgress<double> progress, CancellationToken cancellationToken)
  887. {
  888. // Just run the scheduled task so that the user can see it
  889. _taskManager.CancelIfRunningAndQueue<RefreshMediaLibraryTask>();
  890. return Task.FromResult(true);
  891. }
  892. /// <summary>
  893. /// Queues the library scan.
  894. /// </summary>
  895. public void QueueLibraryScan()
  896. {
  897. // Just run the scheduled task so that the user can see it
  898. _taskManager.QueueScheduledTask<RefreshMediaLibraryTask>();
  899. }
  900. /// <summary>
  901. /// Validates the media library internal.
  902. /// </summary>
  903. /// <param name="progress">The progress.</param>
  904. /// <param name="cancellationToken">The cancellation token.</param>
  905. /// <returns>Task.</returns>
  906. public async Task ValidateMediaLibraryInternal(IProgress<double> progress, CancellationToken cancellationToken)
  907. {
  908. _libraryMonitorFactory().Stop();
  909. try
  910. {
  911. await PerformLibraryValidation(progress, cancellationToken).ConfigureAwait(false);
  912. }
  913. finally
  914. {
  915. _libraryMonitorFactory().Start();
  916. }
  917. }
  918. private async Task PerformLibraryValidation(IProgress<double> progress, CancellationToken cancellationToken)
  919. {
  920. _logger.Info("Validating media library");
  921. await RootFolder.RefreshMetadata(cancellationToken).ConfigureAwait(false);
  922. progress.Report(.5);
  923. // Start by just validating the children of the root, but go no further
  924. await RootFolder.ValidateChildren(new Progress<double>(), cancellationToken, new MetadataRefreshOptions(), recursive: false);
  925. progress.Report(1);
  926. var userRoot = GetUserRootFolder();
  927. await userRoot.RefreshMetadata(cancellationToken).ConfigureAwait(false);
  928. await userRoot.ValidateChildren(new Progress<double>(), cancellationToken, new MetadataRefreshOptions(), recursive: false).ConfigureAwait(false);
  929. progress.Report(2);
  930. var innerProgress = new ActionableProgress<double>();
  931. innerProgress.RegisterAction(pct => progress.Report(2 + pct * .73));
  932. // Now validate the entire media library
  933. await RootFolder.ValidateChildren(innerProgress, cancellationToken, new MetadataRefreshOptions(), recursive: true).ConfigureAwait(false);
  934. progress.Report(75);
  935. innerProgress = new ActionableProgress<double>();
  936. innerProgress.RegisterAction(pct => progress.Report(75 + pct * .25));
  937. // Run post-scan tasks
  938. await RunPostScanTasks(innerProgress, cancellationToken).ConfigureAwait(false);
  939. progress.Report(100);
  940. // Bad practice, i know. But we keep a lot in memory, unfortunately.
  941. GC.Collect(2, GCCollectionMode.Forced, true);
  942. GC.Collect(2, GCCollectionMode.Forced, true);
  943. }
  944. /// <summary>
  945. /// Runs the post scan tasks.
  946. /// </summary>
  947. /// <param name="progress">The progress.</param>
  948. /// <param name="cancellationToken">The cancellation token.</param>
  949. /// <returns>Task.</returns>
  950. private async Task RunPostScanTasks(IProgress<double> progress, CancellationToken cancellationToken)
  951. {
  952. var tasks = PostscanTasks.ToList();
  953. var numComplete = 0;
  954. var numTasks = tasks.Count;
  955. foreach (var task in tasks)
  956. {
  957. var innerProgress = new ActionableProgress<double>();
  958. // Prevent access to modified closure
  959. var currentNumComplete = numComplete;
  960. innerProgress.RegisterAction(pct =>
  961. {
  962. double innerPercent = (currentNumComplete * 100) + pct;
  963. innerPercent /= numTasks;
  964. progress.Report(innerPercent);
  965. });
  966. try
  967. {
  968. await task.Run(innerProgress, cancellationToken);
  969. }
  970. catch (OperationCanceledException)
  971. {
  972. _logger.Info("Post-scan task cancelled: {0}", task.GetType().Name);
  973. }
  974. catch (Exception ex)
  975. {
  976. _logger.ErrorException("Error running postscan task", ex);
  977. }
  978. numComplete++;
  979. double percent = numComplete;
  980. percent /= numTasks;
  981. progress.Report(percent * 100);
  982. }
  983. progress.Report(100);
  984. }
  985. /// <summary>
  986. /// Gets the default view.
  987. /// </summary>
  988. /// <returns>IEnumerable{VirtualFolderInfo}.</returns>
  989. public IEnumerable<VirtualFolderInfo> GetDefaultVirtualFolders()
  990. {
  991. return GetView(ConfigurationManager.ApplicationPaths.DefaultUserViewsPath);
  992. }
  993. /// <summary>
  994. /// Gets the view.
  995. /// </summary>
  996. /// <param name="user">The user.</param>
  997. /// <returns>IEnumerable{VirtualFolderInfo}.</returns>
  998. public IEnumerable<VirtualFolderInfo> GetVirtualFolders(User user)
  999. {
  1000. return GetDefaultVirtualFolders();
  1001. }
  1002. /// <summary>
  1003. /// Gets the view.
  1004. /// </summary>
  1005. /// <param name="path">The path.</param>
  1006. /// <returns>IEnumerable{VirtualFolderInfo}.</returns>
  1007. private IEnumerable<VirtualFolderInfo> GetView(string path)
  1008. {
  1009. return Directory.EnumerateDirectories(path, "*", SearchOption.TopDirectoryOnly)
  1010. .Select(dir => new VirtualFolderInfo
  1011. {
  1012. Name = Path.GetFileName(dir),
  1013. Locations = Directory.EnumerateFiles(dir, "*.mblink", SearchOption.TopDirectoryOnly)
  1014. .Select(_fileSystem.ResolveShortcut)
  1015. .OrderBy(i => i)
  1016. .ToList(),
  1017. CollectionType = GetCollectionType(dir)
  1018. });
  1019. }
  1020. private string GetCollectionType(string path)
  1021. {
  1022. return new DirectoryInfo(path).EnumerateFiles("*.collection", SearchOption.TopDirectoryOnly)
  1023. .Select(i => _fileSystem.GetFileNameWithoutExtension(i))
  1024. .FirstOrDefault();
  1025. }
  1026. /// <summary>
  1027. /// Gets the item by id.
  1028. /// </summary>
  1029. /// <param name="id">The id.</param>
  1030. /// <returns>BaseItem.</returns>
  1031. /// <exception cref="System.ArgumentNullException">id</exception>
  1032. public BaseItem GetItemById(Guid id)
  1033. {
  1034. if (id == Guid.Empty)
  1035. {
  1036. throw new ArgumentNullException("id");
  1037. }
  1038. BaseItem item;
  1039. if (LibraryItemsCache.TryGetValue(id, out item))
  1040. {
  1041. return item;
  1042. }
  1043. item = RetrieveItem(id);
  1044. if (item != null)
  1045. {
  1046. RegisterItem(item);
  1047. }
  1048. return item;
  1049. }
  1050. public BaseItem GetMemoryItemById(Guid id)
  1051. {
  1052. if (id == Guid.Empty)
  1053. {
  1054. throw new ArgumentNullException("id");
  1055. }
  1056. BaseItem item;
  1057. LibraryItemsCache.TryGetValue(id, out item);
  1058. return item;
  1059. }
  1060. /// <summary>
  1061. /// Gets the intros.
  1062. /// </summary>
  1063. /// <param name="item">The item.</param>
  1064. /// <param name="user">The user.</param>
  1065. /// <returns>IEnumerable{System.String}.</returns>
  1066. public async Task<IEnumerable<Video>> GetIntros(BaseItem item, User user)
  1067. {
  1068. var tasks = IntroProviders
  1069. .OrderBy(i => (i.GetType().Name.IndexOf("Default", StringComparison.OrdinalIgnoreCase) == -1 ? 0 : 1))
  1070. .Take(1)
  1071. .Select(i => GetIntros(i, item, user));
  1072. var items = await Task.WhenAll(tasks).ConfigureAwait(false);
  1073. return items
  1074. .SelectMany(i => i.ToArray())
  1075. .Select(ResolveIntro)
  1076. .Where(i => i != null);
  1077. }
  1078. /// <summary>
  1079. /// Gets the intros.
  1080. /// </summary>
  1081. /// <param name="provider">The provider.</param>
  1082. /// <param name="item">The item.</param>
  1083. /// <param name="user">The user.</param>
  1084. /// <returns>Task&lt;IEnumerable&lt;IntroInfo&gt;&gt;.</returns>
  1085. private async Task<IEnumerable<IntroInfo>> GetIntros(IIntroProvider provider, BaseItem item, User user)
  1086. {
  1087. try
  1088. {
  1089. return await provider.GetIntros(item, user).ConfigureAwait(false);
  1090. }
  1091. catch (Exception ex)
  1092. {
  1093. _logger.ErrorException("Error getting intros", ex);
  1094. return new List<IntroInfo>();
  1095. }
  1096. }
  1097. /// <summary>
  1098. /// Gets all intro files.
  1099. /// </summary>
  1100. /// <returns>IEnumerable{System.String}.</returns>
  1101. public IEnumerable<string> GetAllIntroFiles()
  1102. {
  1103. return IntroProviders.SelectMany(i =>
  1104. {
  1105. try
  1106. {
  1107. return i.GetAllIntroFiles().ToList();
  1108. }
  1109. catch (Exception ex)
  1110. {
  1111. _logger.ErrorException("Error getting intro files", ex);
  1112. return new List<string>();
  1113. }
  1114. });
  1115. }
  1116. /// <summary>
  1117. /// Resolves the intro.
  1118. /// </summary>
  1119. /// <param name="info">The info.</param>
  1120. /// <returns>Video.</returns>
  1121. private Video ResolveIntro(IntroInfo info)
  1122. {
  1123. Video video = null;
  1124. if (info.ItemId.HasValue)
  1125. {
  1126. // Get an existing item by Id
  1127. video = GetItemById(info.ItemId.Value) as Video;
  1128. if (video == null)
  1129. {
  1130. _logger.Error("Unable to locate item with Id {0}.", info.ItemId.Value);
  1131. }
  1132. }
  1133. else if (!string.IsNullOrEmpty(info.Path))
  1134. {
  1135. try
  1136. {
  1137. // Try to resolve the path into a video
  1138. video = ResolvePath(_fileSystem.GetFileSystemInfo(info.Path)) as Video;
  1139. if (video == null)
  1140. {
  1141. _logger.Error("Intro resolver returned null for {0}.", info.Path);
  1142. }
  1143. else
  1144. {
  1145. // Pull the saved db item that will include metadata
  1146. var dbItem = GetItemById(video.Id) as Video;
  1147. if (dbItem != null)
  1148. {
  1149. video = dbItem;
  1150. }
  1151. }
  1152. }
  1153. catch (Exception ex)
  1154. {
  1155. _logger.ErrorException("Error resolving path {0}.", ex, info.Path);
  1156. }
  1157. }
  1158. else
  1159. {
  1160. _logger.Error("IntroProvider returned an IntroInfo with null Path and ItemId.");
  1161. }
  1162. return video;
  1163. }
  1164. /// <summary>
  1165. /// Sorts the specified sort by.
  1166. /// </summary>
  1167. /// <param name="items">The items.</param>
  1168. /// <param name="user">The user.</param>
  1169. /// <param name="sortBy">The sort by.</param>
  1170. /// <param name="sortOrder">The sort order.</param>
  1171. /// <returns>IEnumerable{BaseItem}.</returns>
  1172. public IEnumerable<BaseItem> Sort(IEnumerable<BaseItem> items, User user, IEnumerable<string> sortBy, SortOrder sortOrder)
  1173. {
  1174. var isFirst = true;
  1175. IOrderedEnumerable<BaseItem> orderedItems = null;
  1176. foreach (var orderBy in sortBy.Select(o => GetComparer(o, user)).Where(c => c != null))
  1177. {
  1178. if (isFirst)
  1179. {
  1180. orderedItems = sortOrder == SortOrder.Descending ? items.OrderByDescending(i => i, orderBy) : items.OrderBy(i => i, orderBy);
  1181. }
  1182. else
  1183. {
  1184. orderedItems = sortOrder == SortOrder.Descending ? orderedItems.ThenByDescending(i => i, orderBy) : orderedItems.ThenBy(i => i, orderBy);
  1185. }
  1186. isFirst = false;
  1187. }
  1188. return orderedItems ?? items;
  1189. }
  1190. /// <summary>
  1191. /// Gets the comparer.
  1192. /// </summary>
  1193. /// <param name="name">The name.</param>
  1194. /// <param name="user">The user.</param>
  1195. /// <returns>IBaseItemComparer.</returns>
  1196. private IBaseItemComparer GetComparer(string name, User user)
  1197. {
  1198. var comparer = Comparers.FirstOrDefault(c => string.Equals(name, c.Name, StringComparison.OrdinalIgnoreCase));
  1199. if (comparer != null)
  1200. {
  1201. // If it requires a user, create a new one, and assign the user
  1202. if (comparer is IUserBaseItemComparer)
  1203. {
  1204. var userComparer = (IUserBaseItemComparer)Activator.CreateInstance(comparer.GetType());
  1205. userComparer.User = user;
  1206. userComparer.UserManager = _userManager;
  1207. userComparer.UserDataRepository = _userDataRepository;
  1208. return userComparer;
  1209. }
  1210. }
  1211. return comparer;
  1212. }
  1213. /// <summary>
  1214. /// Creates the item.
  1215. /// </summary>
  1216. /// <param name="item">The item.</param>
  1217. /// <param name="cancellationToken">The cancellation token.</param>
  1218. /// <returns>Task.</returns>
  1219. public Task CreateItem(BaseItem item, CancellationToken cancellationToken)
  1220. {
  1221. return CreateItems(new[] { item }, cancellationToken);
  1222. }
  1223. /// <summary>
  1224. /// Creates the items.
  1225. /// </summary>
  1226. /// <param name="items">The items.</param>
  1227. /// <param name="cancellationToken">The cancellation token.</param>
  1228. /// <returns>Task.</returns>
  1229. public async Task CreateItems(IEnumerable<BaseItem> items, CancellationToken cancellationToken)
  1230. {
  1231. var list = items.ToList();
  1232. await ItemRepository.SaveItems(list, cancellationToken).ConfigureAwait(false);
  1233. foreach (var item in list)
  1234. {
  1235. UpdateItemInLibraryCache(item);
  1236. }
  1237. if (ItemAdded != null)
  1238. {
  1239. foreach (var item in list)
  1240. {
  1241. try
  1242. {
  1243. ItemAdded(this, new ItemChangeEventArgs { Item = item });
  1244. }
  1245. catch (Exception ex)
  1246. {
  1247. _logger.ErrorException("Error in ItemAdded event handler", ex);
  1248. }
  1249. }
  1250. }
  1251. }
  1252. /// <summary>
  1253. /// Updates the item.
  1254. /// </summary>
  1255. /// <param name="item">The item.</param>
  1256. /// <param name="updateReason">The update reason.</param>
  1257. /// <param name="cancellationToken">The cancellation token.</param>
  1258. /// <returns>Task.</returns>
  1259. public async Task UpdateItem(BaseItem item, ItemUpdateType updateReason, CancellationToken cancellationToken)
  1260. {
  1261. var locationType = item.LocationType;
  1262. if (locationType != LocationType.Remote && locationType != LocationType.Virtual)
  1263. {
  1264. await _providerManagerFactory().SaveMetadata(item, updateReason).ConfigureAwait(false);
  1265. }
  1266. item.DateLastSaved = DateTime.UtcNow;
  1267. var logName = item.LocationType == LocationType.Remote ? item.Name ?? item.Path : item.Path ?? item.Name;
  1268. _logger.Debug("Saving {0} to database.", logName);
  1269. await ItemRepository.SaveItem(item, cancellationToken).ConfigureAwait(false);
  1270. UpdateItemInLibraryCache(item);
  1271. if (ItemUpdated != null)
  1272. {
  1273. try
  1274. {
  1275. ItemUpdated(this, new ItemChangeEventArgs
  1276. {
  1277. Item = item,
  1278. UpdateReason = updateReason
  1279. });
  1280. }
  1281. catch (Exception ex)
  1282. {
  1283. _logger.ErrorException("Error in ItemUpdated event handler", ex);
  1284. }
  1285. }
  1286. }
  1287. /// <summary>
  1288. /// Reports the item removed.
  1289. /// </summary>
  1290. /// <param name="item">The item.</param>
  1291. public void ReportItemRemoved(BaseItem item)
  1292. {
  1293. if (ItemRemoved != null)
  1294. {
  1295. try
  1296. {
  1297. ItemRemoved(this, new ItemChangeEventArgs { Item = item });
  1298. }
  1299. catch (Exception ex)
  1300. {
  1301. _logger.ErrorException("Error in ItemRemoved event handler", ex);
  1302. }
  1303. }
  1304. }
  1305. /// <summary>
  1306. /// Retrieves the item.
  1307. /// </summary>
  1308. /// <param name="id">The id.</param>
  1309. /// <returns>BaseItem.</returns>
  1310. public BaseItem RetrieveItem(Guid id)
  1311. {
  1312. return ItemRepository.RetrieveItem(id);
  1313. }
  1314. public string GetContentType(BaseItem item)
  1315. {
  1316. string configuredContentType = GetConfiguredContentType(item, false);
  1317. if (!string.IsNullOrWhiteSpace(configuredContentType))
  1318. {
  1319. return configuredContentType;
  1320. }
  1321. configuredContentType = GetConfiguredContentType(item, true);
  1322. if (!string.IsNullOrWhiteSpace(configuredContentType))
  1323. {
  1324. return configuredContentType;
  1325. }
  1326. return GetInheritedContentType(item);
  1327. }
  1328. public string GetInheritedContentType(BaseItem item)
  1329. {
  1330. var type = GetTopFolderContentType(item);
  1331. if (!string.IsNullOrWhiteSpace(type))
  1332. {
  1333. return type;
  1334. }
  1335. return item.Parents
  1336. .Select(GetConfiguredContentType)
  1337. .LastOrDefault(i => !string.IsNullOrWhiteSpace(i));
  1338. }
  1339. public string GetConfiguredContentType(BaseItem item)
  1340. {
  1341. return GetConfiguredContentType(item, false);
  1342. }
  1343. public string GetConfiguredContentType(string path)
  1344. {
  1345. return GetContentTypeOverride(path, false);
  1346. }
  1347. public string GetConfiguredContentType(BaseItem item, bool inheritConfiguredPath)
  1348. {
  1349. ICollectionFolder collectionFolder = item as ICollectionFolder;
  1350. if (collectionFolder != null)
  1351. {
  1352. return collectionFolder.CollectionType;
  1353. }
  1354. return GetContentTypeOverride(item.ContainingFolderPath, inheritConfiguredPath);
  1355. }
  1356. private string GetContentTypeOverride(string path, bool inherit)
  1357. {
  1358. var nameValuePair = ConfigurationManager.Configuration.ContentTypes.FirstOrDefault(i => string.Equals(i.Name, path, StringComparison.OrdinalIgnoreCase) || (inherit && _fileSystem.ContainsSubPath(i.Name, path)));
  1359. if (nameValuePair != null)
  1360. {
  1361. return nameValuePair.Value;
  1362. }
  1363. return null;
  1364. }
  1365. private string GetTopFolderContentType(BaseItem item)
  1366. {
  1367. while (!(item.Parent is AggregateFolder) && item.Parent != null)
  1368. {
  1369. item = item.Parent;
  1370. }
  1371. if (item == null)
  1372. {
  1373. return null;
  1374. }
  1375. return GetUserRootFolder().Children
  1376. .OfType<ICollectionFolder>()
  1377. .Where(i => string.Equals(i.Path, item.Path, StringComparison.OrdinalIgnoreCase) || i.PhysicalLocations.Contains(item.Path))
  1378. .Select(i => i.CollectionType)
  1379. .FirstOrDefault(i => !string.IsNullOrWhiteSpace(i));
  1380. }
  1381. public async Task<UserView> GetNamedView(string name,
  1382. string type,
  1383. string sortName,
  1384. CancellationToken cancellationToken)
  1385. {
  1386. var path = Path.Combine(ConfigurationManager.ApplicationPaths.ItemsByNamePath,
  1387. "views");
  1388. path = Path.Combine(path, _fileSystem.GetValidFilename(type));
  1389. var id = GetNewItemId(path + "_namedview_" + name, typeof(UserView));
  1390. var item = GetItemById(id) as UserView;
  1391. var refresh = false;
  1392. if (item == null ||
  1393. !string.Equals(item.Path, path, StringComparison.OrdinalIgnoreCase))
  1394. {
  1395. Directory.CreateDirectory(path);
  1396. item = new UserView
  1397. {
  1398. Path = path,
  1399. Id = id,
  1400. DateCreated = DateTime.UtcNow,
  1401. Name = name,
  1402. ViewType = type,
  1403. ForcedSortName = sortName
  1404. };
  1405. await CreateItem(item, cancellationToken).ConfigureAwait(false);
  1406. refresh = true;
  1407. }
  1408. if (!refresh && item != null)
  1409. {
  1410. refresh = (DateTime.UtcNow - item.DateLastSaved).TotalHours >= 24;
  1411. }
  1412. if (refresh)
  1413. {
  1414. await item.RefreshMetadata(new MetadataRefreshOptions
  1415. {
  1416. ForceSave = true
  1417. }, cancellationToken).ConfigureAwait(false);
  1418. }
  1419. return item;
  1420. }
  1421. public async Task<UserView> GetSpecialFolder(User user,
  1422. string name,
  1423. string parentId,
  1424. string viewType,
  1425. string sortName,
  1426. CancellationToken cancellationToken)
  1427. {
  1428. if (string.IsNullOrWhiteSpace(name))
  1429. {
  1430. throw new ArgumentNullException("name");
  1431. }
  1432. if (string.IsNullOrWhiteSpace(parentId))
  1433. {
  1434. throw new ArgumentNullException("parentId");
  1435. }
  1436. if (string.IsNullOrWhiteSpace(viewType))
  1437. {
  1438. throw new ArgumentNullException("viewType");
  1439. }
  1440. var id = GetNewItemId("7_namedview_" + name + user.Id.ToString("N") + parentId, typeof(UserView));
  1441. var path = BaseItem.GetInternalMetadataPathForId(id);
  1442. var item = GetItemById(id) as UserView;
  1443. var refresh = false;
  1444. if (item == null)
  1445. {
  1446. Directory.CreateDirectory(path);
  1447. item = new UserView
  1448. {
  1449. Path = path,
  1450. Id = id,
  1451. DateCreated = DateTime.UtcNow,
  1452. Name = name,
  1453. ViewType = viewType,
  1454. ForcedSortName = sortName,
  1455. UserId = user.Id,
  1456. ParentId = new Guid(parentId)
  1457. };
  1458. await CreateItem(item, cancellationToken).ConfigureAwait(false);
  1459. refresh = true;
  1460. }
  1461. if (!refresh && item != null)
  1462. {
  1463. refresh = (DateTime.UtcNow - item.DateLastSaved).TotalHours >= 24;
  1464. }
  1465. if (refresh)
  1466. {
  1467. await item.RefreshMetadata(new MetadataRefreshOptions
  1468. {
  1469. ForceSave = true
  1470. }, cancellationToken).ConfigureAwait(false);
  1471. }
  1472. return item;
  1473. }
  1474. public bool IsVideoFile(string path)
  1475. {
  1476. var resolver = new VideoResolver(GetNamingOptions(), new Naming.Logging.NullLogger());
  1477. return resolver.IsVideoFile(path);
  1478. }
  1479. public bool IsAudioFile(string path)
  1480. {
  1481. var parser = new AudioFileParser(GetNamingOptions());
  1482. return parser.IsAudioFile(path);
  1483. }
  1484. public int? GetSeasonNumberFromPath(string path)
  1485. {
  1486. return new SeasonPathParser(GetNamingOptions(), new RegexProvider()).Parse(path, true, true).SeasonNumber;
  1487. }
  1488. public bool FillMissingEpisodeNumbersFromPath(Episode episode)
  1489. {
  1490. var resolver = new EpisodeResolver(GetNamingOptions(),
  1491. new Naming.Logging.NullLogger());
  1492. var fileType = episode.VideoType == VideoType.BluRay || episode.VideoType == VideoType.Dvd || episode.VideoType == VideoType.HdDvd ?
  1493. FileInfoType.Directory :
  1494. FileInfoType.File;
  1495. var locationType = episode.LocationType;
  1496. var episodeInfo = locationType == LocationType.FileSystem || locationType == LocationType.Offline ?
  1497. resolver.Resolve(episode.Path, fileType) :
  1498. new Naming.TV.EpisodeInfo();
  1499. if (episodeInfo == null)
  1500. {
  1501. episodeInfo = new Naming.TV.EpisodeInfo();
  1502. }
  1503. var changed = false;
  1504. if (episodeInfo.IsByDate)
  1505. {
  1506. if (episode.IndexNumber.HasValue)
  1507. {
  1508. episode.IndexNumber = null;
  1509. changed = true;
  1510. }
  1511. if (episode.IndexNumberEnd.HasValue)
  1512. {
  1513. episode.IndexNumberEnd = null;
  1514. changed = true;
  1515. }
  1516. if (!episode.PremiereDate.HasValue)
  1517. {
  1518. if (episodeInfo.Year.HasValue && episodeInfo.Month.HasValue && episodeInfo.Day.HasValue)
  1519. {
  1520. episode.PremiereDate = new DateTime(episodeInfo.Year.Value, episodeInfo.Month.Value, episodeInfo.Day.Value).ToUniversalTime();
  1521. }
  1522. if (episode.PremiereDate.HasValue)
  1523. {
  1524. changed = true;
  1525. }
  1526. }
  1527. if (!episode.ProductionYear.HasValue)
  1528. {
  1529. episode.ProductionYear = episodeInfo.Year;
  1530. if (episode.ProductionYear.HasValue)
  1531. {
  1532. changed = true;
  1533. }
  1534. }
  1535. if (!episode.ParentIndexNumber.HasValue)
  1536. {
  1537. var season = episode.Season;
  1538. if (season != null)
  1539. {
  1540. episode.ParentIndexNumber = season.IndexNumber;
  1541. }
  1542. if (episode.ParentIndexNumber.HasValue)
  1543. {
  1544. changed = true;
  1545. }
  1546. }
  1547. }
  1548. else
  1549. {
  1550. if (!episode.IndexNumber.HasValue)
  1551. {
  1552. episode.IndexNumber = episodeInfo.EpisodeNumber;
  1553. if (episode.IndexNumber.HasValue)
  1554. {
  1555. changed = true;
  1556. }
  1557. }
  1558. if (!episode.IndexNumberEnd.HasValue)
  1559. {
  1560. episode.IndexNumberEnd = episodeInfo.EndingEpsiodeNumber;
  1561. if (episode.IndexNumberEnd.HasValue)
  1562. {
  1563. changed = true;
  1564. }
  1565. }
  1566. if (!episode.ParentIndexNumber.HasValue)
  1567. {
  1568. episode.ParentIndexNumber = episodeInfo.SeasonNumber;
  1569. if (!episode.ParentIndexNumber.HasValue)
  1570. {
  1571. var season = episode.Season;
  1572. if (season != null)
  1573. {
  1574. episode.ParentIndexNumber = season.IndexNumber;
  1575. }
  1576. }
  1577. if (episode.ParentIndexNumber.HasValue)
  1578. {
  1579. changed = true;
  1580. }
  1581. }
  1582. }
  1583. return changed;
  1584. }
  1585. public NamingOptions GetNamingOptions()
  1586. {
  1587. var options = new ExtendedNamingOptions();
  1588. if (!ConfigurationManager.Configuration.EnableAudioArchiveFiles)
  1589. {
  1590. options.AudioFileExtensions.Remove(".rar");
  1591. options.AudioFileExtensions.Remove(".zip");
  1592. }
  1593. if (!ConfigurationManager.Configuration.EnableVideoArchiveFiles)
  1594. {
  1595. options.VideoFileExtensions.Remove(".rar");
  1596. options.VideoFileExtensions.Remove(".zip");
  1597. }
  1598. return options;
  1599. }
  1600. public ItemLookupInfo ParseName(string name)
  1601. {
  1602. var resolver = new VideoResolver(GetNamingOptions(), new Naming.Logging.NullLogger());
  1603. var result = resolver.CleanDateTime(name);
  1604. var cleanName = resolver.CleanString(result.Name);
  1605. return new ItemLookupInfo
  1606. {
  1607. Name = cleanName.Name,
  1608. Year = result.Year
  1609. };
  1610. }
  1611. public IEnumerable<Video> FindTrailers(BaseItem owner, List<FileSystemInfo> fileSystemChildren, IDirectoryService directoryService)
  1612. {
  1613. var files = fileSystemChildren.OfType<DirectoryInfo>()
  1614. .Where(i => string.Equals(i.Name, BaseItem.TrailerFolderName, StringComparison.OrdinalIgnoreCase))
  1615. .SelectMany(i => i.EnumerateFiles("*", SearchOption.TopDirectoryOnly))
  1616. .ToList();
  1617. var videoListResolver = new VideoListResolver(GetNamingOptions(), new Naming.Logging.NullLogger());
  1618. var videos = videoListResolver.Resolve(fileSystemChildren.Select(i => new PortableFileInfo
  1619. {
  1620. FullName = i.FullName,
  1621. Type = GetFileType(i)
  1622. }).ToList());
  1623. var currentVideo = videos.FirstOrDefault(i => string.Equals(owner.Path, i.Files.First().Path, StringComparison.OrdinalIgnoreCase));
  1624. if (currentVideo != null)
  1625. {
  1626. files.AddRange(currentVideo.Extras.Where(i => string.Equals(i.ExtraType, "trailer", StringComparison.OrdinalIgnoreCase)).Select(i => new FileInfo(i.Path)));
  1627. }
  1628. return ResolvePaths(files, directoryService, null, null)
  1629. .OfType<Video>()
  1630. .Select(video =>
  1631. {
  1632. // Try to retrieve it from the db. If we don't find it, use the resolved version
  1633. var dbItem = GetItemById(video.Id) as Video;
  1634. if (dbItem != null)
  1635. {
  1636. video = dbItem;
  1637. }
  1638. video.ExtraType = ExtraType.Trailer;
  1639. return video;
  1640. // Sort them so that the list can be easily compared for changes
  1641. }).OrderBy(i => i.Path).ToList();
  1642. }
  1643. private FileInfoType GetFileType(FileSystemInfo info)
  1644. {
  1645. if ((info.Attributes & FileAttributes.Directory) == FileAttributes.Directory)
  1646. {
  1647. return FileInfoType.Directory;
  1648. }
  1649. return FileInfoType.File;
  1650. }
  1651. public IEnumerable<Video> FindExtras(BaseItem owner, List<FileSystemInfo> fileSystemChildren, IDirectoryService directoryService)
  1652. {
  1653. var files = fileSystemChildren.OfType<DirectoryInfo>()
  1654. .Where(i => string.Equals(i.Name, "extras", StringComparison.OrdinalIgnoreCase) || string.Equals(i.Name, "specials", StringComparison.OrdinalIgnoreCase))
  1655. .SelectMany(i => i.EnumerateFiles("*", SearchOption.TopDirectoryOnly))
  1656. .ToList();
  1657. var videoListResolver = new VideoListResolver(GetNamingOptions(), new Naming.Logging.NullLogger());
  1658. var videos = videoListResolver.Resolve(fileSystemChildren.Select(i => new PortableFileInfo
  1659. {
  1660. FullName = i.FullName,
  1661. Type = GetFileType(i)
  1662. }).ToList());
  1663. var currentVideo = videos.FirstOrDefault(i => string.Equals(owner.Path, i.Files.First().Path, StringComparison.OrdinalIgnoreCase));
  1664. if (currentVideo != null)
  1665. {
  1666. files.AddRange(currentVideo.Extras.Where(i => !string.Equals(i.ExtraType, "trailer", StringComparison.OrdinalIgnoreCase)).Select(i => new FileInfo(i.Path)));
  1667. }
  1668. return ResolvePaths(files, directoryService, null, null)
  1669. .OfType<Video>()
  1670. .Select(video =>
  1671. {
  1672. // Try to retrieve it from the db. If we don't find it, use the resolved version
  1673. var dbItem = GetItemById(video.Id) as Video;
  1674. if (dbItem != null)
  1675. {
  1676. video = dbItem;
  1677. }
  1678. SetExtraTypeFromFilename(video);
  1679. return video;
  1680. // Sort them so that the list can be easily compared for changes
  1681. }).OrderBy(i => i.Path).ToList();
  1682. }
  1683. private void SetExtraTypeFromFilename(Video item)
  1684. {
  1685. var resolver = new ExtraResolver(GetNamingOptions(), new Naming.Logging.NullLogger(), new RegexProvider());
  1686. var result = resolver.GetExtraInfo(item.Path);
  1687. if (string.Equals(result.ExtraType, "deletedscene", StringComparison.OrdinalIgnoreCase))
  1688. {
  1689. item.ExtraType = ExtraType.DeletedScene;
  1690. }
  1691. else if (string.Equals(result.ExtraType, "behindthescenes", StringComparison.OrdinalIgnoreCase))
  1692. {
  1693. item.ExtraType = ExtraType.BehindTheScenes;
  1694. }
  1695. else if (string.Equals(result.ExtraType, "interview", StringComparison.OrdinalIgnoreCase))
  1696. {
  1697. item.ExtraType = ExtraType.Interview;
  1698. }
  1699. else if (string.Equals(result.ExtraType, "scene", StringComparison.OrdinalIgnoreCase))
  1700. {
  1701. item.ExtraType = ExtraType.Scene;
  1702. }
  1703. else if (string.Equals(result.ExtraType, "sample", StringComparison.OrdinalIgnoreCase))
  1704. {
  1705. item.ExtraType = ExtraType.Sample;
  1706. }
  1707. else
  1708. {
  1709. item.ExtraType = ExtraType.Clip;
  1710. }
  1711. }
  1712. }
  1713. }