DtoService.cs 51 KB

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