LibraryManager.cs 68 KB

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