DtoService.cs 50 KB

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