LibraryManager.cs 59 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709
  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. return files.Select(f =>
  537. {
  538. try
  539. {
  540. return ResolvePath(f, directoryService, parent, collectionType) as T;
  541. }
  542. catch (Exception ex)
  543. {
  544. _logger.ErrorException("Error resolving path {0}", ex, f.FullName);
  545. return null;
  546. }
  547. }).Where(i => i != null)
  548. .ToList();
  549. }
  550. /// <summary>
  551. /// Creates the root media folder
  552. /// </summary>
  553. /// <returns>AggregateFolder.</returns>
  554. /// <exception cref="System.InvalidOperationException">Cannot create the root folder until plugins have loaded</exception>
  555. public AggregateFolder CreateRootFolder()
  556. {
  557. var rootFolderPath = ConfigurationManager.ApplicationPaths.RootFolderPath;
  558. Directory.CreateDirectory(rootFolderPath);
  559. var rootFolder = GetItemById(rootFolderPath.GetMBId(typeof(AggregateFolder))) as AggregateFolder ?? (AggregateFolder)ResolvePath(new DirectoryInfo(rootFolderPath));
  560. // Add in the plug-in folders
  561. foreach (var child in PluginFolderCreators)
  562. {
  563. var folder = child.GetFolder();
  564. if (folder != null)
  565. {
  566. if (folder.Id == Guid.Empty)
  567. {
  568. folder.Id = (folder.Path ?? folder.GetType().Name).GetMBId(folder.GetType());
  569. }
  570. folder = GetItemById(folder.Id) as BasePluginFolder ?? folder;
  571. rootFolder.AddVirtualChild(folder);
  572. RegisterItem(folder);
  573. }
  574. }
  575. return rootFolder;
  576. }
  577. private UserRootFolder _userRootFolder;
  578. public Folder GetUserRootFolder()
  579. {
  580. if (_userRootFolder == null)
  581. {
  582. var userRootPath = ConfigurationManager.ApplicationPaths.DefaultUserViewsPath;
  583. Directory.CreateDirectory(userRootPath);
  584. _userRootFolder = GetItemById(userRootPath.GetMBId(typeof(UserRootFolder))) as UserRootFolder ??
  585. (UserRootFolder)ResolvePath(new DirectoryInfo(userRootPath));
  586. }
  587. return _userRootFolder;
  588. }
  589. /// <summary>
  590. /// Gets a Person
  591. /// </summary>
  592. /// <param name="name">The name.</param>
  593. /// <returns>Task{Person}.</returns>
  594. public Person GetPerson(string name)
  595. {
  596. return GetItemByName<Person>(ConfigurationManager.ApplicationPaths.PeoplePath, name);
  597. }
  598. /// <summary>
  599. /// Gets a Studio
  600. /// </summary>
  601. /// <param name="name">The name.</param>
  602. /// <returns>Task{Studio}.</returns>
  603. public Studio GetStudio(string name)
  604. {
  605. return GetItemByName<Studio>(ConfigurationManager.ApplicationPaths.StudioPath, name);
  606. }
  607. /// <summary>
  608. /// Gets a Genre
  609. /// </summary>
  610. /// <param name="name">The name.</param>
  611. /// <returns>Task{Genre}.</returns>
  612. public Genre GetGenre(string name)
  613. {
  614. return GetItemByName<Genre>(ConfigurationManager.ApplicationPaths.GenrePath, name);
  615. }
  616. /// <summary>
  617. /// Gets the genre.
  618. /// </summary>
  619. /// <param name="name">The name.</param>
  620. /// <returns>Task{MusicGenre}.</returns>
  621. public MusicGenre GetMusicGenre(string name)
  622. {
  623. return GetItemByName<MusicGenre>(ConfigurationManager.ApplicationPaths.MusicGenrePath, name);
  624. }
  625. /// <summary>
  626. /// Gets the game genre.
  627. /// </summary>
  628. /// <param name="name">The name.</param>
  629. /// <returns>Task{GameGenre}.</returns>
  630. public GameGenre GetGameGenre(string name)
  631. {
  632. return GetItemByName<GameGenre>(ConfigurationManager.ApplicationPaths.GameGenrePath, name);
  633. }
  634. /// <summary>
  635. /// The us culture
  636. /// </summary>
  637. private static readonly CultureInfo UsCulture = new CultureInfo("en-US");
  638. /// <summary>
  639. /// Gets a Year
  640. /// </summary>
  641. /// <param name="value">The value.</param>
  642. /// <returns>Task{Year}.</returns>
  643. /// <exception cref="System.ArgumentOutOfRangeException"></exception>
  644. public Year GetYear(int value)
  645. {
  646. if (value <= 0)
  647. {
  648. throw new ArgumentOutOfRangeException("Years less than or equal to 0 are invalid.");
  649. }
  650. return GetItemByName<Year>(ConfigurationManager.ApplicationPaths.YearPath, value.ToString(UsCulture));
  651. }
  652. /// <summary>
  653. /// Gets a Genre
  654. /// </summary>
  655. /// <param name="name">The name.</param>
  656. /// <returns>Task{Genre}.</returns>
  657. public MusicArtist GetArtist(string name)
  658. {
  659. return GetItemByName<MusicArtist>(ConfigurationManager.ApplicationPaths.ArtistsPath, name);
  660. }
  661. private T GetItemByName<T>(string path, string name)
  662. where T : BaseItem, new()
  663. {
  664. if (string.IsNullOrWhiteSpace(path))
  665. {
  666. throw new ArgumentNullException("path");
  667. }
  668. if (string.IsNullOrWhiteSpace(name))
  669. {
  670. throw new ArgumentNullException("name");
  671. }
  672. var validFilename = _fileSystem.GetValidFilename(name).Trim();
  673. string subFolderPrefix = null;
  674. var type = typeof(T);
  675. if (type == typeof(Person) && ConfigurationManager.Configuration.EnablePeoplePrefixSubFolders)
  676. {
  677. subFolderPrefix = validFilename.Substring(0, 1);
  678. }
  679. var fullPath = string.IsNullOrEmpty(subFolderPrefix) ?
  680. Path.Combine(path, validFilename) :
  681. Path.Combine(path, subFolderPrefix, validFilename);
  682. var id = fullPath.GetMBId(type);
  683. BaseItem obj;
  684. if (!_libraryItemsCache.TryGetValue(id, out obj))
  685. {
  686. obj = CreateItemByName<T>(fullPath, name, id);
  687. RegisterItem(id, obj);
  688. }
  689. return obj as T;
  690. }
  691. /// <summary>
  692. /// Creates an IBN item based on a given path
  693. /// </summary>
  694. /// <typeparam name="T"></typeparam>
  695. /// <param name="path">The path.</param>
  696. /// <param name="name">The name.</param>
  697. /// <returns>Task{``0}.</returns>
  698. /// <exception cref="System.IO.IOException">Path not created: + path</exception>
  699. private T CreateItemByName<T>(string path, string name, Guid id)
  700. where T : BaseItem, new()
  701. {
  702. var isArtist = typeof(T) == typeof(MusicArtist);
  703. if (isArtist)
  704. {
  705. var validFilename = _fileSystem.GetValidFilename(name).Trim();
  706. var existing = RootFolder.RecursiveChildren
  707. .OfType<T>()
  708. .FirstOrDefault(i => string.Equals(_fileSystem.GetValidFilename(i.Name).Trim(), validFilename, StringComparison.OrdinalIgnoreCase));
  709. if (existing != null)
  710. {
  711. return existing;
  712. }
  713. }
  714. var fileInfo = new DirectoryInfo(path);
  715. var isNew = false;
  716. if (!fileInfo.Exists)
  717. {
  718. fileInfo = Directory.CreateDirectory(path);
  719. isNew = true;
  720. }
  721. var item = isNew ? null : GetItemById(id) as T;
  722. if (item == null)
  723. {
  724. item = new T
  725. {
  726. Name = name,
  727. Id = id,
  728. DateCreated = _fileSystem.GetCreationTimeUtc(fileInfo),
  729. DateModified = _fileSystem.GetLastWriteTimeUtc(fileInfo),
  730. Path = path
  731. };
  732. }
  733. if (isArtist)
  734. {
  735. (item as MusicArtist).IsAccessedByName = true;
  736. }
  737. return item;
  738. }
  739. /// <summary>
  740. /// Validate and refresh the People sub-set of the IBN.
  741. /// The items are stored in the db but not loaded into memory until actually requested by an operation.
  742. /// </summary>
  743. /// <param name="cancellationToken">The cancellation token.</param>
  744. /// <param name="progress">The progress.</param>
  745. /// <returns>Task.</returns>
  746. public Task ValidatePeople(CancellationToken cancellationToken, IProgress<double> progress)
  747. {
  748. // Ensure the location is available.
  749. Directory.CreateDirectory(ConfigurationManager.ApplicationPaths.PeoplePath);
  750. return new PeopleValidator(this, _logger, ConfigurationManager).ValidatePeople(cancellationToken, progress);
  751. }
  752. /// <summary>
  753. /// Validates the artists.
  754. /// </summary>
  755. /// <param name="cancellationToken">The cancellation token.</param>
  756. /// <param name="progress">The progress.</param>
  757. /// <returns>Task.</returns>
  758. public Task ValidateArtists(CancellationToken cancellationToken, IProgress<double> progress)
  759. {
  760. // Ensure the location is unavailable.
  761. Directory.CreateDirectory(ConfigurationManager.ApplicationPaths.ArtistsPath);
  762. return new ArtistsValidator(this, _userManager, _logger).Run(progress, cancellationToken);
  763. }
  764. /// <summary>
  765. /// Validates the music genres.
  766. /// </summary>
  767. /// <param name="cancellationToken">The cancellation token.</param>
  768. /// <param name="progress">The progress.</param>
  769. /// <returns>Task.</returns>
  770. public Task ValidateMusicGenres(CancellationToken cancellationToken, IProgress<double> progress)
  771. {
  772. // Ensure the location is unavailable.
  773. Directory.CreateDirectory(ConfigurationManager.ApplicationPaths.MusicGenrePath);
  774. return new MusicGenresValidator(this, _logger).Run(progress, cancellationToken);
  775. }
  776. /// <summary>
  777. /// Validates the game genres.
  778. /// </summary>
  779. /// <param name="cancellationToken">The cancellation token.</param>
  780. /// <param name="progress">The progress.</param>
  781. /// <returns>Task.</returns>
  782. public Task ValidateGameGenres(CancellationToken cancellationToken, IProgress<double> progress)
  783. {
  784. // Ensure the location is unavailable.
  785. Directory.CreateDirectory(ConfigurationManager.ApplicationPaths.GameGenrePath);
  786. return new GameGenresValidator(this, _userManager, _logger).Run(progress, cancellationToken);
  787. }
  788. /// <summary>
  789. /// Validates the studios.
  790. /// </summary>
  791. /// <param name="cancellationToken">The cancellation token.</param>
  792. /// <param name="progress">The progress.</param>
  793. /// <returns>Task.</returns>
  794. public Task ValidateStudios(CancellationToken cancellationToken, IProgress<double> progress)
  795. {
  796. // Ensure the location is unavailable.
  797. Directory.CreateDirectory(ConfigurationManager.ApplicationPaths.StudioPath);
  798. return new StudiosValidator(this, _userManager, _logger).Run(progress, cancellationToken);
  799. }
  800. /// <summary>
  801. /// Validates the genres.
  802. /// </summary>
  803. /// <param name="cancellationToken">The cancellation token.</param>
  804. /// <param name="progress">The progress.</param>
  805. /// <returns>Task.</returns>
  806. public Task ValidateGenres(CancellationToken cancellationToken, IProgress<double> progress)
  807. {
  808. // Ensure the location is unavailable.
  809. Directory.CreateDirectory(ConfigurationManager.ApplicationPaths.GenrePath);
  810. return new GenresValidator(this, _userManager, _logger).Run(progress, cancellationToken);
  811. }
  812. /// <summary>
  813. /// Reloads the root media folder
  814. /// </summary>
  815. /// <param name="progress">The progress.</param>
  816. /// <param name="cancellationToken">The cancellation token.</param>
  817. /// <returns>Task.</returns>
  818. public Task ValidateMediaLibrary(IProgress<double> progress, CancellationToken cancellationToken)
  819. {
  820. // Just run the scheduled task so that the user can see it
  821. _taskManager.CancelIfRunningAndQueue<RefreshMediaLibraryTask>();
  822. return Task.FromResult(true);
  823. }
  824. /// <summary>
  825. /// Queues the library scan.
  826. /// </summary>
  827. public void QueueLibraryScan()
  828. {
  829. // Just run the scheduled task so that the user can see it
  830. _taskManager.QueueScheduledTask<RefreshMediaLibraryTask>();
  831. }
  832. /// <summary>
  833. /// Validates the media library internal.
  834. /// </summary>
  835. /// <param name="progress">The progress.</param>
  836. /// <param name="cancellationToken">The cancellation token.</param>
  837. /// <returns>Task.</returns>
  838. public async Task ValidateMediaLibraryInternal(IProgress<double> progress, CancellationToken cancellationToken)
  839. {
  840. _libraryMonitorFactory().Stop();
  841. try
  842. {
  843. await PerformLibraryValidation(progress, cancellationToken).ConfigureAwait(false);
  844. }
  845. finally
  846. {
  847. _libraryMonitorFactory().Start();
  848. }
  849. }
  850. private async Task PerformLibraryValidation(IProgress<double> progress, CancellationToken cancellationToken)
  851. {
  852. _logger.Info("Validating media library");
  853. await RootFolder.RefreshMetadata(cancellationToken).ConfigureAwait(false);
  854. progress.Report(.5);
  855. // Start by just validating the children of the root, but go no further
  856. await RootFolder.ValidateChildren(new Progress<double>(), cancellationToken, new MetadataRefreshOptions(), recursive: false);
  857. progress.Report(1);
  858. var userRoot = GetUserRootFolder();
  859. await userRoot.RefreshMetadata(cancellationToken).ConfigureAwait(false);
  860. await userRoot.ValidateChildren(new Progress<double>(), cancellationToken, new MetadataRefreshOptions(), recursive: false).ConfigureAwait(false);
  861. progress.Report(2);
  862. var innerProgress = new ActionableProgress<double>();
  863. innerProgress.RegisterAction(pct => progress.Report(2 + pct * .73));
  864. // Now validate the entire media library
  865. await RootFolder.ValidateChildren(innerProgress, cancellationToken, new MetadataRefreshOptions(), recursive: true).ConfigureAwait(false);
  866. progress.Report(75);
  867. innerProgress = new ActionableProgress<double>();
  868. innerProgress.RegisterAction(pct => progress.Report(75 + pct * .25));
  869. // Run post-scan tasks
  870. await RunPostScanTasks(innerProgress, cancellationToken).ConfigureAwait(false);
  871. progress.Report(100);
  872. // Bad practice, i know. But we keep a lot in memory, unfortunately.
  873. GC.Collect(2, GCCollectionMode.Forced, true);
  874. GC.Collect(2, GCCollectionMode.Forced, true);
  875. }
  876. /// <summary>
  877. /// Runs the post scan tasks.
  878. /// </summary>
  879. /// <param name="progress">The progress.</param>
  880. /// <param name="cancellationToken">The cancellation token.</param>
  881. /// <returns>Task.</returns>
  882. private async Task RunPostScanTasks(IProgress<double> progress, CancellationToken cancellationToken)
  883. {
  884. var tasks = PostscanTasks.ToList();
  885. var numComplete = 0;
  886. var numTasks = tasks.Count;
  887. foreach (var task in tasks)
  888. {
  889. var innerProgress = new ActionableProgress<double>();
  890. // Prevent access to modified closure
  891. var currentNumComplete = numComplete;
  892. innerProgress.RegisterAction(pct =>
  893. {
  894. double innerPercent = (currentNumComplete * 100) + pct;
  895. innerPercent /= numTasks;
  896. progress.Report(innerPercent);
  897. });
  898. try
  899. {
  900. await task.Run(innerProgress, cancellationToken);
  901. }
  902. catch (OperationCanceledException)
  903. {
  904. _logger.Info("Post-scan task cancelled: {0}", task.GetType().Name);
  905. }
  906. catch (Exception ex)
  907. {
  908. _logger.ErrorException("Error running postscan task", ex);
  909. }
  910. numComplete++;
  911. double percent = numComplete;
  912. percent /= numTasks;
  913. progress.Report(percent * 100);
  914. }
  915. progress.Report(100);
  916. }
  917. /// <summary>
  918. /// Gets the default view.
  919. /// </summary>
  920. /// <returns>IEnumerable{VirtualFolderInfo}.</returns>
  921. public IEnumerable<VirtualFolderInfo> GetDefaultVirtualFolders()
  922. {
  923. return GetView(ConfigurationManager.ApplicationPaths.DefaultUserViewsPath);
  924. }
  925. /// <summary>
  926. /// Gets the view.
  927. /// </summary>
  928. /// <param name="user">The user.</param>
  929. /// <returns>IEnumerable{VirtualFolderInfo}.</returns>
  930. public IEnumerable<VirtualFolderInfo> GetVirtualFolders(User user)
  931. {
  932. return GetDefaultVirtualFolders();
  933. }
  934. /// <summary>
  935. /// Gets the view.
  936. /// </summary>
  937. /// <param name="path">The path.</param>
  938. /// <returns>IEnumerable{VirtualFolderInfo}.</returns>
  939. private IEnumerable<VirtualFolderInfo> GetView(string path)
  940. {
  941. return Directory.EnumerateDirectories(path, "*", SearchOption.TopDirectoryOnly)
  942. .Select(dir => new VirtualFolderInfo
  943. {
  944. Name = Path.GetFileName(dir),
  945. Locations = Directory.EnumerateFiles(dir, "*.mblink", SearchOption.TopDirectoryOnly)
  946. .Select(_fileSystem.ResolveShortcut)
  947. .OrderBy(i => i)
  948. .ToList(),
  949. CollectionType = GetCollectionType(dir)
  950. });
  951. }
  952. private string GetCollectionType(string path)
  953. {
  954. return new DirectoryInfo(path).EnumerateFiles("*.collection", SearchOption.TopDirectoryOnly)
  955. .Select(i => _fileSystem.GetFileNameWithoutExtension(i))
  956. .FirstOrDefault();
  957. }
  958. /// <summary>
  959. /// Gets the item by id.
  960. /// </summary>
  961. /// <param name="id">The id.</param>
  962. /// <returns>BaseItem.</returns>
  963. /// <exception cref="System.ArgumentNullException">id</exception>
  964. public BaseItem GetItemById(Guid id)
  965. {
  966. if (id == Guid.Empty)
  967. {
  968. throw new ArgumentNullException("id");
  969. }
  970. BaseItem item;
  971. if (LibraryItemsCache.TryGetValue(id, out item))
  972. {
  973. return item;
  974. }
  975. item = RetrieveItem(id);
  976. if (item != null)
  977. {
  978. RegisterItem(item);
  979. }
  980. return item;
  981. }
  982. public BaseItem GetMemoryItemById(Guid id)
  983. {
  984. if (id == Guid.Empty)
  985. {
  986. throw new ArgumentNullException("id");
  987. }
  988. BaseItem item;
  989. LibraryItemsCache.TryGetValue(id, out item);
  990. return item;
  991. }
  992. /// <summary>
  993. /// Gets the intros.
  994. /// </summary>
  995. /// <param name="item">The item.</param>
  996. /// <param name="user">The user.</param>
  997. /// <returns>IEnumerable{System.String}.</returns>
  998. public async Task<IEnumerable<Video>> GetIntros(BaseItem item, User user)
  999. {
  1000. var tasks = IntroProviders
  1001. .OrderBy(i => (i.GetType().Name.IndexOf("Default", StringComparison.OrdinalIgnoreCase) == -1 ? 0 : 1))
  1002. .Take(1)
  1003. .Select(i => GetIntros(i, item, user));
  1004. var items = await Task.WhenAll(tasks).ConfigureAwait(false);
  1005. return items
  1006. .SelectMany(i => i.ToArray())
  1007. .Select(ResolveIntro)
  1008. .Where(i => i != null);
  1009. }
  1010. /// <summary>
  1011. /// Gets the intros.
  1012. /// </summary>
  1013. /// <param name="provider">The provider.</param>
  1014. /// <param name="item">The item.</param>
  1015. /// <param name="user">The user.</param>
  1016. /// <returns>Task&lt;IEnumerable&lt;IntroInfo&gt;&gt;.</returns>
  1017. private async Task<IEnumerable<IntroInfo>> GetIntros(IIntroProvider provider, BaseItem item, User user)
  1018. {
  1019. try
  1020. {
  1021. return await provider.GetIntros(item, user).ConfigureAwait(false);
  1022. }
  1023. catch (Exception ex)
  1024. {
  1025. _logger.ErrorException("Error getting intros", ex);
  1026. return new List<IntroInfo>();
  1027. }
  1028. }
  1029. /// <summary>
  1030. /// Gets all intro files.
  1031. /// </summary>
  1032. /// <returns>IEnumerable{System.String}.</returns>
  1033. public IEnumerable<string> GetAllIntroFiles()
  1034. {
  1035. return IntroProviders.SelectMany(i =>
  1036. {
  1037. try
  1038. {
  1039. return i.GetAllIntroFiles().ToList();
  1040. }
  1041. catch (Exception ex)
  1042. {
  1043. _logger.ErrorException("Error getting intro files", ex);
  1044. return new List<string>();
  1045. }
  1046. });
  1047. }
  1048. /// <summary>
  1049. /// Resolves the intro.
  1050. /// </summary>
  1051. /// <param name="info">The info.</param>
  1052. /// <returns>Video.</returns>
  1053. private Video ResolveIntro(IntroInfo info)
  1054. {
  1055. Video video = null;
  1056. if (info.ItemId.HasValue)
  1057. {
  1058. // Get an existing item by Id
  1059. video = GetItemById(info.ItemId.Value) as Video;
  1060. if (video == null)
  1061. {
  1062. _logger.Error("Unable to locate item with Id {0}.", info.ItemId.Value);
  1063. }
  1064. }
  1065. else if (!string.IsNullOrEmpty(info.Path))
  1066. {
  1067. try
  1068. {
  1069. // Try to resolve the path into a video
  1070. video = ResolvePath(_fileSystem.GetFileSystemInfo(info.Path)) as Video;
  1071. if (video == null)
  1072. {
  1073. _logger.Error("Intro resolver returned null for {0}.", info.Path);
  1074. }
  1075. else
  1076. {
  1077. // Pull the saved db item that will include metadata
  1078. var dbItem = GetItemById(video.Id) as Video;
  1079. if (dbItem != null)
  1080. {
  1081. video = dbItem;
  1082. }
  1083. }
  1084. }
  1085. catch (Exception ex)
  1086. {
  1087. _logger.ErrorException("Error resolving path {0}.", ex, info.Path);
  1088. }
  1089. }
  1090. else
  1091. {
  1092. _logger.Error("IntroProvider returned an IntroInfo with null Path and ItemId.");
  1093. }
  1094. return video;
  1095. }
  1096. /// <summary>
  1097. /// Sorts the specified sort by.
  1098. /// </summary>
  1099. /// <param name="items">The items.</param>
  1100. /// <param name="user">The user.</param>
  1101. /// <param name="sortBy">The sort by.</param>
  1102. /// <param name="sortOrder">The sort order.</param>
  1103. /// <returns>IEnumerable{BaseItem}.</returns>
  1104. public IEnumerable<BaseItem> Sort(IEnumerable<BaseItem> items, User user, IEnumerable<string> sortBy, SortOrder sortOrder)
  1105. {
  1106. var isFirst = true;
  1107. IOrderedEnumerable<BaseItem> orderedItems = null;
  1108. foreach (var orderBy in sortBy.Select(o => GetComparer(o, user)).Where(c => c != null))
  1109. {
  1110. if (isFirst)
  1111. {
  1112. orderedItems = sortOrder == SortOrder.Descending ? items.OrderByDescending(i => i, orderBy) : items.OrderBy(i => i, orderBy);
  1113. }
  1114. else
  1115. {
  1116. orderedItems = sortOrder == SortOrder.Descending ? orderedItems.ThenByDescending(i => i, orderBy) : orderedItems.ThenBy(i => i, orderBy);
  1117. }
  1118. isFirst = false;
  1119. }
  1120. return orderedItems ?? items;
  1121. }
  1122. /// <summary>
  1123. /// Gets the comparer.
  1124. /// </summary>
  1125. /// <param name="name">The name.</param>
  1126. /// <param name="user">The user.</param>
  1127. /// <returns>IBaseItemComparer.</returns>
  1128. private IBaseItemComparer GetComparer(string name, User user)
  1129. {
  1130. var comparer = Comparers.FirstOrDefault(c => string.Equals(name, c.Name, StringComparison.OrdinalIgnoreCase));
  1131. if (comparer != null)
  1132. {
  1133. // If it requires a user, create a new one, and assign the user
  1134. if (comparer is IUserBaseItemComparer)
  1135. {
  1136. var userComparer = (IUserBaseItemComparer)Activator.CreateInstance(comparer.GetType());
  1137. userComparer.User = user;
  1138. userComparer.UserManager = _userManager;
  1139. userComparer.UserDataRepository = _userDataRepository;
  1140. return userComparer;
  1141. }
  1142. }
  1143. return comparer;
  1144. }
  1145. /// <summary>
  1146. /// Creates the item.
  1147. /// </summary>
  1148. /// <param name="item">The item.</param>
  1149. /// <param name="cancellationToken">The cancellation token.</param>
  1150. /// <returns>Task.</returns>
  1151. public Task CreateItem(BaseItem item, CancellationToken cancellationToken)
  1152. {
  1153. return CreateItems(new[] { item }, cancellationToken);
  1154. }
  1155. /// <summary>
  1156. /// Creates the items.
  1157. /// </summary>
  1158. /// <param name="items">The items.</param>
  1159. /// <param name="cancellationToken">The cancellation token.</param>
  1160. /// <returns>Task.</returns>
  1161. public async Task CreateItems(IEnumerable<BaseItem> items, CancellationToken cancellationToken)
  1162. {
  1163. var list = items.ToList();
  1164. await ItemRepository.SaveItems(list, cancellationToken).ConfigureAwait(false);
  1165. foreach (var item in list)
  1166. {
  1167. UpdateItemInLibraryCache(item);
  1168. }
  1169. if (ItemAdded != null)
  1170. {
  1171. foreach (var item in list)
  1172. {
  1173. try
  1174. {
  1175. ItemAdded(this, new ItemChangeEventArgs { Item = item });
  1176. }
  1177. catch (Exception ex)
  1178. {
  1179. _logger.ErrorException("Error in ItemAdded event handler", ex);
  1180. }
  1181. }
  1182. }
  1183. }
  1184. /// <summary>
  1185. /// Updates the item.
  1186. /// </summary>
  1187. /// <param name="item">The item.</param>
  1188. /// <param name="updateReason">The update reason.</param>
  1189. /// <param name="cancellationToken">The cancellation token.</param>
  1190. /// <returns>Task.</returns>
  1191. public async Task UpdateItem(BaseItem item, ItemUpdateType updateReason, CancellationToken cancellationToken)
  1192. {
  1193. var locationType = item.LocationType;
  1194. if (locationType != LocationType.Remote && locationType != LocationType.Virtual)
  1195. {
  1196. await _providerManagerFactory().SaveMetadata(item, updateReason).ConfigureAwait(false);
  1197. }
  1198. item.DateLastSaved = DateTime.UtcNow;
  1199. var logName = item.LocationType == LocationType.Remote ? item.Name ?? item.Path : item.Path ?? item.Name;
  1200. _logger.Debug("Saving {0} to database.", logName);
  1201. await ItemRepository.SaveItem(item, cancellationToken).ConfigureAwait(false);
  1202. UpdateItemInLibraryCache(item);
  1203. if (ItemUpdated != null)
  1204. {
  1205. try
  1206. {
  1207. ItemUpdated(this, new ItemChangeEventArgs
  1208. {
  1209. Item = item,
  1210. UpdateReason = updateReason
  1211. });
  1212. }
  1213. catch (Exception ex)
  1214. {
  1215. _logger.ErrorException("Error in ItemUpdated event handler", ex);
  1216. }
  1217. }
  1218. }
  1219. /// <summary>
  1220. /// Reports the item removed.
  1221. /// </summary>
  1222. /// <param name="item">The item.</param>
  1223. public void ReportItemRemoved(BaseItem item)
  1224. {
  1225. if (ItemRemoved != null)
  1226. {
  1227. try
  1228. {
  1229. ItemRemoved(this, new ItemChangeEventArgs { Item = item });
  1230. }
  1231. catch (Exception ex)
  1232. {
  1233. _logger.ErrorException("Error in ItemRemoved event handler", ex);
  1234. }
  1235. }
  1236. }
  1237. /// <summary>
  1238. /// Retrieves the item.
  1239. /// </summary>
  1240. /// <param name="id">The id.</param>
  1241. /// <returns>BaseItem.</returns>
  1242. public BaseItem RetrieveItem(Guid id)
  1243. {
  1244. return ItemRepository.RetrieveItem(id);
  1245. }
  1246. /// <summary>
  1247. /// Finds the type of the collection.
  1248. /// </summary>
  1249. /// <param name="item">The item.</param>
  1250. /// <returns>System.String.</returns>
  1251. public string FindCollectionType(BaseItem item)
  1252. {
  1253. while (!(item.Parent is AggregateFolder) && item.Parent != null)
  1254. {
  1255. item = item.Parent;
  1256. }
  1257. if (item == null)
  1258. {
  1259. return null;
  1260. }
  1261. var collectionTypes = GetUserRootFolder().Children
  1262. .OfType<ICollectionFolder>()
  1263. .Where(i => !string.IsNullOrEmpty(i.CollectionType) && (string.Equals(i.Path, item.Path, StringComparison.OrdinalIgnoreCase) || i.PhysicalLocations.Contains(item.Path)))
  1264. .Select(i => i.CollectionType)
  1265. .Distinct()
  1266. .ToList();
  1267. return collectionTypes.Count == 1 ? collectionTypes[0] : null;
  1268. }
  1269. public async Task<UserView> GetNamedView(string name,
  1270. string type,
  1271. string sortName,
  1272. CancellationToken cancellationToken)
  1273. {
  1274. var path = Path.Combine(ConfigurationManager.ApplicationPaths.ItemsByNamePath,
  1275. "views");
  1276. path = Path.Combine(path, _fileSystem.GetValidFilename(type));
  1277. var id = (path + "_namedview_" + name).GetMBId(typeof(UserView));
  1278. var item = GetItemById(id) as UserView;
  1279. var refresh = false;
  1280. if (item == null ||
  1281. !string.Equals(item.Path, path, StringComparison.OrdinalIgnoreCase))
  1282. {
  1283. Directory.CreateDirectory(path);
  1284. item = new UserView
  1285. {
  1286. Path = path,
  1287. Id = id,
  1288. DateCreated = DateTime.UtcNow,
  1289. Name = name,
  1290. ViewType = type,
  1291. ForcedSortName = sortName
  1292. };
  1293. await CreateItem(item, cancellationToken).ConfigureAwait(false);
  1294. refresh = true;
  1295. }
  1296. if (!refresh && item != null)
  1297. {
  1298. refresh = (DateTime.UtcNow - item.DateLastSaved).TotalHours >= 24;
  1299. }
  1300. if (refresh)
  1301. {
  1302. await item.RefreshMetadata(new MetadataRefreshOptions
  1303. {
  1304. ForceSave = true
  1305. }, cancellationToken).ConfigureAwait(false);
  1306. }
  1307. return item;
  1308. }
  1309. public async Task<UserView> GetSpecialFolder(User user,
  1310. string name,
  1311. string parentId,
  1312. string viewType,
  1313. string sortName,
  1314. CancellationToken cancellationToken)
  1315. {
  1316. if (string.IsNullOrWhiteSpace(name))
  1317. {
  1318. throw new ArgumentNullException("name");
  1319. }
  1320. if (string.IsNullOrWhiteSpace(parentId))
  1321. {
  1322. throw new ArgumentNullException("parentId");
  1323. }
  1324. if (string.IsNullOrWhiteSpace(viewType))
  1325. {
  1326. throw new ArgumentNullException("viewType");
  1327. }
  1328. var id = ("7_namedview_" + name + user.Id.ToString("N") + parentId).GetMBId(typeof(UserView));
  1329. var path = BaseItem.GetInternalMetadataPathForId(id);
  1330. var item = GetItemById(id) as UserView;
  1331. var refresh = false;
  1332. if (item == null)
  1333. {
  1334. Directory.CreateDirectory(path);
  1335. item = new UserView
  1336. {
  1337. Path = path,
  1338. Id = id,
  1339. DateCreated = DateTime.UtcNow,
  1340. Name = name,
  1341. ViewType = viewType,
  1342. ForcedSortName = sortName,
  1343. UserId = user.Id,
  1344. ParentId = new Guid(parentId)
  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 bool IsVideoFile(string path)
  1363. {
  1364. var resolver = new VideoResolver(new ExpandedVideoOptions(), new AudioOptions(), new Naming.Logging.NullLogger());
  1365. return resolver.IsVideoFile(path);
  1366. }
  1367. public bool IsAudioFile(string path)
  1368. {
  1369. var parser = new AudioFileParser(new AudioOptions());
  1370. return parser.IsAudioFile(path);
  1371. }
  1372. public int? GetSeasonNumberFromPath(string path)
  1373. {
  1374. return SeriesResolver.GetSeasonNumberFromPath(path);
  1375. }
  1376. public int? GetSeasonNumberFromEpisodeFile(string path)
  1377. {
  1378. return SeriesResolver.GetSeasonNumberFromEpisodeFile(path);
  1379. }
  1380. public int? GetEndingEpisodeNumberFromFile(string path)
  1381. {
  1382. return SeriesResolver.GetEndingEpisodeNumberFromFile(path);
  1383. }
  1384. public int? GetEpisodeNumberFromFile(string path, bool considerSeasonless)
  1385. {
  1386. return SeriesResolver.GetEpisodeNumberFromFile(path, considerSeasonless);
  1387. }
  1388. public ItemLookupInfo ParseName(string name)
  1389. {
  1390. var resolver = new VideoResolver(new ExpandedVideoOptions(), new AudioOptions(), new Naming.Logging.NullLogger());
  1391. var result = resolver.CleanDateTime(name);
  1392. var cleanName = resolver.CleanString(result.Name);
  1393. return new ItemLookupInfo
  1394. {
  1395. Name = cleanName.Name,
  1396. Year = result.Year
  1397. };
  1398. }
  1399. public IEnumerable<FileSystemInfo> GetAdditionalParts(string file,
  1400. VideoType type,
  1401. IEnumerable<FileSystemInfo> files)
  1402. {
  1403. var resolver = new StackResolver(new ExpandedVideoOptions(), new AudioOptions(), new Naming.Logging.NullLogger());
  1404. StackResult result;
  1405. List<FileSystemInfo> filteredFiles;
  1406. if (type == VideoType.BluRay || type == VideoType.Dvd)
  1407. {
  1408. filteredFiles = files.Where(i => (i.Attributes & FileAttributes.Directory) == FileAttributes.Directory)
  1409. .ToList();
  1410. result = resolver.ResolveDirectories(filteredFiles.Select(i => i.FullName));
  1411. }
  1412. else
  1413. {
  1414. filteredFiles = files.Where(i => (i.Attributes & FileAttributes.Directory) != FileAttributes.Directory)
  1415. .ToList();
  1416. result = resolver.ResolveFiles(filteredFiles.Select(i => i.FullName));
  1417. }
  1418. var stack = result.Stacks
  1419. .FirstOrDefault(i => i.Files.Contains(file, StringComparer.OrdinalIgnoreCase));
  1420. if (stack != null)
  1421. {
  1422. return stack.Files.Where(i => !string.Equals(i, file, StringComparison.OrdinalIgnoreCase))
  1423. .Select(i => filteredFiles.FirstOrDefault(f => string.Equals(i, f.FullName, StringComparison.OrdinalIgnoreCase)))
  1424. .Where(i => i != null);
  1425. }
  1426. return new List<FileSystemInfo>();
  1427. }
  1428. }
  1429. }