MetadataService.cs 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235
  1. #nullable disable
  2. #pragma warning disable CS1591
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6. using System.Net.Http;
  7. using System.Threading;
  8. using System.Threading.Tasks;
  9. using Jellyfin.Extensions;
  10. using MediaBrowser.Controller.Configuration;
  11. using MediaBrowser.Controller.Entities;
  12. using MediaBrowser.Controller.Entities.Audio;
  13. using MediaBrowser.Controller.Library;
  14. using MediaBrowser.Controller.Providers;
  15. using MediaBrowser.Model.Configuration;
  16. using MediaBrowser.Model.Entities;
  17. using MediaBrowser.Model.IO;
  18. using MediaBrowser.Model.Providers;
  19. using Microsoft.Extensions.Logging;
  20. namespace MediaBrowser.Providers.Manager
  21. {
  22. public abstract class MetadataService<TItemType, TIdType> : IMetadataService
  23. where TItemType : BaseItem, IHasLookupInfo<TIdType>, new()
  24. where TIdType : ItemLookupInfo, new()
  25. {
  26. protected MetadataService(IServerConfigurationManager serverConfigurationManager, ILogger<MetadataService<TItemType, TIdType>> logger, IProviderManager providerManager, IFileSystem fileSystem, ILibraryManager libraryManager)
  27. {
  28. ServerConfigurationManager = serverConfigurationManager;
  29. Logger = logger;
  30. ProviderManager = providerManager;
  31. FileSystem = fileSystem;
  32. LibraryManager = libraryManager;
  33. ImageProvider = new ItemImageProvider(Logger, ProviderManager, FileSystem);
  34. }
  35. protected ItemImageProvider ImageProvider { get; }
  36. protected IServerConfigurationManager ServerConfigurationManager { get; }
  37. protected ILogger<MetadataService<TItemType, TIdType>> Logger { get; }
  38. protected IProviderManager ProviderManager { get; }
  39. protected IFileSystem FileSystem { get; }
  40. protected ILibraryManager LibraryManager { get; }
  41. protected virtual bool EnableUpdatingPremiereDateFromChildren => false;
  42. protected virtual bool EnableUpdatingGenresFromChildren => false;
  43. protected virtual bool EnableUpdatingStudiosFromChildren => false;
  44. protected virtual bool EnableUpdatingOfficialRatingFromChildren => false;
  45. public virtual int Order => 0;
  46. private FileSystemMetadata TryGetFile(string path, IDirectoryService directoryService)
  47. {
  48. try
  49. {
  50. return directoryService.GetFile(path);
  51. }
  52. catch (Exception ex)
  53. {
  54. Logger.LogError(ex, "Error getting file {Path}", path);
  55. return null;
  56. }
  57. }
  58. public virtual async Task<ItemUpdateType> RefreshMetadata(BaseItem item, MetadataRefreshOptions refreshOptions, CancellationToken cancellationToken)
  59. {
  60. var itemOfType = (TItemType)item;
  61. var updateType = ItemUpdateType.None;
  62. var libraryOptions = LibraryManager.GetLibraryOptions(item);
  63. var isFirstRefresh = item.DateLastRefreshed == default;
  64. var hasRefreshedMetadata = true;
  65. var hasRefreshedImages = true;
  66. var requiresRefresh = libraryOptions.AutomaticRefreshIntervalDays > 0 && (DateTime.UtcNow - item.DateLastRefreshed).TotalDays >= libraryOptions.AutomaticRefreshIntervalDays;
  67. if (!requiresRefresh && refreshOptions.MetadataRefreshMode != MetadataRefreshMode.None)
  68. {
  69. // TODO: If this returns true, should we instead just change metadata refresh mode to Full?
  70. requiresRefresh = item.RequiresRefresh();
  71. if (requiresRefresh)
  72. {
  73. Logger.LogDebug("Refreshing {Type} {Item} because item.RequiresRefresh() returned true", typeof(TItemType).Name, item.Path ?? item.Name);
  74. }
  75. }
  76. if (refreshOptions.RemoveOldMetadata && refreshOptions.ReplaceAllImages)
  77. {
  78. if (ImageProvider.RemoveImages(item))
  79. {
  80. updateType |= ItemUpdateType.ImageUpdate;
  81. }
  82. }
  83. var localImagesFailed = false;
  84. var allImageProviders = ProviderManager.GetImageProviders(item, refreshOptions).ToList();
  85. // Only validate already registered images if we are replacing and saving locally
  86. if (item.IsSaveLocalMetadataEnabled() && refreshOptions.ReplaceAllImages)
  87. {
  88. item.ValidateImages();
  89. }
  90. else
  91. {
  92. // Run full image validation and register new local images
  93. try
  94. {
  95. if (ImageProvider.ValidateImages(item, allImageProviders.OfType<ILocalImageProvider>(), refreshOptions))
  96. {
  97. updateType |= ItemUpdateType.ImageUpdate;
  98. }
  99. }
  100. catch (Exception ex)
  101. {
  102. localImagesFailed = true;
  103. Logger.LogError(ex, "Error validating images for {Item}", item.Path ?? item.Name ?? "Unknown name");
  104. }
  105. }
  106. var metadataResult = new MetadataResult<TItemType>
  107. {
  108. Item = itemOfType,
  109. People = LibraryManager.GetPeople(item)
  110. };
  111. var beforeSaveResult = BeforeSave(itemOfType, isFirstRefresh || refreshOptions.ReplaceAllMetadata || refreshOptions.MetadataRefreshMode == MetadataRefreshMode.FullRefresh || requiresRefresh || refreshOptions.ForceSave, updateType);
  112. updateType |= beforeSaveResult;
  113. updateType = await SaveInternal(item, refreshOptions, updateType, isFirstRefresh, requiresRefresh, metadataResult, cancellationToken).ConfigureAwait(false);
  114. // Next run metadata providers
  115. if (refreshOptions.MetadataRefreshMode != MetadataRefreshMode.None)
  116. {
  117. var providers = GetProviders(item, libraryOptions, refreshOptions, isFirstRefresh, requiresRefresh)
  118. .ToList();
  119. if (providers.Count > 0 || isFirstRefresh || requiresRefresh)
  120. {
  121. if (item.BeforeMetadataRefresh(refreshOptions.ReplaceAllMetadata))
  122. {
  123. updateType |= ItemUpdateType.MetadataImport;
  124. }
  125. }
  126. if (providers.Count > 0)
  127. {
  128. var id = itemOfType.GetLookupInfo();
  129. if (refreshOptions.SearchResult is not null)
  130. {
  131. ApplySearchResult(id, refreshOptions.SearchResult);
  132. }
  133. id.IsAutomated = refreshOptions.IsAutomated;
  134. var hasMetadataSavers = ProviderManager.GetMetadataSavers(item, libraryOptions).Any();
  135. var result = await RefreshWithProviders(metadataResult, id, refreshOptions, providers, ImageProvider, hasMetadataSavers, cancellationToken).ConfigureAwait(false);
  136. updateType |= result.UpdateType;
  137. if (result.Failures > 0)
  138. {
  139. hasRefreshedMetadata = false;
  140. }
  141. }
  142. }
  143. // Next run remote image providers, but only if local image providers didn't throw an exception
  144. if (!localImagesFailed && refreshOptions.ImageRefreshMode > MetadataRefreshMode.ValidationOnly)
  145. {
  146. var providers = GetNonLocalImageProviders(item, allImageProviders, refreshOptions).ToList();
  147. if (providers.Count > 0)
  148. {
  149. var result = await ImageProvider.RefreshImages(itemOfType, libraryOptions, providers, refreshOptions, cancellationToken).ConfigureAwait(false);
  150. updateType |= result.UpdateType;
  151. if (result.Failures > 0)
  152. {
  153. hasRefreshedImages = false;
  154. }
  155. }
  156. }
  157. if (hasRefreshedMetadata && hasRefreshedImages)
  158. {
  159. item.DateLastRefreshed = DateTime.UtcNow;
  160. }
  161. updateType = await SaveInternal(item, refreshOptions, updateType, isFirstRefresh, requiresRefresh, metadataResult, cancellationToken).ConfigureAwait(false);
  162. await AfterMetadataRefresh(itemOfType, refreshOptions, cancellationToken).ConfigureAwait(false);
  163. return updateType;
  164. async Task<ItemUpdateType> SaveInternal(BaseItem item, MetadataRefreshOptions refreshOptions, ItemUpdateType updateType, bool isFirstRefresh, bool requiresRefresh, MetadataResult<TItemType> metadataResult, CancellationToken cancellationToken)
  165. {
  166. // Save if changes were made, or it's never been saved before
  167. if (refreshOptions.ForceSave || updateType > ItemUpdateType.None || isFirstRefresh || refreshOptions.ReplaceAllMetadata || requiresRefresh)
  168. {
  169. if (item.IsFileProtocol)
  170. {
  171. var file = TryGetFile(item.Path, refreshOptions.DirectoryService);
  172. if (file is not null)
  173. {
  174. item.DateModified = file.LastWriteTimeUtc;
  175. }
  176. }
  177. // If any of these properties are set then make sure the updateType is not None, just to force everything to save
  178. if (refreshOptions.ForceSave || refreshOptions.ReplaceAllMetadata)
  179. {
  180. updateType |= ItemUpdateType.MetadataDownload;
  181. }
  182. // Save to database
  183. await SaveItemAsync(metadataResult, updateType, cancellationToken).ConfigureAwait(false);
  184. }
  185. return updateType;
  186. }
  187. }
  188. private void ApplySearchResult(ItemLookupInfo lookupInfo, RemoteSearchResult result)
  189. {
  190. // Episode and Season do not support Identify, so the search results are the Series'
  191. switch (lookupInfo)
  192. {
  193. case EpisodeInfo episodeInfo:
  194. episodeInfo.SeriesProviderIds = result.ProviderIds;
  195. episodeInfo.ProviderIds.Clear();
  196. break;
  197. case SeasonInfo seasonInfo:
  198. seasonInfo.SeriesProviderIds = result.ProviderIds;
  199. seasonInfo.ProviderIds.Clear();
  200. break;
  201. default:
  202. lookupInfo.ProviderIds = result.ProviderIds;
  203. lookupInfo.Name = result.Name;
  204. lookupInfo.Year = result.ProductionYear;
  205. break;
  206. }
  207. }
  208. protected async Task SaveItemAsync(MetadataResult<TItemType> result, ItemUpdateType reason, CancellationToken cancellationToken)
  209. {
  210. if (result.Item.SupportsPeople)
  211. {
  212. var baseItem = result.Item;
  213. await LibraryManager.UpdatePeopleAsync(baseItem, result.People, cancellationToken).ConfigureAwait(false);
  214. }
  215. await result.Item.UpdateToRepositoryAsync(reason, cancellationToken).ConfigureAwait(false);
  216. }
  217. protected virtual Task AfterMetadataRefresh(TItemType item, MetadataRefreshOptions refreshOptions, CancellationToken cancellationToken)
  218. {
  219. item.AfterMetadataRefresh();
  220. return Task.CompletedTask;
  221. }
  222. /// <summary>
  223. /// Before the save.
  224. /// </summary>
  225. /// <param name="item">The item.</param>
  226. /// <param name="isFullRefresh">if set to <c>true</c> [is full refresh].</param>
  227. /// <param name="currentUpdateType">Type of the current update.</param>
  228. /// <returns>ItemUpdateType.</returns>
  229. private ItemUpdateType BeforeSave(TItemType item, bool isFullRefresh, ItemUpdateType currentUpdateType)
  230. {
  231. var updateType = BeforeSaveInternal(item, isFullRefresh, currentUpdateType);
  232. updateType |= item.OnMetadataChanged();
  233. return updateType;
  234. }
  235. protected virtual ItemUpdateType BeforeSaveInternal(TItemType item, bool isFullRefresh, ItemUpdateType updateType)
  236. {
  237. if (EnableUpdateMetadataFromChildren(item, isFullRefresh, updateType))
  238. {
  239. if (isFullRefresh || updateType > ItemUpdateType.None)
  240. {
  241. var children = GetChildrenForMetadataUpdates(item);
  242. updateType = UpdateMetadataFromChildren(item, children, isFullRefresh, updateType);
  243. }
  244. }
  245. var presentationUniqueKey = item.CreatePresentationUniqueKey();
  246. if (!string.Equals(item.PresentationUniqueKey, presentationUniqueKey, StringComparison.Ordinal))
  247. {
  248. item.PresentationUniqueKey = presentationUniqueKey;
  249. updateType |= ItemUpdateType.MetadataImport;
  250. }
  251. return updateType;
  252. }
  253. protected virtual bool EnableUpdateMetadataFromChildren(TItemType item, bool isFullRefresh, ItemUpdateType currentUpdateType)
  254. {
  255. if (isFullRefresh || currentUpdateType > ItemUpdateType.None)
  256. {
  257. if (EnableUpdatingPremiereDateFromChildren || EnableUpdatingGenresFromChildren || EnableUpdatingStudiosFromChildren || EnableUpdatingOfficialRatingFromChildren)
  258. {
  259. return true;
  260. }
  261. if (item is Folder folder)
  262. {
  263. return folder.SupportsDateLastMediaAdded || folder.SupportsCumulativeRunTimeTicks;
  264. }
  265. }
  266. return false;
  267. }
  268. protected virtual IReadOnlyList<BaseItem> GetChildrenForMetadataUpdates(TItemType item)
  269. {
  270. if (item is Folder folder)
  271. {
  272. return folder.GetRecursiveChildren();
  273. }
  274. return [];
  275. }
  276. protected virtual ItemUpdateType UpdateMetadataFromChildren(TItemType item, IReadOnlyList<BaseItem> children, bool isFullRefresh, ItemUpdateType currentUpdateType)
  277. {
  278. var updateType = ItemUpdateType.None;
  279. if (isFullRefresh || currentUpdateType > ItemUpdateType.None)
  280. {
  281. updateType |= UpdateCumulativeRunTimeTicks(item, children);
  282. updateType |= UpdateDateLastMediaAdded(item, children);
  283. // don't update user-changeable metadata for locked items
  284. if (item.IsLocked)
  285. {
  286. return updateType;
  287. }
  288. if (EnableUpdatingPremiereDateFromChildren)
  289. {
  290. updateType |= UpdatePremiereDate(item, children);
  291. }
  292. if (EnableUpdatingGenresFromChildren)
  293. {
  294. updateType |= UpdateGenres(item, children);
  295. }
  296. if (EnableUpdatingStudiosFromChildren)
  297. {
  298. updateType |= UpdateStudios(item, children);
  299. }
  300. if (EnableUpdatingOfficialRatingFromChildren)
  301. {
  302. updateType |= UpdateOfficialRating(item, children);
  303. }
  304. }
  305. return updateType;
  306. }
  307. private ItemUpdateType UpdateCumulativeRunTimeTicks(TItemType item, IReadOnlyList<BaseItem> children)
  308. {
  309. if (item is Folder folder && folder.SupportsCumulativeRunTimeTicks)
  310. {
  311. long ticks = 0;
  312. foreach (var child in children)
  313. {
  314. if (!child.IsFolder)
  315. {
  316. ticks += child.RunTimeTicks ?? 0;
  317. }
  318. }
  319. if (!folder.RunTimeTicks.HasValue || folder.RunTimeTicks.Value != ticks)
  320. {
  321. folder.RunTimeTicks = ticks;
  322. return ItemUpdateType.MetadataImport;
  323. }
  324. }
  325. return ItemUpdateType.None;
  326. }
  327. private ItemUpdateType UpdateDateLastMediaAdded(TItemType item, IReadOnlyList<BaseItem> children)
  328. {
  329. var updateType = ItemUpdateType.None;
  330. if (item is Folder folder && folder.SupportsDateLastMediaAdded)
  331. {
  332. var dateLastMediaAdded = DateTime.MinValue;
  333. var any = false;
  334. foreach (var child in children)
  335. {
  336. // Exclude any folders and virtual items since they are only placeholders
  337. if (!child.IsFolder && !child.IsVirtualItem)
  338. {
  339. var childDateCreated = child.DateCreated;
  340. if (childDateCreated > dateLastMediaAdded)
  341. {
  342. dateLastMediaAdded = childDateCreated;
  343. }
  344. any = true;
  345. }
  346. }
  347. if ((!folder.DateLastMediaAdded.HasValue && any) || folder.DateLastMediaAdded != dateLastMediaAdded)
  348. {
  349. folder.DateLastMediaAdded = dateLastMediaAdded;
  350. updateType = ItemUpdateType.MetadataImport;
  351. }
  352. }
  353. return updateType;
  354. }
  355. private ItemUpdateType UpdatePremiereDate(TItemType item, IReadOnlyList<BaseItem> children)
  356. {
  357. var updateType = ItemUpdateType.None;
  358. if (children.Count == 0)
  359. {
  360. return updateType;
  361. }
  362. var date = children.Select(i => i.PremiereDate ?? DateTime.MaxValue).Min();
  363. var originalPremiereDate = item.PremiereDate;
  364. var originalProductionYear = item.ProductionYear;
  365. if (date > DateTime.MinValue && date < DateTime.MaxValue)
  366. {
  367. item.PremiereDate = date;
  368. item.ProductionYear = date.Year;
  369. }
  370. else
  371. {
  372. var year = children.Select(i => i.ProductionYear ?? 0).Min();
  373. if (year > 0)
  374. {
  375. item.ProductionYear = year;
  376. }
  377. }
  378. if ((originalPremiereDate ?? DateTime.MinValue) != (item.PremiereDate ?? DateTime.MinValue)
  379. || (originalProductionYear ?? -1) != (item.ProductionYear ?? -1))
  380. {
  381. updateType |= ItemUpdateType.MetadataEdit;
  382. }
  383. return updateType;
  384. }
  385. private ItemUpdateType UpdateGenres(TItemType item, IReadOnlyList<BaseItem> children)
  386. {
  387. var updateType = ItemUpdateType.None;
  388. if (!item.LockedFields.Contains(MetadataField.Genres))
  389. {
  390. var currentList = item.Genres;
  391. item.Genres = children.SelectMany(i => i.Genres)
  392. .Distinct(StringComparer.OrdinalIgnoreCase)
  393. .ToArray();
  394. if (currentList.Length != item.Genres.Length || !currentList.Order().SequenceEqual(item.Genres.Order(), StringComparer.OrdinalIgnoreCase))
  395. {
  396. updateType |= ItemUpdateType.MetadataEdit;
  397. }
  398. }
  399. return updateType;
  400. }
  401. private ItemUpdateType UpdateStudios(TItemType item, IReadOnlyList<BaseItem> children)
  402. {
  403. var updateType = ItemUpdateType.None;
  404. if (!item.LockedFields.Contains(MetadataField.Studios))
  405. {
  406. var currentList = item.Studios;
  407. item.Studios = children.SelectMany(i => i.Studios)
  408. .Distinct(StringComparer.OrdinalIgnoreCase)
  409. .ToArray();
  410. if (currentList.Length != item.Studios.Length || !currentList.Order().SequenceEqual(item.Studios.Order(), StringComparer.OrdinalIgnoreCase))
  411. {
  412. updateType |= ItemUpdateType.MetadataEdit;
  413. }
  414. }
  415. return updateType;
  416. }
  417. private ItemUpdateType UpdateOfficialRating(TItemType item, IReadOnlyList<BaseItem> children)
  418. {
  419. var updateType = ItemUpdateType.None;
  420. if (!item.LockedFields.Contains(MetadataField.OfficialRating))
  421. {
  422. if (item.UpdateRatingToItems(children))
  423. {
  424. updateType |= ItemUpdateType.MetadataEdit;
  425. }
  426. }
  427. return updateType;
  428. }
  429. /// <summary>
  430. /// Gets the providers.
  431. /// </summary>
  432. /// <param name="item">A media item.</param>
  433. /// <param name="libraryOptions">The LibraryOptions to use.</param>
  434. /// <param name="options">The MetadataRefreshOptions to use.</param>
  435. /// <param name="isFirstRefresh">Specifies first refresh mode.</param>
  436. /// <param name="requiresRefresh">Specifies refresh mode.</param>
  437. /// <returns>IEnumerable{`0}.</returns>
  438. protected IEnumerable<IMetadataProvider> GetProviders(BaseItem item, LibraryOptions libraryOptions, MetadataRefreshOptions options, bool isFirstRefresh, bool requiresRefresh)
  439. {
  440. // Get providers to refresh
  441. var providers = ProviderManager.GetMetadataProviders<TItemType>(item, libraryOptions).ToList();
  442. var metadataRefreshMode = options.MetadataRefreshMode;
  443. // Run all if either of these flags are true
  444. var runAllProviders = options.ReplaceAllMetadata ||
  445. metadataRefreshMode == MetadataRefreshMode.FullRefresh ||
  446. (isFirstRefresh && metadataRefreshMode >= MetadataRefreshMode.Default) ||
  447. (requiresRefresh && metadataRefreshMode >= MetadataRefreshMode.Default);
  448. if (!runAllProviders)
  449. {
  450. var providersWithChanges = providers
  451. .Where(i =>
  452. {
  453. if (i is IHasItemChangeMonitor hasFileChangeMonitor)
  454. {
  455. return HasChanged(item, hasFileChangeMonitor, options.DirectoryService);
  456. }
  457. return false;
  458. })
  459. .ToList();
  460. if (providersWithChanges.Count == 0)
  461. {
  462. providers = new List<IMetadataProvider<TItemType>>();
  463. }
  464. else
  465. {
  466. var anyRemoteProvidersChanged = providersWithChanges.OfType<IRemoteMetadataProvider>()
  467. .Any();
  468. var anyLocalProvidersChanged = providersWithChanges.OfType<ILocalMetadataProvider>()
  469. .Any();
  470. var anyLocalPreRefreshProvidersChanged = providersWithChanges.OfType<IPreRefreshProvider>()
  471. .Any();
  472. providers = providers.Where(i =>
  473. {
  474. // If any provider reports a change, always run local ones as well
  475. if (i is ILocalMetadataProvider)
  476. {
  477. return anyRemoteProvidersChanged || anyLocalProvidersChanged || anyLocalPreRefreshProvidersChanged;
  478. }
  479. // If any remote providers changed, run them all so that priorities can be honored
  480. if (i is IRemoteMetadataProvider)
  481. {
  482. if (options.MetadataRefreshMode == MetadataRefreshMode.ValidationOnly)
  483. {
  484. return false;
  485. }
  486. return anyRemoteProvidersChanged;
  487. }
  488. // Run custom refresh providers if they report a change or any remote providers change
  489. return anyRemoteProvidersChanged || providersWithChanges.Contains(i);
  490. }).ToList();
  491. }
  492. }
  493. return providers;
  494. }
  495. protected virtual IEnumerable<IImageProvider> GetNonLocalImageProviders(BaseItem item, IEnumerable<IImageProvider> allImageProviders, ImageRefreshOptions options)
  496. {
  497. // Get providers to refresh
  498. var providers = allImageProviders.Where(i => i is not ILocalImageProvider);
  499. var dateLastImageRefresh = item.DateLastRefreshed;
  500. // Run all if either of these flags are true
  501. var runAllProviders = options.ImageRefreshMode == MetadataRefreshMode.FullRefresh || dateLastImageRefresh == default(DateTime);
  502. if (!runAllProviders)
  503. {
  504. providers = providers
  505. .Where(i =>
  506. {
  507. if (i is IHasItemChangeMonitor hasFileChangeMonitor)
  508. {
  509. return HasChanged(item, hasFileChangeMonitor, options.DirectoryService);
  510. }
  511. return false;
  512. });
  513. }
  514. return providers;
  515. }
  516. public bool CanRefresh(BaseItem item)
  517. {
  518. return item is TItemType;
  519. }
  520. public bool CanRefreshPrimary(Type type)
  521. {
  522. return type == typeof(TItemType);
  523. }
  524. protected virtual async Task<RefreshResult> RefreshWithProviders(
  525. MetadataResult<TItemType> metadata,
  526. TIdType id,
  527. MetadataRefreshOptions options,
  528. ICollection<IMetadataProvider> providers,
  529. ItemImageProvider imageService,
  530. bool isSavingMetadata,
  531. CancellationToken cancellationToken)
  532. {
  533. var refreshResult = new RefreshResult
  534. {
  535. UpdateType = ItemUpdateType.None
  536. };
  537. var item = metadata.Item;
  538. var customProviders = providers.OfType<ICustomMetadataProvider<TItemType>>().ToList();
  539. var logName = !item.IsFileProtocol ? item.Name ?? item.Path : item.Path ?? item.Name;
  540. foreach (var provider in customProviders.Where(i => i is IPreRefreshProvider))
  541. {
  542. await RunCustomProvider(provider, item, logName, options, refreshResult, cancellationToken).ConfigureAwait(false);
  543. }
  544. if (item.IsLocked)
  545. {
  546. return refreshResult;
  547. }
  548. var temp = new MetadataResult<TItemType>
  549. {
  550. Item = CreateNew()
  551. };
  552. temp.Item.Path = item.Path;
  553. temp.Item.Id = item.Id;
  554. temp.Item.ParentIndexNumber = item.ParentIndexNumber;
  555. temp.Item.PreferredMetadataCountryCode = item.PreferredMetadataCountryCode;
  556. temp.Item.PreferredMetadataLanguage = item.PreferredMetadataLanguage;
  557. var foundImageTypes = new List<ImageType>();
  558. // Do not execute local providers if we are identifying or replacing with local metadata saving enabled
  559. if (options.SearchResult is null && !(isSavingMetadata && options.ReplaceAllMetadata))
  560. {
  561. foreach (var provider in providers.OfType<ILocalMetadataProvider<TItemType>>())
  562. {
  563. var providerName = provider.GetType().Name;
  564. Logger.LogDebug("Running {Provider} for {Item}", providerName, logName);
  565. var itemInfo = new ItemInfo(item);
  566. try
  567. {
  568. var localItem = await provider.GetMetadata(itemInfo, options.DirectoryService, cancellationToken).ConfigureAwait(false);
  569. if (localItem.HasMetadata)
  570. {
  571. foreach (var remoteImage in localItem.RemoteImages)
  572. {
  573. try
  574. {
  575. if (item.ImageInfos.Any(x => x.Type == remoteImage.Type)
  576. && !options.IsReplacingImage(remoteImage.Type))
  577. {
  578. continue;
  579. }
  580. await ProviderManager.SaveImage(item, remoteImage.Url, remoteImage.Type, null, cancellationToken).ConfigureAwait(false);
  581. refreshResult.UpdateType |= ItemUpdateType.ImageUpdate;
  582. // remember imagetype that has just been downloaded
  583. foundImageTypes.Add(remoteImage.Type);
  584. }
  585. catch (HttpRequestException ex)
  586. {
  587. Logger.LogError(ex, "Could not save {ImageType} image: {Url}", Enum.GetName(remoteImage.Type), remoteImage.Url);
  588. }
  589. }
  590. if (foundImageTypes.Count > 0)
  591. {
  592. imageService.UpdateReplaceImages(options, foundImageTypes);
  593. }
  594. if (imageService.MergeImages(item, localItem.Images, options))
  595. {
  596. refreshResult.UpdateType |= ItemUpdateType.ImageUpdate;
  597. }
  598. MergeData(localItem, temp, [], false, true);
  599. refreshResult.UpdateType |= ItemUpdateType.MetadataImport;
  600. break;
  601. }
  602. Logger.LogDebug("{Provider} returned no metadata for {Item}", providerName, logName);
  603. }
  604. catch (OperationCanceledException)
  605. {
  606. throw;
  607. }
  608. catch (Exception ex)
  609. {
  610. Logger.LogError(ex, "Error in {Provider}", provider.Name);
  611. // If a local provider fails, consider that a failure
  612. refreshResult.ErrorMessage = ex.Message;
  613. }
  614. }
  615. }
  616. var isLocalLocked = temp.Item.IsLocked;
  617. if (!isLocalLocked && (options.ReplaceAllMetadata || options.MetadataRefreshMode > MetadataRefreshMode.ValidationOnly))
  618. {
  619. var remoteResult = await ExecuteRemoteProviders(temp, logName, false, id, providers.OfType<IRemoteMetadataProvider<TItemType, TIdType>>(), cancellationToken)
  620. .ConfigureAwait(false);
  621. refreshResult.UpdateType |= remoteResult.UpdateType;
  622. refreshResult.ErrorMessage = remoteResult.ErrorMessage;
  623. refreshResult.Failures += remoteResult.Failures;
  624. }
  625. if (providers.Any(i => i is not ICustomMetadataProvider))
  626. {
  627. if (refreshResult.UpdateType > ItemUpdateType.None)
  628. {
  629. if (!options.RemoveOldMetadata)
  630. {
  631. // Add existing metadata to provider result if it does not exist there
  632. MergeData(metadata, temp, [], false, false);
  633. }
  634. if (isLocalLocked)
  635. {
  636. MergeData(temp, metadata, item.LockedFields, true, true);
  637. }
  638. else
  639. {
  640. var shouldReplace = (options.MetadataRefreshMode > MetadataRefreshMode.ValidationOnly && options.ReplaceAllMetadata)
  641. // Case for Scan for new and updated files
  642. || (options.MetadataRefreshMode == MetadataRefreshMode.Default && !options.ReplaceAllMetadata);
  643. MergeData(temp, metadata, item.LockedFields, shouldReplace, true);
  644. }
  645. }
  646. }
  647. foreach (var provider in customProviders.Where(i => i is not IPreRefreshProvider))
  648. {
  649. await RunCustomProvider(provider, item, logName, options, refreshResult, cancellationToken).ConfigureAwait(false);
  650. }
  651. return refreshResult;
  652. }
  653. private async Task RunCustomProvider(ICustomMetadataProvider<TItemType> provider, TItemType item, string logName, MetadataRefreshOptions options, RefreshResult refreshResult, CancellationToken cancellationToken)
  654. {
  655. Logger.LogDebug("Running {Provider} for {Item}", provider.GetType().Name, logName);
  656. try
  657. {
  658. refreshResult.UpdateType |= await provider.FetchAsync(item, options, cancellationToken).ConfigureAwait(false);
  659. }
  660. catch (OperationCanceledException)
  661. {
  662. throw;
  663. }
  664. catch (Exception ex)
  665. {
  666. refreshResult.ErrorMessage = ex.Message;
  667. Logger.LogError(ex, "Error in {Provider}", provider.Name);
  668. }
  669. }
  670. protected virtual TItemType CreateNew()
  671. {
  672. return new TItemType();
  673. }
  674. private async Task<RefreshResult> ExecuteRemoteProviders(MetadataResult<TItemType> temp, string logName, bool replaceData, TIdType id, IEnumerable<IRemoteMetadataProvider<TItemType, TIdType>> providers, CancellationToken cancellationToken)
  675. {
  676. var refreshResult = new RefreshResult();
  677. if (id is not null)
  678. {
  679. MergeNewData(temp.Item, id);
  680. }
  681. foreach (var provider in providers)
  682. {
  683. var providerName = provider.GetType().Name;
  684. Logger.LogDebug("Running {Provider} for {Item}", providerName, logName);
  685. try
  686. {
  687. var result = await provider.GetMetadata(id, cancellationToken).ConfigureAwait(false);
  688. if (result.HasMetadata)
  689. {
  690. result.Provider = provider.Name;
  691. MergeData(result, temp, [], replaceData, false);
  692. MergeNewData(temp.Item, id);
  693. refreshResult.UpdateType |= ItemUpdateType.MetadataDownload;
  694. }
  695. else
  696. {
  697. Logger.LogDebug("{Provider} returned no metadata for {Item}", providerName, logName);
  698. }
  699. }
  700. catch (OperationCanceledException)
  701. {
  702. throw;
  703. }
  704. catch (Exception ex)
  705. {
  706. refreshResult.Failures++;
  707. refreshResult.ErrorMessage = ex.Message;
  708. Logger.LogError(ex, "Error in {Provider}", provider.Name);
  709. }
  710. }
  711. return refreshResult;
  712. }
  713. private void MergeNewData(TItemType source, TIdType lookupInfo)
  714. {
  715. // Copy new provider id's that may have been obtained
  716. foreach (var providerId in source.ProviderIds)
  717. {
  718. var key = providerId.Key;
  719. // Don't replace existing Id's.
  720. lookupInfo.ProviderIds.TryAdd(key, providerId.Value);
  721. }
  722. }
  723. private bool HasChanged(BaseItem item, IHasItemChangeMonitor changeMonitor, IDirectoryService directoryService)
  724. {
  725. try
  726. {
  727. var hasChanged = changeMonitor.HasChanged(item, directoryService);
  728. if (hasChanged)
  729. {
  730. Logger.LogDebug("{Monitor} reports change to {Item}", changeMonitor.GetType().Name, item.Path ?? item.Name);
  731. }
  732. return hasChanged;
  733. }
  734. catch (Exception ex)
  735. {
  736. Logger.LogError(ex, "Error in {Monitor}.HasChanged", changeMonitor.GetType().Name);
  737. return false;
  738. }
  739. }
  740. /// <summary>
  741. /// Merges metadata from source into target.
  742. /// </summary>
  743. /// <param name="source">The source for new metadata.</param>
  744. /// <param name="target">The target to insert new metadata into.</param>
  745. /// <param name="lockedFields">The fields that are locked and should not be updated.</param>
  746. /// <param name="replaceData"><c>true</c> if existing data should be replaced.</param>
  747. /// <param name="mergeMetadataSettings"><c>true</c> if the metadata settings in target should be updated to match source.</param>
  748. /// <exception cref="ArgumentException">Thrown if source or target are null.</exception>
  749. protected virtual void MergeData(
  750. MetadataResult<TItemType> source,
  751. MetadataResult<TItemType> target,
  752. MetadataField[] lockedFields,
  753. bool replaceData,
  754. bool mergeMetadataSettings)
  755. {
  756. MergeBaseItemData(source, target, lockedFields, replaceData, mergeMetadataSettings);
  757. }
  758. internal static void MergeBaseItemData(
  759. MetadataResult<TItemType> sourceResult,
  760. MetadataResult<TItemType> targetResult,
  761. MetadataField[] lockedFields,
  762. bool replaceData,
  763. bool mergeMetadataSettings)
  764. {
  765. var source = sourceResult.Item;
  766. var target = targetResult.Item;
  767. ArgumentNullException.ThrowIfNull(sourceResult);
  768. ArgumentNullException.ThrowIfNull(targetResult);
  769. if (!lockedFields.Contains(MetadataField.Name))
  770. {
  771. if (replaceData || string.IsNullOrEmpty(target.Name))
  772. {
  773. // Safeguard against incoming data having an empty name
  774. if (!string.IsNullOrWhiteSpace(source.Name))
  775. {
  776. target.Name = source.Name;
  777. }
  778. }
  779. }
  780. if (replaceData || string.IsNullOrEmpty(target.OriginalTitle))
  781. {
  782. target.OriginalTitle = source.OriginalTitle;
  783. }
  784. if (replaceData || !target.CommunityRating.HasValue)
  785. {
  786. target.CommunityRating = source.CommunityRating;
  787. }
  788. if (replaceData || !target.EndDate.HasValue)
  789. {
  790. target.EndDate = source.EndDate;
  791. }
  792. if (!lockedFields.Contains(MetadataField.Genres))
  793. {
  794. if (replaceData || target.Genres.Length == 0)
  795. {
  796. target.Genres = source.Genres;
  797. }
  798. }
  799. if (replaceData || !target.IndexNumber.HasValue)
  800. {
  801. target.IndexNumber = source.IndexNumber;
  802. }
  803. if (!lockedFields.Contains(MetadataField.OfficialRating))
  804. {
  805. if (replaceData || string.IsNullOrEmpty(target.OfficialRating))
  806. {
  807. target.OfficialRating = source.OfficialRating;
  808. }
  809. }
  810. if (replaceData || string.IsNullOrEmpty(target.CustomRating))
  811. {
  812. target.CustomRating = source.CustomRating;
  813. }
  814. if (replaceData || string.IsNullOrEmpty(target.Tagline))
  815. {
  816. target.Tagline = source.Tagline;
  817. }
  818. if (!lockedFields.Contains(MetadataField.Overview))
  819. {
  820. if (replaceData || string.IsNullOrEmpty(target.Overview))
  821. {
  822. target.Overview = source.Overview;
  823. }
  824. }
  825. if (replaceData || !target.ParentIndexNumber.HasValue)
  826. {
  827. target.ParentIndexNumber = source.ParentIndexNumber;
  828. }
  829. if (!lockedFields.Contains(MetadataField.Cast))
  830. {
  831. if (replaceData || targetResult.People is null || targetResult.People.Count == 0)
  832. {
  833. targetResult.People = sourceResult.People;
  834. }
  835. else if (sourceResult.People is not null && sourceResult.People.Count > 0)
  836. {
  837. MergePeople(sourceResult.People, targetResult.People);
  838. }
  839. }
  840. if (replaceData || !target.PremiereDate.HasValue)
  841. {
  842. target.PremiereDate = source.PremiereDate;
  843. }
  844. if (replaceData || !target.ProductionYear.HasValue)
  845. {
  846. target.ProductionYear = source.ProductionYear;
  847. }
  848. if (!lockedFields.Contains(MetadataField.Runtime))
  849. {
  850. if (replaceData || !target.RunTimeTicks.HasValue)
  851. {
  852. if (target is not Audio && target is not Video)
  853. {
  854. target.RunTimeTicks = source.RunTimeTicks;
  855. }
  856. }
  857. }
  858. if (!lockedFields.Contains(MetadataField.Studios))
  859. {
  860. if (replaceData || target.Studios.Length == 0)
  861. {
  862. target.Studios = source.Studios;
  863. }
  864. else
  865. {
  866. target.Studios = target.Studios.Concat(source.Studios).Distinct().ToArray();
  867. }
  868. }
  869. if (!lockedFields.Contains(MetadataField.Tags))
  870. {
  871. if (replaceData || target.Tags.Length == 0)
  872. {
  873. target.Tags = source.Tags;
  874. }
  875. else
  876. {
  877. target.Tags = target.Tags.Concat(source.Tags).Distinct().ToArray();
  878. }
  879. }
  880. if (!lockedFields.Contains(MetadataField.ProductionLocations))
  881. {
  882. if (replaceData || target.ProductionLocations.Length == 0)
  883. {
  884. target.ProductionLocations = source.ProductionLocations;
  885. }
  886. else
  887. {
  888. target.ProductionLocations = target.ProductionLocations.Concat(source.ProductionLocations).Distinct().ToArray();
  889. }
  890. }
  891. foreach (var id in source.ProviderIds)
  892. {
  893. var key = id.Key;
  894. // Don't replace existing Id's.
  895. if (replaceData)
  896. {
  897. target.ProviderIds[key] = id.Value;
  898. }
  899. else
  900. {
  901. target.ProviderIds.TryAdd(key, id.Value);
  902. }
  903. }
  904. if (replaceData || !target.CriticRating.HasValue)
  905. {
  906. target.CriticRating = source.CriticRating;
  907. }
  908. if (replaceData || target.RemoteTrailers.Count == 0)
  909. {
  910. target.RemoteTrailers = source.RemoteTrailers;
  911. }
  912. else
  913. {
  914. target.RemoteTrailers = target.RemoteTrailers.Concat(source.RemoteTrailers).DistinctBy(t => t.Url).ToArray();
  915. }
  916. MergeAlbumArtist(source, target, replaceData);
  917. MergeVideoInfo(source, target, replaceData);
  918. MergeDisplayOrder(source, target, replaceData);
  919. if (replaceData || string.IsNullOrEmpty(target.ForcedSortName))
  920. {
  921. var forcedSortName = source.ForcedSortName;
  922. if (!string.IsNullOrEmpty(forcedSortName))
  923. {
  924. target.ForcedSortName = forcedSortName;
  925. }
  926. }
  927. if (mergeMetadataSettings)
  928. {
  929. if (replaceData || !target.IsLocked)
  930. {
  931. target.IsLocked = target.IsLocked || source.IsLocked;
  932. }
  933. if (target.LockedFields.Length == 0)
  934. {
  935. target.LockedFields = source.LockedFields;
  936. }
  937. else
  938. {
  939. target.LockedFields = target.LockedFields.Concat(source.LockedFields).Distinct().ToArray();
  940. }
  941. if (source.DateCreated != default)
  942. {
  943. target.DateCreated = source.DateCreated;
  944. }
  945. if (replaceData || string.IsNullOrEmpty(target.PreferredMetadataCountryCode))
  946. {
  947. target.PreferredMetadataCountryCode = source.PreferredMetadataCountryCode;
  948. }
  949. if (replaceData || string.IsNullOrEmpty(target.PreferredMetadataLanguage))
  950. {
  951. target.PreferredMetadataLanguage = source.PreferredMetadataLanguage;
  952. }
  953. }
  954. }
  955. private static void MergePeople(IReadOnlyList<PersonInfo> source, IReadOnlyList<PersonInfo> target)
  956. {
  957. var sourceByName = source.ToLookup(p => p.Name.RemoveDiacritics(), StringComparer.OrdinalIgnoreCase);
  958. var targetByName = target.ToLookup(p => p.Name.RemoveDiacritics(), StringComparer.OrdinalIgnoreCase);
  959. foreach (var name in targetByName.Select(g => g.Key))
  960. {
  961. var targetPeople = targetByName[name].ToArray();
  962. var sourcePeople = sourceByName[name].ToArray();
  963. if (sourcePeople.Length == 0)
  964. {
  965. continue;
  966. }
  967. for (int i = 0; i < targetPeople.Length; i++)
  968. {
  969. var person = targetPeople[i];
  970. var personInSource = i < sourcePeople.Length ? sourcePeople[i] : sourcePeople[0];
  971. foreach (var providerId in personInSource.ProviderIds)
  972. {
  973. person.ProviderIds.TryAdd(providerId.Key, providerId.Value);
  974. }
  975. if (string.IsNullOrWhiteSpace(person.ImageUrl))
  976. {
  977. person.ImageUrl = personInSource.ImageUrl;
  978. }
  979. if (!string.IsNullOrWhiteSpace(personInSource.Role) && string.IsNullOrWhiteSpace(person.Role))
  980. {
  981. person.Role = personInSource.Role;
  982. }
  983. if (personInSource.SortOrder.HasValue && !person.SortOrder.HasValue)
  984. {
  985. person.SortOrder = personInSource.SortOrder;
  986. }
  987. }
  988. }
  989. }
  990. private static void MergeDisplayOrder(BaseItem source, BaseItem target, bool replaceData)
  991. {
  992. if (source is IHasDisplayOrder sourceHasDisplayOrder
  993. && target is IHasDisplayOrder targetHasDisplayOrder)
  994. {
  995. if (replaceData || string.IsNullOrEmpty(targetHasDisplayOrder.DisplayOrder))
  996. {
  997. var displayOrder = sourceHasDisplayOrder.DisplayOrder;
  998. if (!string.IsNullOrWhiteSpace(displayOrder))
  999. {
  1000. targetHasDisplayOrder.DisplayOrder = displayOrder;
  1001. }
  1002. }
  1003. }
  1004. }
  1005. private static void MergeAlbumArtist(BaseItem source, BaseItem target, bool replaceData)
  1006. {
  1007. if (source is IHasAlbumArtist sourceHasAlbumArtist
  1008. && target is IHasAlbumArtist targetHasAlbumArtist)
  1009. {
  1010. if (replaceData || targetHasAlbumArtist.AlbumArtists.Count == 0)
  1011. {
  1012. targetHasAlbumArtist.AlbumArtists = sourceHasAlbumArtist.AlbumArtists;
  1013. }
  1014. else if (sourceHasAlbumArtist.AlbumArtists.Count > 0)
  1015. {
  1016. targetHasAlbumArtist.AlbumArtists = targetHasAlbumArtist.AlbumArtists.Concat(sourceHasAlbumArtist.AlbumArtists).Distinct().ToArray();
  1017. }
  1018. }
  1019. }
  1020. private static void MergeVideoInfo(BaseItem source, BaseItem target, bool replaceData)
  1021. {
  1022. if (source is Video sourceCast && target is Video targetCast)
  1023. {
  1024. if (replaceData || !targetCast.Video3DFormat.HasValue)
  1025. {
  1026. targetCast.Video3DFormat = sourceCast.Video3DFormat;
  1027. }
  1028. }
  1029. }
  1030. }
  1031. }