DtoService.cs 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445
  1. #pragma warning disable CS1591
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Globalization;
  5. using System.IO;
  6. using System.Linq;
  7. using Jellyfin.Data.Entities;
  8. using Jellyfin.Data.Enums;
  9. using Jellyfin.Extensions;
  10. using MediaBrowser.Common;
  11. using MediaBrowser.Controller.Channels;
  12. using MediaBrowser.Controller.Chapters;
  13. using MediaBrowser.Controller.Drawing;
  14. using MediaBrowser.Controller.Dto;
  15. using MediaBrowser.Controller.Entities;
  16. using MediaBrowser.Controller.Entities.Audio;
  17. using MediaBrowser.Controller.Library;
  18. using MediaBrowser.Controller.LiveTv;
  19. using MediaBrowser.Controller.Persistence;
  20. using MediaBrowser.Controller.Playlists;
  21. using MediaBrowser.Controller.Providers;
  22. using MediaBrowser.Controller.Trickplay;
  23. using MediaBrowser.Model.Dto;
  24. using MediaBrowser.Model.Entities;
  25. using MediaBrowser.Model.Querying;
  26. using Microsoft.Extensions.Logging;
  27. using Book = MediaBrowser.Controller.Entities.Book;
  28. using Episode = MediaBrowser.Controller.Entities.TV.Episode;
  29. using Movie = MediaBrowser.Controller.Entities.Movies.Movie;
  30. using MusicAlbum = MediaBrowser.Controller.Entities.Audio.MusicAlbum;
  31. using Person = MediaBrowser.Controller.Entities.Person;
  32. using Photo = MediaBrowser.Controller.Entities.Photo;
  33. using Season = MediaBrowser.Controller.Entities.TV.Season;
  34. using Series = MediaBrowser.Controller.Entities.TV.Series;
  35. namespace Emby.Server.Implementations.Dto
  36. {
  37. public class DtoService : IDtoService
  38. {
  39. private readonly ILogger<DtoService> _logger;
  40. private readonly ILibraryManager _libraryManager;
  41. private readonly IUserDataManager _userDataRepository;
  42. private readonly IItemRepository _itemRepo;
  43. private readonly IImageProcessor _imageProcessor;
  44. private readonly IProviderManager _providerManager;
  45. private readonly IRecordingsManager _recordingsManager;
  46. private readonly IApplicationHost _appHost;
  47. private readonly IMediaSourceManager _mediaSourceManager;
  48. private readonly Lazy<ILiveTvManager> _livetvManagerFactory;
  49. private readonly ITrickplayManager _trickplayManager;
  50. private readonly IChapterRepository _chapterRepository;
  51. public DtoService(
  52. ILogger<DtoService> logger,
  53. ILibraryManager libraryManager,
  54. IUserDataManager userDataRepository,
  55. IItemRepository itemRepo,
  56. IImageProcessor imageProcessor,
  57. IProviderManager providerManager,
  58. IRecordingsManager recordingsManager,
  59. IApplicationHost appHost,
  60. IMediaSourceManager mediaSourceManager,
  61. Lazy<ILiveTvManager> livetvManagerFactory,
  62. ITrickplayManager trickplayManager,
  63. IChapterRepository chapterRepository)
  64. {
  65. _logger = logger;
  66. _libraryManager = libraryManager;
  67. _userDataRepository = userDataRepository;
  68. _itemRepo = itemRepo;
  69. _imageProcessor = imageProcessor;
  70. _providerManager = providerManager;
  71. _recordingsManager = recordingsManager;
  72. _appHost = appHost;
  73. _mediaSourceManager = mediaSourceManager;
  74. _livetvManagerFactory = livetvManagerFactory;
  75. _trickplayManager = trickplayManager;
  76. _chapterRepository = chapterRepository;
  77. }
  78. private ILiveTvManager LivetvManager => _livetvManagerFactory.Value;
  79. /// <inheritdoc />
  80. public IReadOnlyList<BaseItemDto> GetBaseItemDtos(IReadOnlyList<BaseItem> items, DtoOptions options, User? user = null, BaseItem? owner = null)
  81. {
  82. var accessibleItems = user is null ? items : items.Where(x => x.IsVisible(user)).ToList();
  83. var returnItems = new BaseItemDto[accessibleItems.Count];
  84. List<(BaseItem, BaseItemDto)>? programTuples = null;
  85. List<(BaseItemDto, LiveTvChannel)>? channelTuples = null;
  86. for (int index = 0; index < accessibleItems.Count; index++)
  87. {
  88. var item = accessibleItems[index];
  89. var dto = GetBaseItemDtoInternal(item, options, user, owner);
  90. if (item is LiveTvChannel tvChannel)
  91. {
  92. (channelTuples ??= new()).Add((dto, tvChannel));
  93. }
  94. else if (item is LiveTvProgram)
  95. {
  96. (programTuples ??= new()).Add((item, dto));
  97. }
  98. if (item is IItemByName byName)
  99. {
  100. if (options.ContainsField(ItemFields.ItemCounts))
  101. {
  102. var libraryItems = byName.GetTaggedItems(new InternalItemsQuery(user)
  103. {
  104. Recursive = true,
  105. DtoOptions = new DtoOptions(false)
  106. {
  107. EnableImages = false
  108. }
  109. });
  110. SetItemByNameInfo(item, dto, libraryItems);
  111. }
  112. }
  113. returnItems[index] = dto;
  114. }
  115. if (programTuples is not null)
  116. {
  117. LivetvManager.AddInfoToProgramDto(programTuples, options.Fields, user).GetAwaiter().GetResult();
  118. }
  119. if (channelTuples is not null)
  120. {
  121. LivetvManager.AddChannelInfo(channelTuples, options, user);
  122. }
  123. return returnItems;
  124. }
  125. public BaseItemDto GetBaseItemDto(BaseItem item, DtoOptions options, User? user = null, BaseItem? owner = null)
  126. {
  127. var dto = GetBaseItemDtoInternal(item, options, user, owner);
  128. if (item is LiveTvChannel tvChannel)
  129. {
  130. LivetvManager.AddChannelInfo(new[] { (dto, tvChannel) }, options, user);
  131. }
  132. else if (item is LiveTvProgram)
  133. {
  134. LivetvManager.AddInfoToProgramDto(new[] { (item, dto) }, options.Fields, user).GetAwaiter().GetResult();
  135. }
  136. if (item is IItemByName itemByName
  137. && options.ContainsField(ItemFields.ItemCounts))
  138. {
  139. SetItemByNameInfo(
  140. item,
  141. dto,
  142. GetTaggedItems(
  143. itemByName,
  144. user,
  145. new DtoOptions(false)
  146. {
  147. EnableImages = false
  148. }));
  149. }
  150. return dto;
  151. }
  152. private static IReadOnlyList<BaseItem> GetTaggedItems(IItemByName byName, User? user, DtoOptions options)
  153. {
  154. return byName.GetTaggedItems(
  155. new InternalItemsQuery(user)
  156. {
  157. Recursive = true,
  158. DtoOptions = options
  159. });
  160. }
  161. private BaseItemDto GetBaseItemDtoInternal(BaseItem item, DtoOptions options, User? user = null, BaseItem? owner = null)
  162. {
  163. var dto = new BaseItemDto
  164. {
  165. ServerId = _appHost.SystemId
  166. };
  167. if (item.SourceType == SourceType.Channel)
  168. {
  169. dto.SourceType = item.SourceType.ToString();
  170. }
  171. if (options.ContainsField(ItemFields.People))
  172. {
  173. AttachPeople(dto, item, user);
  174. }
  175. if (options.ContainsField(ItemFields.PrimaryImageAspectRatio))
  176. {
  177. try
  178. {
  179. AttachPrimaryImageAspectRatio(dto, item);
  180. }
  181. catch (Exception ex)
  182. {
  183. // Have to use a catch-all unfortunately because some .net image methods throw plain Exceptions
  184. _logger.LogError(ex, "Error generating PrimaryImageAspectRatio for {ItemName}", item.Name);
  185. }
  186. }
  187. if (options.ContainsField(ItemFields.DisplayPreferencesId))
  188. {
  189. dto.DisplayPreferencesId = item.DisplayPreferencesId.ToString("N", CultureInfo.InvariantCulture);
  190. }
  191. if (user is not null)
  192. {
  193. AttachUserSpecificInfo(dto, item, user, options);
  194. }
  195. if (item is IHasMediaSources
  196. && options.ContainsField(ItemFields.MediaSources))
  197. {
  198. dto.MediaSources = _mediaSourceManager.GetStaticMediaSources(item, true, user).ToArray();
  199. NormalizeMediaSourceContainers(dto);
  200. }
  201. if (options.ContainsField(ItemFields.Studios))
  202. {
  203. AttachStudios(dto, item);
  204. }
  205. AttachBasicFields(dto, item, owner, options);
  206. if (options.ContainsField(ItemFields.CanDelete))
  207. {
  208. dto.CanDelete = user is null
  209. ? item.CanDelete()
  210. : item.CanDelete(user);
  211. }
  212. if (options.ContainsField(ItemFields.CanDownload))
  213. {
  214. dto.CanDownload = user is null
  215. ? item.CanDownload()
  216. : item.CanDownload(user);
  217. }
  218. if (options.ContainsField(ItemFields.Etag))
  219. {
  220. dto.Etag = item.GetEtag(user);
  221. }
  222. var activeRecording = _recordingsManager.GetActiveRecordingInfo(item.Path);
  223. if (activeRecording is not null)
  224. {
  225. dto.Type = BaseItemKind.Recording;
  226. dto.CanDownload = false;
  227. dto.RunTimeTicks = null;
  228. if (!string.IsNullOrEmpty(dto.SeriesName))
  229. {
  230. dto.EpisodeTitle = dto.Name;
  231. dto.Name = dto.SeriesName;
  232. }
  233. LivetvManager.AddInfoToRecordingDto(item, dto, activeRecording, user);
  234. }
  235. if (item is Audio audio)
  236. {
  237. dto.HasLyrics = audio.GetMediaStreams().Any(s => s.Type == MediaStreamType.Lyric);
  238. }
  239. return dto;
  240. }
  241. private static void NormalizeMediaSourceContainers(BaseItemDto dto)
  242. {
  243. foreach (var mediaSource in dto.MediaSources)
  244. {
  245. var container = mediaSource.Container;
  246. if (string.IsNullOrEmpty(container))
  247. {
  248. continue;
  249. }
  250. var containers = container.Split(',');
  251. if (containers.Length < 2)
  252. {
  253. continue;
  254. }
  255. var path = mediaSource.Path;
  256. string? fileExtensionContainer = null;
  257. if (!string.IsNullOrEmpty(path))
  258. {
  259. path = Path.GetExtension(path);
  260. if (!string.IsNullOrEmpty(path))
  261. {
  262. path = Path.GetExtension(path);
  263. if (!string.IsNullOrEmpty(path))
  264. {
  265. path = path.TrimStart('.');
  266. }
  267. if (!string.IsNullOrEmpty(path) && containers.Contains(path, StringComparison.OrdinalIgnoreCase))
  268. {
  269. fileExtensionContainer = path;
  270. }
  271. }
  272. }
  273. mediaSource.Container = fileExtensionContainer ?? containers[0];
  274. }
  275. }
  276. /// <inheritdoc />
  277. public BaseItemDto GetItemByNameDto(BaseItem item, DtoOptions options, List<BaseItem>? taggedItems, User? user = null)
  278. {
  279. var dto = GetBaseItemDtoInternal(item, options, user);
  280. if (taggedItems is not null && options.ContainsField(ItemFields.ItemCounts))
  281. {
  282. SetItemByNameInfo(item, dto, taggedItems);
  283. }
  284. return dto;
  285. }
  286. private static void SetItemByNameInfo(BaseItem item, BaseItemDto dto, IReadOnlyList<BaseItem> taggedItems)
  287. {
  288. if (item is MusicArtist)
  289. {
  290. dto.AlbumCount = taggedItems.Count(i => i is MusicAlbum);
  291. dto.MusicVideoCount = taggedItems.Count(i => i is MusicVideo);
  292. dto.SongCount = taggedItems.Count(i => i is Audio);
  293. }
  294. else if (item is MusicGenre)
  295. {
  296. dto.ArtistCount = taggedItems.Count(i => i is MusicArtist);
  297. dto.AlbumCount = taggedItems.Count(i => i is MusicAlbum);
  298. dto.MusicVideoCount = taggedItems.Count(i => i is MusicVideo);
  299. dto.SongCount = taggedItems.Count(i => i is Audio);
  300. }
  301. else
  302. {
  303. // This populates them all and covers Genre, Person, Studio, Year
  304. dto.ArtistCount = taggedItems.Count(i => i is MusicArtist);
  305. dto.AlbumCount = taggedItems.Count(i => i is MusicAlbum);
  306. dto.EpisodeCount = taggedItems.Count(i => i is Episode);
  307. dto.MovieCount = taggedItems.Count(i => i is Movie);
  308. dto.TrailerCount = taggedItems.Count(i => i is Trailer);
  309. dto.MusicVideoCount = taggedItems.Count(i => i is MusicVideo);
  310. dto.SeriesCount = taggedItems.Count(i => i is Series);
  311. dto.ProgramCount = taggedItems.Count(i => i is LiveTvProgram);
  312. dto.SongCount = taggedItems.Count(i => i is Audio);
  313. }
  314. dto.ChildCount = taggedItems.Count;
  315. }
  316. /// <summary>
  317. /// Attaches the user specific info.
  318. /// </summary>
  319. private void AttachUserSpecificInfo(BaseItemDto dto, BaseItem item, User user, DtoOptions options)
  320. {
  321. if (item.IsFolder)
  322. {
  323. var folder = (Folder)item;
  324. if (options.EnableUserData)
  325. {
  326. dto.UserData = _userDataRepository.GetUserDataDto(item, dto, user, options);
  327. }
  328. if (!dto.ChildCount.HasValue && item.SourceType == SourceType.Library)
  329. {
  330. // For these types we can try to optimize and assume these values will be equal
  331. if (item is MusicAlbum || item is Season || item is Playlist)
  332. {
  333. dto.ChildCount = dto.RecursiveItemCount;
  334. var folderChildCount = folder.LinkedChildren.Length;
  335. // The default is an empty array, so we can't reliably use the count when it's empty
  336. if (folderChildCount > 0)
  337. {
  338. dto.ChildCount ??= folderChildCount;
  339. }
  340. }
  341. if (options.ContainsField(ItemFields.ChildCount))
  342. {
  343. dto.ChildCount ??= GetChildCount(folder, user);
  344. }
  345. }
  346. if (options.ContainsField(ItemFields.CumulativeRunTimeTicks))
  347. {
  348. dto.CumulativeRunTimeTicks = item.RunTimeTicks;
  349. }
  350. if (options.ContainsField(ItemFields.DateLastMediaAdded))
  351. {
  352. dto.DateLastMediaAdded = folder.DateLastMediaAdded;
  353. }
  354. }
  355. else
  356. {
  357. if (options.EnableUserData)
  358. {
  359. dto.UserData = _userDataRepository.GetUserDataDto(item, user);
  360. }
  361. }
  362. if (options.ContainsField(ItemFields.PlayAccess))
  363. {
  364. dto.PlayAccess = item.GetPlayAccess(user);
  365. }
  366. }
  367. private static int GetChildCount(Folder folder, User user)
  368. {
  369. // Right now this is too slow to calculate for top level folders on a per-user basis
  370. // Just return something so that apps that are expecting a value won't think the folders are empty
  371. if (folder is ICollectionFolder || folder is UserView)
  372. {
  373. return Random.Shared.Next(1, 10);
  374. }
  375. return folder.GetChildCount(user);
  376. }
  377. private static void SetBookProperties(BaseItemDto dto, Book item)
  378. {
  379. dto.SeriesName = item.SeriesName;
  380. }
  381. private static void SetPhotoProperties(BaseItemDto dto, Photo item)
  382. {
  383. dto.CameraMake = item.CameraMake;
  384. dto.CameraModel = item.CameraModel;
  385. dto.Software = item.Software;
  386. dto.ExposureTime = item.ExposureTime;
  387. dto.FocalLength = item.FocalLength;
  388. dto.ImageOrientation = item.Orientation;
  389. dto.Aperture = item.Aperture;
  390. dto.ShutterSpeed = item.ShutterSpeed;
  391. dto.Latitude = item.Latitude;
  392. dto.Longitude = item.Longitude;
  393. dto.Altitude = item.Altitude;
  394. dto.IsoSpeedRating = item.IsoSpeedRating;
  395. var album = item.AlbumEntity;
  396. if (album is not null)
  397. {
  398. dto.Album = album.Name;
  399. dto.AlbumId = album.Id;
  400. }
  401. }
  402. private void SetMusicVideoProperties(BaseItemDto dto, MusicVideo item)
  403. {
  404. if (!string.IsNullOrEmpty(item.Album))
  405. {
  406. var parentAlbumIds = _libraryManager.GetItemIds(new InternalItemsQuery
  407. {
  408. IncludeItemTypes = new[] { BaseItemKind.MusicAlbum },
  409. Name = item.Album,
  410. Limit = 1
  411. });
  412. if (parentAlbumIds.Count > 0)
  413. {
  414. dto.AlbumId = parentAlbumIds[0];
  415. }
  416. }
  417. dto.Album = item.Album;
  418. }
  419. private string[] GetImageTags(BaseItem item, List<ItemImageInfo> images)
  420. {
  421. return images
  422. .Select(p => GetImageCacheTag(item, p))
  423. .Where(i => i is not null)
  424. .ToArray()!; // null values got filtered out
  425. }
  426. private string? GetImageCacheTag(BaseItem item, ItemImageInfo image)
  427. {
  428. try
  429. {
  430. return _imageProcessor.GetImageCacheTag(item, image);
  431. }
  432. catch (Exception ex)
  433. {
  434. _logger.LogError(ex, "Error getting {ImageType} image info for {Path}", image.Type, image.Path);
  435. return null;
  436. }
  437. }
  438. /// <summary>
  439. /// Attaches People DTO's to a DTOBaseItem.
  440. /// </summary>
  441. /// <param name="dto">The dto.</param>
  442. /// <param name="item">The item.</param>
  443. /// <param name="user">The requesting user.</param>
  444. private void AttachPeople(BaseItemDto dto, BaseItem item, User? user = null)
  445. {
  446. // Ordering by person type to ensure actors and artists are at the front.
  447. // This is taking advantage of the fact that they both begin with A
  448. // This should be improved in the future
  449. var people = _libraryManager.GetPeople(item).OrderBy(i => i.SortOrder ?? int.MaxValue)
  450. .ThenBy(i =>
  451. {
  452. if (i.IsType(PersonKind.Actor))
  453. {
  454. return 0;
  455. }
  456. if (i.IsType(PersonKind.GuestStar))
  457. {
  458. return 1;
  459. }
  460. if (i.IsType(PersonKind.Director))
  461. {
  462. return 2;
  463. }
  464. if (i.IsType(PersonKind.Writer))
  465. {
  466. return 3;
  467. }
  468. if (i.IsType(PersonKind.Producer))
  469. {
  470. return 4;
  471. }
  472. if (i.IsType(PersonKind.Composer))
  473. {
  474. return 4;
  475. }
  476. return 10;
  477. })
  478. .ToList();
  479. var list = new List<BaseItemPerson>();
  480. Dictionary<string, Person> dictionary = people.Select(p => p.Name)
  481. .Distinct(StringComparer.OrdinalIgnoreCase).Select(c =>
  482. {
  483. try
  484. {
  485. return _libraryManager.GetPerson(c);
  486. }
  487. catch (Exception ex)
  488. {
  489. _logger.LogError(ex, "Error getting person {Name}", c);
  490. return null;
  491. }
  492. }).Where(i => i is not null)
  493. .Where(i => user is null || i!.IsVisible(user))
  494. .DistinctBy(x => x!.Name, StringComparer.OrdinalIgnoreCase)
  495. .ToDictionary(i => i!.Name, StringComparer.OrdinalIgnoreCase)!; // null values got filtered out
  496. for (var i = 0; i < people.Count; i++)
  497. {
  498. var person = people[i];
  499. var baseItemPerson = new BaseItemPerson
  500. {
  501. Name = person.Name,
  502. Role = person.Role,
  503. Type = person.Type
  504. };
  505. if (dictionary.TryGetValue(person.Name, out Person? entity))
  506. {
  507. baseItemPerson.PrimaryImageTag = GetTagAndFillBlurhash(dto, entity, ImageType.Primary);
  508. baseItemPerson.Id = entity.Id;
  509. if (dto.ImageBlurHashes is not null)
  510. {
  511. // Only add BlurHash for the person's image.
  512. baseItemPerson.ImageBlurHashes = new Dictionary<ImageType, Dictionary<string, string>>();
  513. foreach (var (imageType, blurHash) in dto.ImageBlurHashes)
  514. {
  515. if (blurHash is not null)
  516. {
  517. baseItemPerson.ImageBlurHashes[imageType] = new Dictionary<string, string>();
  518. foreach (var (imageId, blurHashValue) in blurHash)
  519. {
  520. if (string.Equals(baseItemPerson.PrimaryImageTag, imageId, StringComparison.OrdinalIgnoreCase))
  521. {
  522. baseItemPerson.ImageBlurHashes[imageType][imageId] = blurHashValue;
  523. }
  524. }
  525. }
  526. }
  527. }
  528. list.Add(baseItemPerson);
  529. }
  530. }
  531. dto.People = list.ToArray();
  532. }
  533. /// <summary>
  534. /// Attaches the studios.
  535. /// </summary>
  536. /// <param name="dto">The dto.</param>
  537. /// <param name="item">The item.</param>
  538. private void AttachStudios(BaseItemDto dto, BaseItem item)
  539. {
  540. dto.Studios = item.Studios
  541. .Where(i => !string.IsNullOrEmpty(i))
  542. .Select(i => new NameGuidPair
  543. {
  544. Name = i,
  545. Id = _libraryManager.GetStudioId(i)
  546. })
  547. .ToArray();
  548. }
  549. private void AttachGenreItems(BaseItemDto dto, BaseItem item)
  550. {
  551. dto.GenreItems = item.Genres
  552. .Where(i => !string.IsNullOrEmpty(i))
  553. .Select(i => new NameGuidPair
  554. {
  555. Name = i,
  556. Id = GetGenreId(i, item)
  557. })
  558. .ToArray();
  559. }
  560. private Guid GetGenreId(string name, BaseItem owner)
  561. {
  562. if (owner is IHasMusicGenres)
  563. {
  564. return _libraryManager.GetMusicGenreId(name);
  565. }
  566. return _libraryManager.GetGenreId(name);
  567. }
  568. private string? GetTagAndFillBlurhash(BaseItemDto dto, BaseItem item, ImageType imageType, int imageIndex = 0)
  569. {
  570. var image = item.GetImageInfo(imageType, imageIndex);
  571. if (image is not null)
  572. {
  573. return GetTagAndFillBlurhash(dto, item, image);
  574. }
  575. return null;
  576. }
  577. private string? GetTagAndFillBlurhash(BaseItemDto dto, BaseItem item, ItemImageInfo image)
  578. {
  579. var tag = GetImageCacheTag(item, image);
  580. if (tag is null)
  581. {
  582. return null;
  583. }
  584. if (!string.IsNullOrEmpty(image.BlurHash))
  585. {
  586. dto.ImageBlurHashes ??= new Dictionary<ImageType, Dictionary<string, string>>();
  587. if (!dto.ImageBlurHashes.TryGetValue(image.Type, out var value))
  588. {
  589. value = new Dictionary<string, string>();
  590. dto.ImageBlurHashes[image.Type] = value;
  591. }
  592. value[tag] = image.BlurHash;
  593. }
  594. return tag;
  595. }
  596. private string[] GetTagsAndFillBlurhashes(BaseItemDto dto, BaseItem item, ImageType imageType, int limit)
  597. {
  598. return GetTagsAndFillBlurhashes(dto, item, imageType, item.GetImages(imageType).Take(limit).ToList());
  599. }
  600. private string[] GetTagsAndFillBlurhashes(BaseItemDto dto, BaseItem item, ImageType imageType, List<ItemImageInfo> images)
  601. {
  602. var tags = GetImageTags(item, images);
  603. var hashes = new Dictionary<string, string>();
  604. for (int i = 0; i < images.Count; i++)
  605. {
  606. var img = images[i];
  607. if (!string.IsNullOrEmpty(img.BlurHash))
  608. {
  609. var tag = tags[i];
  610. hashes[tag] = img.BlurHash;
  611. }
  612. }
  613. if (hashes.Count > 0)
  614. {
  615. dto.ImageBlurHashes ??= new Dictionary<ImageType, Dictionary<string, string>>();
  616. dto.ImageBlurHashes[imageType] = hashes;
  617. }
  618. return tags;
  619. }
  620. /// <summary>
  621. /// Sets simple property values on a DTOBaseItem.
  622. /// </summary>
  623. /// <param name="dto">The dto.</param>
  624. /// <param name="item">The item.</param>
  625. /// <param name="owner">The owner.</param>
  626. /// <param name="options">The options.</param>
  627. private void AttachBasicFields(BaseItemDto dto, BaseItem item, BaseItem? owner, DtoOptions options)
  628. {
  629. if (options.ContainsField(ItemFields.DateCreated))
  630. {
  631. dto.DateCreated = item.DateCreated;
  632. }
  633. if (options.ContainsField(ItemFields.Settings))
  634. {
  635. dto.LockedFields = item.LockedFields;
  636. dto.LockData = item.IsLocked;
  637. dto.ForcedSortName = item.ForcedSortName;
  638. }
  639. dto.Container = item.Container;
  640. dto.EndDate = item.EndDate;
  641. if (options.ContainsField(ItemFields.ExternalUrls))
  642. {
  643. dto.ExternalUrls = _providerManager.GetExternalUrls(item).ToArray();
  644. }
  645. if (options.ContainsField(ItemFields.Tags))
  646. {
  647. dto.Tags = item.Tags;
  648. }
  649. if (item is IHasAspectRatio hasAspectRatio)
  650. {
  651. dto.AspectRatio = hasAspectRatio.AspectRatio;
  652. }
  653. dto.ImageBlurHashes = new Dictionary<ImageType, Dictionary<string, string>>();
  654. var backdropLimit = options.GetImageLimit(ImageType.Backdrop);
  655. if (backdropLimit > 0)
  656. {
  657. dto.BackdropImageTags = GetTagsAndFillBlurhashes(dto, item, ImageType.Backdrop, backdropLimit);
  658. }
  659. if (options.ContainsField(ItemFields.Genres))
  660. {
  661. dto.Genres = item.Genres;
  662. AttachGenreItems(dto, item);
  663. }
  664. if (options.EnableImages)
  665. {
  666. dto.ImageTags = new Dictionary<ImageType, string>();
  667. // Prevent implicitly captured closure
  668. var currentItem = item;
  669. foreach (var image in currentItem.ImageInfos.Where(i => !currentItem.AllowsMultipleImages(i.Type)))
  670. {
  671. if (options.GetImageLimit(image.Type) > 0)
  672. {
  673. var tag = GetTagAndFillBlurhash(dto, item, image);
  674. if (tag is not null)
  675. {
  676. dto.ImageTags[image.Type] = tag;
  677. }
  678. }
  679. }
  680. }
  681. dto.Id = item.Id;
  682. dto.IndexNumber = item.IndexNumber;
  683. dto.ParentIndexNumber = item.ParentIndexNumber;
  684. if (item.IsFolder)
  685. {
  686. dto.IsFolder = true;
  687. }
  688. else if (item is IHasMediaSources)
  689. {
  690. dto.IsFolder = false;
  691. }
  692. dto.MediaType = item.MediaType;
  693. if (item is not LiveTvProgram)
  694. {
  695. dto.LocationType = item.LocationType;
  696. }
  697. dto.Audio = item.Audio;
  698. if (options.ContainsField(ItemFields.Settings))
  699. {
  700. dto.PreferredMetadataCountryCode = item.PreferredMetadataCountryCode;
  701. dto.PreferredMetadataLanguage = item.PreferredMetadataLanguage;
  702. }
  703. dto.CriticRating = item.CriticRating;
  704. if (item is IHasDisplayOrder hasDisplayOrder)
  705. {
  706. dto.DisplayOrder = hasDisplayOrder.DisplayOrder;
  707. }
  708. if (item is IHasCollectionType hasCollectionType)
  709. {
  710. dto.CollectionType = hasCollectionType.CollectionType;
  711. }
  712. if (options.ContainsField(ItemFields.RemoteTrailers))
  713. {
  714. dto.RemoteTrailers = item.RemoteTrailers;
  715. }
  716. dto.Name = item.Name;
  717. dto.OfficialRating = item.OfficialRating;
  718. if (options.ContainsField(ItemFields.Overview))
  719. {
  720. dto.Overview = item.Overview;
  721. }
  722. if (options.ContainsField(ItemFields.OriginalTitle))
  723. {
  724. dto.OriginalTitle = item.OriginalTitle;
  725. }
  726. if (options.ContainsField(ItemFields.ParentId))
  727. {
  728. dto.ParentId = item.DisplayParentId;
  729. }
  730. AddInheritedImages(dto, item, options, owner);
  731. if (options.ContainsField(ItemFields.Path))
  732. {
  733. dto.Path = GetMappedPath(item, owner);
  734. }
  735. if (options.ContainsField(ItemFields.EnableMediaSourceDisplay))
  736. {
  737. dto.EnableMediaSourceDisplay = item.EnableMediaSourceDisplay;
  738. }
  739. dto.PremiereDate = item.PremiereDate;
  740. dto.ProductionYear = item.ProductionYear;
  741. if (options.ContainsField(ItemFields.ProviderIds))
  742. {
  743. dto.ProviderIds = item.ProviderIds;
  744. }
  745. dto.RunTimeTicks = item.RunTimeTicks;
  746. if (options.ContainsField(ItemFields.SortName))
  747. {
  748. dto.SortName = item.SortName;
  749. }
  750. if (options.ContainsField(ItemFields.CustomRating))
  751. {
  752. dto.CustomRating = item.CustomRating;
  753. }
  754. if (options.ContainsField(ItemFields.Taglines))
  755. {
  756. if (!string.IsNullOrEmpty(item.Tagline))
  757. {
  758. dto.Taglines = new string[] { item.Tagline };
  759. }
  760. dto.Taglines ??= Array.Empty<string>();
  761. }
  762. dto.Type = item.GetBaseItemKind();
  763. if ((item.CommunityRating ?? 0) > 0)
  764. {
  765. dto.CommunityRating = item.CommunityRating;
  766. }
  767. if (item is ISupportsPlaceHolders supportsPlaceHolders && supportsPlaceHolders.IsPlaceHolder)
  768. {
  769. dto.IsPlaceHolder = supportsPlaceHolders.IsPlaceHolder;
  770. }
  771. if (item.LUFS.HasValue)
  772. {
  773. // -18 LUFS reference, same as ReplayGain 2.0, compatible with ReplayGain 1.0
  774. dto.NormalizationGain = -18f - item.LUFS;
  775. }
  776. else if (item.NormalizationGain.HasValue)
  777. {
  778. dto.NormalizationGain = item.NormalizationGain;
  779. }
  780. // Add audio info
  781. if (item is Audio audio)
  782. {
  783. dto.Album = audio.Album;
  784. dto.ExtraType = audio.ExtraType;
  785. var albumParent = audio.AlbumEntity;
  786. if (albumParent is not null)
  787. {
  788. dto.AlbumId = albumParent.Id;
  789. dto.AlbumPrimaryImageTag = GetTagAndFillBlurhash(dto, albumParent, ImageType.Primary);
  790. }
  791. // if (options.ContainsField(ItemFields.MediaSourceCount))
  792. // {
  793. // Songs always have one
  794. // }
  795. }
  796. if (item is IHasArtist hasArtist)
  797. {
  798. dto.Artists = hasArtist.Artists;
  799. // var artistItems = _libraryManager.GetArtists(new InternalItemsQuery
  800. // {
  801. // EnableTotalRecordCount = false,
  802. // ItemIds = new[] { item.Id.ToString("N", CultureInfo.InvariantCulture) }
  803. // });
  804. // dto.ArtistItems = artistItems.Items
  805. // .Select(i =>
  806. // {
  807. // var artist = i.Item1;
  808. // return new NameIdPair
  809. // {
  810. // Name = artist.Name,
  811. // Id = artist.Id.ToString("N", CultureInfo.InvariantCulture)
  812. // };
  813. // })
  814. // .ToList();
  815. // Include artists that are not in the database yet, e.g., just added via metadata editor
  816. // var foundArtists = artistItems.Items.Select(i => i.Item1.Name).ToList();
  817. dto.ArtistItems = hasArtist.Artists
  818. // .Except(foundArtists, new DistinctNameComparer())
  819. .Select(i =>
  820. {
  821. // This should not be necessary but we're seeing some cases of it
  822. if (string.IsNullOrEmpty(i))
  823. {
  824. return null;
  825. }
  826. var artist = _libraryManager.GetArtist(i, new DtoOptions(false)
  827. {
  828. EnableImages = false
  829. });
  830. if (artist is not null)
  831. {
  832. return new NameGuidPair
  833. {
  834. Name = artist.Name,
  835. Id = artist.Id
  836. };
  837. }
  838. return null;
  839. }).Where(i => i is not null).ToArray();
  840. }
  841. if (item is IHasAlbumArtist hasAlbumArtist)
  842. {
  843. dto.AlbumArtist = hasAlbumArtist.AlbumArtists.FirstOrDefault();
  844. // var artistItems = _libraryManager.GetAlbumArtists(new InternalItemsQuery
  845. // {
  846. // EnableTotalRecordCount = false,
  847. // ItemIds = new[] { item.Id.ToString("N", CultureInfo.InvariantCulture) }
  848. // });
  849. // dto.AlbumArtists = artistItems.Items
  850. // .Select(i =>
  851. // {
  852. // var artist = i.Item1;
  853. // return new NameIdPair
  854. // {
  855. // Name = artist.Name,
  856. // Id = artist.Id.ToString("N", CultureInfo.InvariantCulture)
  857. // };
  858. // })
  859. // .ToList();
  860. dto.AlbumArtists = hasAlbumArtist.AlbumArtists
  861. // .Except(foundArtists, new DistinctNameComparer())
  862. .Select(i =>
  863. {
  864. // This should not be necessary but we're seeing some cases of it
  865. if (string.IsNullOrEmpty(i))
  866. {
  867. return null;
  868. }
  869. var artist = _libraryManager.GetArtist(i, new DtoOptions(false)
  870. {
  871. EnableImages = false
  872. });
  873. if (artist is not null)
  874. {
  875. return new NameGuidPair
  876. {
  877. Name = artist.Name,
  878. Id = artist.Id
  879. };
  880. }
  881. return null;
  882. }).Where(i => i is not null).ToArray();
  883. }
  884. // Add video info
  885. if (item is Video video)
  886. {
  887. dto.VideoType = video.VideoType;
  888. dto.Video3DFormat = video.Video3DFormat;
  889. dto.IsoType = video.IsoType;
  890. if (video.HasSubtitles)
  891. {
  892. dto.HasSubtitles = video.HasSubtitles;
  893. }
  894. if (video.AdditionalParts.Length != 0)
  895. {
  896. dto.PartCount = video.AdditionalParts.Length + 1;
  897. }
  898. if (options.ContainsField(ItemFields.MediaSourceCount))
  899. {
  900. var mediaSourceCount = video.MediaSourceCount;
  901. if (mediaSourceCount != 1)
  902. {
  903. dto.MediaSourceCount = mediaSourceCount;
  904. }
  905. }
  906. if (options.ContainsField(ItemFields.Chapters))
  907. {
  908. dto.Chapters = _chapterRepository.GetChapters(item.Id).ToList();
  909. }
  910. if (options.ContainsField(ItemFields.Trickplay))
  911. {
  912. dto.Trickplay = _trickplayManager.GetTrickplayManifest(item).GetAwaiter().GetResult();
  913. }
  914. dto.ExtraType = video.ExtraType;
  915. }
  916. if (options.ContainsField(ItemFields.MediaStreams))
  917. {
  918. // Add VideoInfo
  919. if (item is IHasMediaSources)
  920. {
  921. MediaStream[] mediaStreams;
  922. if (dto.MediaSources is not null && dto.MediaSources.Length > 0)
  923. {
  924. if (item.SourceType == SourceType.Channel)
  925. {
  926. mediaStreams = dto.MediaSources[0].MediaStreams.ToArray();
  927. }
  928. else
  929. {
  930. string id = item.Id.ToString("N", CultureInfo.InvariantCulture);
  931. mediaStreams = dto.MediaSources.Where(i => string.Equals(i.Id, id, StringComparison.OrdinalIgnoreCase))
  932. .SelectMany(i => i.MediaStreams)
  933. .ToArray();
  934. }
  935. }
  936. else
  937. {
  938. mediaStreams = _mediaSourceManager.GetStaticMediaSources(item, true)[0].MediaStreams.ToArray();
  939. }
  940. dto.MediaStreams = mediaStreams;
  941. }
  942. }
  943. BaseItem[]? allExtras = null;
  944. if (options.ContainsField(ItemFields.SpecialFeatureCount))
  945. {
  946. allExtras = item.GetExtras().ToArray();
  947. dto.SpecialFeatureCount = allExtras.Count(i => i.ExtraType.HasValue && BaseItem.DisplayExtraTypes.Contains(i.ExtraType.Value));
  948. }
  949. if (options.ContainsField(ItemFields.LocalTrailerCount))
  950. {
  951. if (item is IHasTrailers hasTrailers)
  952. {
  953. dto.LocalTrailerCount = hasTrailers.LocalTrailers.Count;
  954. }
  955. else
  956. {
  957. dto.LocalTrailerCount = (allExtras ?? item.GetExtras()).Count(i => i.ExtraType == ExtraType.Trailer);
  958. }
  959. }
  960. // Add EpisodeInfo
  961. if (item is Episode episode)
  962. {
  963. dto.IndexNumberEnd = episode.IndexNumberEnd;
  964. dto.SeriesName = episode.SeriesName;
  965. if (options.ContainsField(ItemFields.SpecialEpisodeNumbers))
  966. {
  967. dto.AirsAfterSeasonNumber = episode.AirsAfterSeasonNumber;
  968. dto.AirsBeforeEpisodeNumber = episode.AirsBeforeEpisodeNumber;
  969. dto.AirsBeforeSeasonNumber = episode.AirsBeforeSeasonNumber;
  970. }
  971. dto.SeasonName = episode.SeasonName;
  972. dto.SeasonId = episode.SeasonId;
  973. dto.SeriesId = episode.SeriesId;
  974. Series? episodeSeries = null;
  975. // this block will add the series poster for episodes without a poster
  976. // TODO maybe remove the if statement entirely
  977. // if (options.ContainsField(ItemFields.SeriesPrimaryImage))
  978. {
  979. episodeSeries ??= episode.Series;
  980. if (episodeSeries is not null)
  981. {
  982. dto.SeriesPrimaryImageTag = GetTagAndFillBlurhash(dto, episodeSeries, ImageType.Primary);
  983. if (dto.ImageTags is null || !dto.ImageTags.ContainsKey(ImageType.Primary))
  984. {
  985. AttachPrimaryImageAspectRatio(dto, episodeSeries);
  986. }
  987. }
  988. }
  989. if (options.ContainsField(ItemFields.SeriesStudio))
  990. {
  991. episodeSeries ??= episode.Series;
  992. if (episodeSeries is not null)
  993. {
  994. dto.SeriesStudio = episodeSeries.Studios.FirstOrDefault();
  995. }
  996. }
  997. }
  998. // Add SeriesInfo
  999. Series? series;
  1000. if (item is Series tmp)
  1001. {
  1002. series = tmp;
  1003. dto.AirDays = series.AirDays;
  1004. dto.AirTime = series.AirTime;
  1005. dto.Status = series.Status?.ToString();
  1006. }
  1007. // Add SeasonInfo
  1008. if (item is Season season)
  1009. {
  1010. dto.SeriesName = season.SeriesName;
  1011. dto.SeriesId = season.SeriesId;
  1012. series = null;
  1013. if (options.ContainsField(ItemFields.SeriesStudio))
  1014. {
  1015. series ??= season.Series;
  1016. if (series is not null)
  1017. {
  1018. dto.SeriesStudio = series.Studios.FirstOrDefault();
  1019. }
  1020. }
  1021. // this block will add the series poster for seasons without a poster
  1022. // TODO maybe remove the if statement entirely
  1023. // if (options.ContainsField(ItemFields.SeriesPrimaryImage))
  1024. {
  1025. series ??= season.Series;
  1026. if (series is not null)
  1027. {
  1028. dto.SeriesPrimaryImageTag = GetTagAndFillBlurhash(dto, series, ImageType.Primary);
  1029. if (dto.ImageTags is null || !dto.ImageTags.ContainsKey(ImageType.Primary))
  1030. {
  1031. AttachPrimaryImageAspectRatio(dto, series);
  1032. }
  1033. }
  1034. }
  1035. }
  1036. if (item is MusicVideo musicVideo)
  1037. {
  1038. SetMusicVideoProperties(dto, musicVideo);
  1039. }
  1040. if (item is Book book)
  1041. {
  1042. SetBookProperties(dto, book);
  1043. }
  1044. if (options.ContainsField(ItemFields.ProductionLocations))
  1045. {
  1046. if (item.ProductionLocations.Length > 0 || item is Movie)
  1047. {
  1048. dto.ProductionLocations = item.ProductionLocations;
  1049. }
  1050. }
  1051. if (options.ContainsField(ItemFields.Width))
  1052. {
  1053. var width = item.Width;
  1054. if (width > 0)
  1055. {
  1056. dto.Width = width;
  1057. }
  1058. }
  1059. if (options.ContainsField(ItemFields.Height))
  1060. {
  1061. var height = item.Height;
  1062. if (height > 0)
  1063. {
  1064. dto.Height = height;
  1065. }
  1066. }
  1067. if (options.ContainsField(ItemFields.IsHD))
  1068. {
  1069. // Compatibility
  1070. if (item.IsHD)
  1071. {
  1072. dto.IsHD = true;
  1073. }
  1074. }
  1075. if (item is Photo photo)
  1076. {
  1077. SetPhotoProperties(dto, photo);
  1078. }
  1079. dto.ChannelId = item.ChannelId;
  1080. if (item.SourceType == SourceType.Channel)
  1081. {
  1082. var channel = _libraryManager.GetItemById(item.ChannelId);
  1083. if (channel is not null)
  1084. {
  1085. dto.ChannelName = channel.Name;
  1086. }
  1087. }
  1088. }
  1089. private BaseItem? GetImageDisplayParent(BaseItem currentItem, BaseItem originalItem)
  1090. {
  1091. if (currentItem is MusicAlbum musicAlbum)
  1092. {
  1093. var artist = musicAlbum.GetMusicArtist(new DtoOptions(false));
  1094. if (artist is not null)
  1095. {
  1096. return artist;
  1097. }
  1098. }
  1099. var parent = currentItem.DisplayParent ?? currentItem.GetOwner() ?? currentItem.GetParent();
  1100. if (parent is null && originalItem is not UserRootFolder && originalItem is not UserView && originalItem is not AggregateFolder && originalItem is not ICollectionFolder && originalItem is not Channel)
  1101. {
  1102. parent = _libraryManager.GetCollectionFolders(originalItem).FirstOrDefault();
  1103. }
  1104. return parent;
  1105. }
  1106. private void AddInheritedImages(BaseItemDto dto, BaseItem item, DtoOptions options, BaseItem? owner)
  1107. {
  1108. if (!item.SupportsInheritedParentImages)
  1109. {
  1110. return;
  1111. }
  1112. var logoLimit = options.GetImageLimit(ImageType.Logo);
  1113. var artLimit = options.GetImageLimit(ImageType.Art);
  1114. var thumbLimit = options.GetImageLimit(ImageType.Thumb);
  1115. var backdropLimit = options.GetImageLimit(ImageType.Backdrop);
  1116. // For now. Emby apps are not using this
  1117. artLimit = 0;
  1118. if (logoLimit == 0 && artLimit == 0 && thumbLimit == 0 && backdropLimit == 0)
  1119. {
  1120. return;
  1121. }
  1122. BaseItem? parent = null;
  1123. var isFirst = true;
  1124. var imageTags = dto.ImageTags;
  1125. while ((!(imageTags is not null && imageTags.ContainsKey(ImageType.Logo)) && logoLimit > 0)
  1126. || (!(imageTags is not null && imageTags.ContainsKey(ImageType.Art)) && artLimit > 0)
  1127. || (!(imageTags is not null && imageTags.ContainsKey(ImageType.Thumb)) && thumbLimit > 0)
  1128. || parent is Series)
  1129. {
  1130. parent ??= isFirst ? GetImageDisplayParent(item, item) ?? owner : parent;
  1131. if (parent is null)
  1132. {
  1133. break;
  1134. }
  1135. var allImages = parent.ImageInfos;
  1136. if (logoLimit > 0 && !(imageTags is not null && imageTags.ContainsKey(ImageType.Logo)) && dto.ParentLogoItemId is null)
  1137. {
  1138. var image = allImages.FirstOrDefault(i => i.Type == ImageType.Logo);
  1139. if (image is not null)
  1140. {
  1141. dto.ParentLogoItemId = parent.Id;
  1142. dto.ParentLogoImageTag = GetTagAndFillBlurhash(dto, parent, image);
  1143. }
  1144. }
  1145. if (artLimit > 0 && !(imageTags is not null && imageTags.ContainsKey(ImageType.Art)) && dto.ParentArtItemId is null)
  1146. {
  1147. var image = allImages.FirstOrDefault(i => i.Type == ImageType.Art);
  1148. if (image is not null)
  1149. {
  1150. dto.ParentArtItemId = parent.Id;
  1151. dto.ParentArtImageTag = GetTagAndFillBlurhash(dto, parent, image);
  1152. }
  1153. }
  1154. if (thumbLimit > 0 && !(imageTags is not null && imageTags.ContainsKey(ImageType.Thumb)) && (dto.ParentThumbItemId is null || parent is Series) && parent is not ICollectionFolder && parent is not UserView)
  1155. {
  1156. var image = allImages.FirstOrDefault(i => i.Type == ImageType.Thumb);
  1157. if (image is not null)
  1158. {
  1159. dto.ParentThumbItemId = parent.Id;
  1160. dto.ParentThumbImageTag = GetTagAndFillBlurhash(dto, parent, image);
  1161. }
  1162. }
  1163. if (backdropLimit > 0 && !((dto.BackdropImageTags is not null && dto.BackdropImageTags.Length > 0) || (dto.ParentBackdropImageTags is not null && dto.ParentBackdropImageTags.Length > 0)))
  1164. {
  1165. var images = allImages.Where(i => i.Type == ImageType.Backdrop).Take(backdropLimit).ToList();
  1166. if (images.Count > 0)
  1167. {
  1168. dto.ParentBackdropItemId = parent.Id;
  1169. dto.ParentBackdropImageTags = GetTagsAndFillBlurhashes(dto, parent, ImageType.Backdrop, images);
  1170. }
  1171. }
  1172. isFirst = false;
  1173. if (!parent.SupportsInheritedParentImages)
  1174. {
  1175. break;
  1176. }
  1177. parent = GetImageDisplayParent(parent, item);
  1178. }
  1179. }
  1180. private string GetMappedPath(BaseItem item, BaseItem? ownerItem)
  1181. {
  1182. var path = item.Path;
  1183. if (item.IsFileProtocol)
  1184. {
  1185. path = _libraryManager.GetPathAfterNetworkSubstitution(path, ownerItem ?? item);
  1186. }
  1187. return path;
  1188. }
  1189. /// <summary>
  1190. /// Attaches the primary image aspect ratio.
  1191. /// </summary>
  1192. /// <param name="dto">The dto.</param>
  1193. /// <param name="item">The item.</param>
  1194. public void AttachPrimaryImageAspectRatio(IItemDto dto, BaseItem item)
  1195. {
  1196. dto.PrimaryImageAspectRatio = GetPrimaryImageAspectRatio(item);
  1197. }
  1198. public double? GetPrimaryImageAspectRatio(BaseItem item)
  1199. {
  1200. var imageInfo = item.GetImageInfo(ImageType.Primary, 0);
  1201. if (imageInfo is null)
  1202. {
  1203. return null;
  1204. }
  1205. if (!imageInfo.IsLocalFile)
  1206. {
  1207. return item.GetDefaultPrimaryImageAspectRatio();
  1208. }
  1209. try
  1210. {
  1211. var size = _imageProcessor.GetImageDimensions(item, imageInfo);
  1212. var width = size.Width;
  1213. var height = size.Height;
  1214. if (width > 0 && height > 0)
  1215. {
  1216. return (double)width / height;
  1217. }
  1218. }
  1219. catch (Exception ex)
  1220. {
  1221. _logger.LogError(ex, "Failed to determine primary image aspect ratio for {ImagePath}", imageInfo.Path);
  1222. }
  1223. return item.GetDefaultPrimaryImageAspectRatio();
  1224. }
  1225. }
  1226. }