LibraryManager.cs 76 KB

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