DtoService.cs 50 KB

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