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