LibraryManager.cs 72 KB

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