LibraryManager.cs 70 KB

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