DtoService.cs 51 KB

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