LibraryManager.cs 72 KB

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