DtoService.cs 50 KB

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