LibraryManager.cs 76 KB

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