LibraryManager.cs 68 KB

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