LibraryManager.cs 70 KB

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