LibraryManager.cs 70 KB

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