LibraryManager.cs 59 KB

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