LibraryManager.cs 71 KB

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