LibraryManager.cs 69 KB

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