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.Data.Entities;
  9. using Jellyfin.Data.Enums;
  10. using Jellyfin.Extensions;
  11. using MediaBrowser.Common;
  12. using MediaBrowser.Controller.Channels;
  13. using MediaBrowser.Controller.Drawing;
  14. using MediaBrowser.Controller.Dto;
  15. using MediaBrowser.Controller.Entities;
  16. using MediaBrowser.Controller.Entities.Audio;
  17. using MediaBrowser.Controller.Library;
  18. using MediaBrowser.Controller.LiveTv;
  19. using MediaBrowser.Controller.Persistence;
  20. using MediaBrowser.Controller.Playlists;
  21. using MediaBrowser.Controller.Providers;
  22. using MediaBrowser.Model.Drawing;
  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. if (item is IItemByName itemByName
  127. && options.ContainsField(ItemFields.ItemCounts))
  128. {
  129. SetItemByNameInfo(
  130. item,
  131. dto,
  132. GetTaggedItems(
  133. itemByName,
  134. user,
  135. new DtoOptions(false)
  136. {
  137. EnableImages = false
  138. }));
  139. }
  140. return dto;
  141. }
  142. private static IList<BaseItem> GetTaggedItems(IItemByName byName, User user, DtoOptions options)
  143. {
  144. return byName.GetTaggedItems(
  145. new InternalItemsQuery(user)
  146. {
  147. Recursive = true,
  148. DtoOptions = options
  149. });
  150. }
  151. private BaseItemDto GetBaseItemDtoInternal(BaseItem item, DtoOptions options, User user = null, BaseItem owner = null)
  152. {
  153. var dto = new BaseItemDto
  154. {
  155. ServerId = _appHost.SystemId
  156. };
  157. if (item.SourceType == SourceType.Channel)
  158. {
  159. dto.SourceType = item.SourceType.ToString();
  160. }
  161. if (options.ContainsField(ItemFields.People))
  162. {
  163. AttachPeople(dto, item);
  164. }
  165. if (options.ContainsField(ItemFields.PrimaryImageAspectRatio))
  166. {
  167. try
  168. {
  169. AttachPrimaryImageAspectRatio(dto, item);
  170. }
  171. catch (Exception ex)
  172. {
  173. // Have to use a catch-all unfortunately because some .net image methods throw plain Exceptions
  174. _logger.LogError(ex, "Error generating PrimaryImageAspectRatio for {ItemName}", item.Name);
  175. }
  176. }
  177. if (options.ContainsField(ItemFields.DisplayPreferencesId))
  178. {
  179. dto.DisplayPreferencesId = item.DisplayPreferencesId.ToString("N", CultureInfo.InvariantCulture);
  180. }
  181. if (user != null)
  182. {
  183. AttachUserSpecificInfo(dto, item, user, options);
  184. }
  185. if (item is IHasMediaSources
  186. && options.ContainsField(ItemFields.MediaSources))
  187. {
  188. dto.MediaSources = _mediaSourceManager.GetStaticMediaSources(item, true, user).ToArray();
  189. NormalizeMediaSourceContainers(dto);
  190. }
  191. if (options.ContainsField(ItemFields.Studios))
  192. {
  193. AttachStudios(dto, item);
  194. }
  195. AttachBasicFields(dto, item, owner, options);
  196. if (options.ContainsField(ItemFields.CanDelete))
  197. {
  198. dto.CanDelete = user == null
  199. ? item.CanDelete()
  200. : item.CanDelete(user);
  201. }
  202. if (options.ContainsField(ItemFields.CanDownload))
  203. {
  204. dto.CanDownload = user == null
  205. ? item.CanDownload()
  206. : item.CanDownload(user);
  207. }
  208. if (options.ContainsField(ItemFields.Etag))
  209. {
  210. dto.Etag = item.GetEtag(user);
  211. }
  212. var liveTvManager = LivetvManager;
  213. var activeRecording = liveTvManager.GetActiveRecordingInfo(item.Path);
  214. if (activeRecording != null)
  215. {
  216. dto.Type = BaseItemKind.Recording;
  217. dto.CanDownload = false;
  218. dto.RunTimeTicks = null;
  219. if (!string.IsNullOrEmpty(dto.SeriesName))
  220. {
  221. dto.EpisodeTitle = dto.Name;
  222. dto.Name = dto.SeriesName;
  223. }
  224. liveTvManager.AddInfoToRecordingDto(item, dto, activeRecording, user);
  225. }
  226. return dto;
  227. }
  228. private static void NormalizeMediaSourceContainers(BaseItemDto dto)
  229. {
  230. foreach (var mediaSource in dto.MediaSources)
  231. {
  232. var container = mediaSource.Container;
  233. if (string.IsNullOrEmpty(container))
  234. {
  235. continue;
  236. }
  237. var containers = container.Split(',');
  238. if (containers.Length < 2)
  239. {
  240. continue;
  241. }
  242. var path = mediaSource.Path;
  243. string fileExtensionContainer = null;
  244. if (!string.IsNullOrEmpty(path))
  245. {
  246. path = Path.GetExtension(path);
  247. if (!string.IsNullOrEmpty(path))
  248. {
  249. path = Path.GetExtension(path);
  250. if (!string.IsNullOrEmpty(path))
  251. {
  252. path = path.TrimStart('.');
  253. }
  254. if (!string.IsNullOrEmpty(path) && containers.Contains(path, StringComparison.OrdinalIgnoreCase))
  255. {
  256. fileExtensionContainer = path;
  257. }
  258. }
  259. }
  260. mediaSource.Container = fileExtensionContainer ?? containers[0];
  261. }
  262. }
  263. public BaseItemDto GetItemByNameDto(BaseItem item, DtoOptions options, List<BaseItem> taggedItems, User user = null)
  264. {
  265. var dto = GetBaseItemDtoInternal(item, options, user);
  266. if (taggedItems != null && options.ContainsField(ItemFields.ItemCounts))
  267. {
  268. SetItemByNameInfo(item, dto, taggedItems);
  269. }
  270. return dto;
  271. }
  272. private static void SetItemByNameInfo(BaseItem item, BaseItemDto dto, IList<BaseItem> taggedItems)
  273. {
  274. if (item is MusicArtist)
  275. {
  276. dto.AlbumCount = taggedItems.Count(i => i is MusicAlbum);
  277. dto.MusicVideoCount = taggedItems.Count(i => i is MusicVideo);
  278. dto.SongCount = taggedItems.Count(i => i is Audio);
  279. }
  280. else if (item is MusicGenre)
  281. {
  282. dto.ArtistCount = taggedItems.Count(i => i is MusicArtist);
  283. dto.AlbumCount = taggedItems.Count(i => i is MusicAlbum);
  284. dto.MusicVideoCount = taggedItems.Count(i => i is MusicVideo);
  285. dto.SongCount = taggedItems.Count(i => i is Audio);
  286. }
  287. else
  288. {
  289. // This populates them all and covers Genre, Person, Studio, Year
  290. dto.ArtistCount = taggedItems.Count(i => i is MusicArtist);
  291. dto.AlbumCount = taggedItems.Count(i => i is MusicAlbum);
  292. dto.EpisodeCount = taggedItems.Count(i => i is Episode);
  293. dto.MovieCount = taggedItems.Count(i => i is Movie);
  294. dto.TrailerCount = taggedItems.Count(i => i is Trailer);
  295. dto.MusicVideoCount = taggedItems.Count(i => i is MusicVideo);
  296. dto.SeriesCount = taggedItems.Count(i => i is Series);
  297. dto.ProgramCount = taggedItems.Count(i => i is LiveTvProgram);
  298. dto.SongCount = taggedItems.Count(i => i is Audio);
  299. }
  300. dto.ChildCount = taggedItems.Count;
  301. }
  302. /// <summary>
  303. /// Attaches the user specific info.
  304. /// </summary>
  305. private void AttachUserSpecificInfo(BaseItemDto dto, BaseItem item, User user, DtoOptions options)
  306. {
  307. if (item.IsFolder)
  308. {
  309. var folder = (Folder)item;
  310. if (options.EnableUserData)
  311. {
  312. dto.UserData = _userDataRepository.GetUserDataDto(item, dto, user, options);
  313. }
  314. if (!dto.ChildCount.HasValue && item.SourceType == SourceType.Library)
  315. {
  316. // For these types we can try to optimize and assume these values will be equal
  317. if (item is MusicAlbum || item is Season || item is Playlist)
  318. {
  319. dto.ChildCount = dto.RecursiveItemCount;
  320. var folderChildCount = folder.LinkedChildren.Length;
  321. // The default is an empty array, so we can't reliably use the count when it's empty
  322. if (folderChildCount > 0)
  323. {
  324. dto.ChildCount ??= folderChildCount;
  325. }
  326. }
  327. if (options.ContainsField(ItemFields.ChildCount))
  328. {
  329. dto.ChildCount ??= GetChildCount(folder, user);
  330. }
  331. }
  332. if (options.ContainsField(ItemFields.CumulativeRunTimeTicks))
  333. {
  334. dto.CumulativeRunTimeTicks = item.RunTimeTicks;
  335. }
  336. if (options.ContainsField(ItemFields.DateLastMediaAdded))
  337. {
  338. dto.DateLastMediaAdded = folder.DateLastMediaAdded;
  339. }
  340. }
  341. else
  342. {
  343. if (options.EnableUserData)
  344. {
  345. dto.UserData = _userDataRepository.GetUserDataDto(item, user);
  346. }
  347. }
  348. if (options.ContainsField(ItemFields.PlayAccess))
  349. {
  350. dto.PlayAccess = item.GetPlayAccess(user);
  351. }
  352. if (options.ContainsField(ItemFields.BasicSyncInfo))
  353. {
  354. var userCanSync = user != null && user.HasPermission(PermissionKind.EnableContentDownloading);
  355. if (userCanSync && item.SupportsExternalTransfer)
  356. {
  357. dto.SupportsSync = true;
  358. }
  359. }
  360. }
  361. private static int GetChildCount(Folder folder, User user)
  362. {
  363. // Right now this is too slow to calculate for top level folders on a per-user basis
  364. // Just return something so that apps that are expecting a value won't think the folders are empty
  365. if (folder is ICollectionFolder || folder is UserView)
  366. {
  367. return Random.Shared.Next(1, 10);
  368. }
  369. return folder.GetChildCount(user);
  370. }
  371. private static void SetBookProperties(BaseItemDto dto, Book item)
  372. {
  373. dto.SeriesName = item.SeriesName;
  374. }
  375. private static void SetPhotoProperties(BaseItemDto dto, Photo item)
  376. {
  377. dto.CameraMake = item.CameraMake;
  378. dto.CameraModel = item.CameraModel;
  379. dto.Software = item.Software;
  380. dto.ExposureTime = item.ExposureTime;
  381. dto.FocalLength = item.FocalLength;
  382. dto.ImageOrientation = item.Orientation;
  383. dto.Aperture = item.Aperture;
  384. dto.ShutterSpeed = item.ShutterSpeed;
  385. dto.Latitude = item.Latitude;
  386. dto.Longitude = item.Longitude;
  387. dto.Altitude = item.Altitude;
  388. dto.IsoSpeedRating = item.IsoSpeedRating;
  389. var album = item.AlbumEntity;
  390. if (album != null)
  391. {
  392. dto.Album = album.Name;
  393. dto.AlbumId = album.Id;
  394. }
  395. }
  396. private void SetMusicVideoProperties(BaseItemDto dto, MusicVideo item)
  397. {
  398. if (!string.IsNullOrEmpty(item.Album))
  399. {
  400. var parentAlbumIds = _libraryManager.GetItemIds(new InternalItemsQuery
  401. {
  402. IncludeItemTypes = new[] { BaseItemKind.MusicAlbum },
  403. Name = item.Album,
  404. Limit = 1
  405. });
  406. if (parentAlbumIds.Count > 0)
  407. {
  408. dto.AlbumId = parentAlbumIds[0];
  409. }
  410. }
  411. dto.Album = item.Album;
  412. }
  413. private string[] GetImageTags(BaseItem item, List<ItemImageInfo> images)
  414. {
  415. return images
  416. .Select(p => GetImageCacheTag(item, p))
  417. .Where(i => i != null)
  418. .ToArray();
  419. }
  420. private string GetImageCacheTag(BaseItem item, ItemImageInfo image)
  421. {
  422. try
  423. {
  424. return _imageProcessor.GetImageCacheTag(item, image);
  425. }
  426. catch (Exception ex)
  427. {
  428. _logger.LogError(ex, "Error getting {ImageType} image info for {Path}", image.Type, image.Path);
  429. return null;
  430. }
  431. }
  432. /// <summary>
  433. /// Attaches People DTO's to a DTOBaseItem.
  434. /// </summary>
  435. /// <param name="dto">The dto.</param>
  436. /// <param name="item">The item.</param>
  437. private void AttachPeople(BaseItemDto dto, BaseItem item)
  438. {
  439. // Ordering by person type to ensure actors and artists are at the front.
  440. // This is taking advantage of the fact that they both begin with A
  441. // This should be improved in the future
  442. var people = _libraryManager.GetPeople(item).OrderBy(i => i.SortOrder ?? int.MaxValue)
  443. .ThenBy(i =>
  444. {
  445. if (i.IsType(PersonType.Actor))
  446. {
  447. return 0;
  448. }
  449. if (i.IsType(PersonType.GuestStar))
  450. {
  451. return 1;
  452. }
  453. if (i.IsType(PersonType.Director))
  454. {
  455. return 2;
  456. }
  457. if (i.IsType(PersonType.Writer))
  458. {
  459. return 3;
  460. }
  461. if (i.IsType(PersonType.Producer))
  462. {
  463. return 4;
  464. }
  465. if (i.IsType(PersonType.Composer))
  466. {
  467. return 4;
  468. }
  469. return 10;
  470. })
  471. .ToList();
  472. var list = new List<BaseItemPerson>();
  473. var dictionary = people.Select(p => p.Name)
  474. .Distinct(StringComparer.OrdinalIgnoreCase).Select(c =>
  475. {
  476. try
  477. {
  478. return _libraryManager.GetPerson(c);
  479. }
  480. catch (Exception ex)
  481. {
  482. _logger.LogError(ex, "Error getting person {Name}", c);
  483. return null;
  484. }
  485. }).Where(i => i != null)
  486. .GroupBy(i => i.Name, StringComparer.OrdinalIgnoreCase)
  487. .Select(x => x.First())
  488. .ToDictionary(i => i.Name, StringComparer.OrdinalIgnoreCase);
  489. for (var i = 0; i < people.Count; i++)
  490. {
  491. var person = people[i];
  492. var baseItemPerson = new BaseItemPerson
  493. {
  494. Name = person.Name,
  495. Role = person.Role,
  496. Type = person.Type
  497. };
  498. if (dictionary.TryGetValue(person.Name, out Person entity))
  499. {
  500. baseItemPerson.PrimaryImageTag = GetTagAndFillBlurhash(dto, entity, ImageType.Primary);
  501. baseItemPerson.Id = entity.Id;
  502. if (dto.ImageBlurHashes != null)
  503. {
  504. // Only add BlurHash for the person's image.
  505. baseItemPerson.ImageBlurHashes = new Dictionary<ImageType, Dictionary<string, string>>();
  506. foreach (var (imageType, blurHash) in dto.ImageBlurHashes)
  507. {
  508. if (blurHash != null)
  509. {
  510. baseItemPerson.ImageBlurHashes[imageType] = new Dictionary<string, string>();
  511. foreach (var (imageId, blurHashValue) in blurHash)
  512. {
  513. if (string.Equals(baseItemPerson.PrimaryImageTag, imageId, StringComparison.OrdinalIgnoreCase))
  514. {
  515. baseItemPerson.ImageBlurHashes[imageType][imageId] = blurHashValue;
  516. }
  517. }
  518. }
  519. }
  520. }
  521. list.Add(baseItemPerson);
  522. }
  523. }
  524. dto.People = list.ToArray();
  525. }
  526. /// <summary>
  527. /// Attaches the studios.
  528. /// </summary>
  529. /// <param name="dto">The dto.</param>
  530. /// <param name="item">The item.</param>
  531. private void AttachStudios(BaseItemDto dto, BaseItem item)
  532. {
  533. dto.Studios = item.Studios
  534. .Where(i => !string.IsNullOrEmpty(i))
  535. .Select(i => new NameGuidPair
  536. {
  537. Name = i,
  538. Id = _libraryManager.GetStudioId(i)
  539. })
  540. .ToArray();
  541. }
  542. private void AttachGenreItems(BaseItemDto dto, BaseItem item)
  543. {
  544. dto.GenreItems = item.Genres
  545. .Where(i => !string.IsNullOrEmpty(i))
  546. .Select(i => new NameGuidPair
  547. {
  548. Name = i,
  549. Id = GetGenreId(i, item)
  550. })
  551. .ToArray();
  552. }
  553. private Guid GetGenreId(string name, BaseItem owner)
  554. {
  555. if (owner is IHasMusicGenres)
  556. {
  557. return _libraryManager.GetMusicGenreId(name);
  558. }
  559. return _libraryManager.GetGenreId(name);
  560. }
  561. private string GetTagAndFillBlurhash(BaseItemDto dto, BaseItem item, ImageType imageType, int imageIndex = 0)
  562. {
  563. var image = item.GetImageInfo(imageType, imageIndex);
  564. if (image != null)
  565. {
  566. return GetTagAndFillBlurhash(dto, item, image);
  567. }
  568. return null;
  569. }
  570. private string GetTagAndFillBlurhash(BaseItemDto dto, BaseItem item, ItemImageInfo image)
  571. {
  572. var tag = GetImageCacheTag(item, image);
  573. if (!string.IsNullOrEmpty(image.BlurHash))
  574. {
  575. dto.ImageBlurHashes ??= new Dictionary<ImageType, Dictionary<string, string>>();
  576. if (!dto.ImageBlurHashes.ContainsKey(image.Type))
  577. {
  578. dto.ImageBlurHashes[image.Type] = new Dictionary<string, string>();
  579. }
  580. dto.ImageBlurHashes[image.Type][tag] = image.BlurHash;
  581. }
  582. return tag;
  583. }
  584. private string[] GetTagsAndFillBlurhashes(BaseItemDto dto, BaseItem item, ImageType imageType, int limit)
  585. {
  586. return GetTagsAndFillBlurhashes(dto, item, imageType, item.GetImages(imageType).Take(limit).ToList());
  587. }
  588. private string[] GetTagsAndFillBlurhashes(BaseItemDto dto, BaseItem item, ImageType imageType, List<ItemImageInfo> images)
  589. {
  590. var tags = GetImageTags(item, images);
  591. var hashes = new Dictionary<string, string>();
  592. for (int i = 0; i < images.Count; i++)
  593. {
  594. var img = images[i];
  595. if (!string.IsNullOrEmpty(img.BlurHash))
  596. {
  597. var tag = tags[i];
  598. hashes[tag] = img.BlurHash;
  599. }
  600. }
  601. if (hashes.Count > 0)
  602. {
  603. dto.ImageBlurHashes ??= new Dictionary<ImageType, Dictionary<string, string>>();
  604. dto.ImageBlurHashes[imageType] = hashes;
  605. }
  606. return tags;
  607. }
  608. /// <summary>
  609. /// Sets simple property values on a DTOBaseItem.
  610. /// </summary>
  611. /// <param name="dto">The dto.</param>
  612. /// <param name="item">The item.</param>
  613. /// <param name="owner">The owner.</param>
  614. /// <param name="options">The options.</param>
  615. private void AttachBasicFields(BaseItemDto dto, BaseItem item, BaseItem owner, DtoOptions options)
  616. {
  617. if (options.ContainsField(ItemFields.DateCreated))
  618. {
  619. dto.DateCreated = item.DateCreated;
  620. }
  621. if (options.ContainsField(ItemFields.Settings))
  622. {
  623. dto.LockedFields = item.LockedFields;
  624. dto.LockData = item.IsLocked;
  625. dto.ForcedSortName = item.ForcedSortName;
  626. }
  627. dto.Container = item.Container;
  628. dto.EndDate = item.EndDate;
  629. if (options.ContainsField(ItemFields.ExternalUrls))
  630. {
  631. dto.ExternalUrls = _providerManager.GetExternalUrls(item).ToArray();
  632. }
  633. if (options.ContainsField(ItemFields.Tags))
  634. {
  635. dto.Tags = item.Tags;
  636. }
  637. var hasAspectRatio = item as IHasAspectRatio;
  638. if (hasAspectRatio != null)
  639. {
  640. dto.AspectRatio = hasAspectRatio.AspectRatio;
  641. }
  642. dto.ImageBlurHashes = new Dictionary<ImageType, Dictionary<string, string>>();
  643. var backdropLimit = options.GetImageLimit(ImageType.Backdrop);
  644. if (backdropLimit > 0)
  645. {
  646. dto.BackdropImageTags = GetTagsAndFillBlurhashes(dto, item, ImageType.Backdrop, backdropLimit);
  647. }
  648. if (options.ContainsField(ItemFields.Genres))
  649. {
  650. dto.Genres = item.Genres;
  651. AttachGenreItems(dto, item);
  652. }
  653. if (options.EnableImages)
  654. {
  655. dto.ImageTags = new Dictionary<ImageType, string>();
  656. // Prevent implicitly captured closure
  657. var currentItem = item;
  658. foreach (var image in currentItem.ImageInfos.Where(i => !currentItem.AllowsMultipleImages(i.Type)))
  659. {
  660. if (options.GetImageLimit(image.Type) > 0)
  661. {
  662. var tag = GetTagAndFillBlurhash(dto, item, image);
  663. if (tag != null)
  664. {
  665. dto.ImageTags[image.Type] = tag;
  666. }
  667. }
  668. }
  669. }
  670. dto.Id = item.Id;
  671. dto.IndexNumber = item.IndexNumber;
  672. dto.ParentIndexNumber = item.ParentIndexNumber;
  673. if (item.IsFolder)
  674. {
  675. dto.IsFolder = true;
  676. }
  677. else if (item is IHasMediaSources)
  678. {
  679. dto.IsFolder = false;
  680. }
  681. dto.MediaType = item.MediaType;
  682. if (item is not LiveTvProgram)
  683. {
  684. dto.LocationType = item.LocationType;
  685. }
  686. dto.Audio = item.Audio;
  687. if (options.ContainsField(ItemFields.Settings))
  688. {
  689. dto.PreferredMetadataCountryCode = item.PreferredMetadataCountryCode;
  690. dto.PreferredMetadataLanguage = item.PreferredMetadataLanguage;
  691. }
  692. dto.CriticRating = item.CriticRating;
  693. if (item is IHasDisplayOrder hasDisplayOrder)
  694. {
  695. dto.DisplayOrder = hasDisplayOrder.DisplayOrder;
  696. }
  697. if (item is IHasCollectionType hasCollectionType)
  698. {
  699. dto.CollectionType = hasCollectionType.CollectionType;
  700. }
  701. if (options.ContainsField(ItemFields.RemoteTrailers))
  702. {
  703. dto.RemoteTrailers = item.RemoteTrailers;
  704. }
  705. dto.Name = item.Name;
  706. dto.OfficialRating = item.OfficialRating;
  707. if (options.ContainsField(ItemFields.Overview))
  708. {
  709. dto.Overview = item.Overview;
  710. }
  711. if (options.ContainsField(ItemFields.OriginalTitle))
  712. {
  713. dto.OriginalTitle = item.OriginalTitle;
  714. }
  715. if (options.ContainsField(ItemFields.ParentId))
  716. {
  717. dto.ParentId = item.DisplayParentId;
  718. }
  719. AddInheritedImages(dto, item, options, owner);
  720. if (options.ContainsField(ItemFields.Path))
  721. {
  722. dto.Path = GetMappedPath(item, owner);
  723. }
  724. if (options.ContainsField(ItemFields.EnableMediaSourceDisplay))
  725. {
  726. dto.EnableMediaSourceDisplay = item.EnableMediaSourceDisplay;
  727. }
  728. dto.PremiereDate = item.PremiereDate;
  729. dto.ProductionYear = item.ProductionYear;
  730. if (options.ContainsField(ItemFields.ProviderIds))
  731. {
  732. dto.ProviderIds = item.ProviderIds;
  733. }
  734. dto.RunTimeTicks = item.RunTimeTicks;
  735. if (options.ContainsField(ItemFields.SortName))
  736. {
  737. dto.SortName = item.SortName;
  738. }
  739. if (options.ContainsField(ItemFields.CustomRating))
  740. {
  741. dto.CustomRating = item.CustomRating;
  742. }
  743. if (options.ContainsField(ItemFields.Taglines))
  744. {
  745. if (!string.IsNullOrEmpty(item.Tagline))
  746. {
  747. dto.Taglines = new string[] { item.Tagline };
  748. }
  749. dto.Taglines ??= Array.Empty<string>();
  750. }
  751. dto.Type = item.GetBaseItemKind();
  752. if ((item.CommunityRating ?? 0) > 0)
  753. {
  754. dto.CommunityRating = item.CommunityRating;
  755. }
  756. var supportsPlaceHolders = item as ISupportsPlaceHolders;
  757. if (supportsPlaceHolders != null && supportsPlaceHolders.IsPlaceHolder)
  758. {
  759. dto.IsPlaceHolder = supportsPlaceHolders.IsPlaceHolder;
  760. }
  761. // Add audio info
  762. var audio = item as Audio;
  763. if (audio != null)
  764. {
  765. dto.Album = audio.Album;
  766. if (audio.ExtraType.HasValue)
  767. {
  768. dto.ExtraType = audio.ExtraType.Value.ToString();
  769. }
  770. var albumParent = audio.AlbumEntity;
  771. if (albumParent != null)
  772. {
  773. dto.AlbumId = albumParent.Id;
  774. dto.AlbumPrimaryImageTag = GetTagAndFillBlurhash(dto, albumParent, ImageType.Primary);
  775. }
  776. // if (options.ContainsField(ItemFields.MediaSourceCount))
  777. // {
  778. // Songs always have one
  779. // }
  780. }
  781. if (item is IHasArtist hasArtist)
  782. {
  783. dto.Artists = hasArtist.Artists;
  784. // var artistItems = _libraryManager.GetArtists(new InternalItemsQuery
  785. // {
  786. // EnableTotalRecordCount = false,
  787. // ItemIds = new[] { item.Id.ToString("N", CultureInfo.InvariantCulture) }
  788. // });
  789. // dto.ArtistItems = artistItems.Items
  790. // .Select(i =>
  791. // {
  792. // var artist = i.Item1;
  793. // return new NameIdPair
  794. // {
  795. // Name = artist.Name,
  796. // Id = artist.Id.ToString("N", CultureInfo.InvariantCulture)
  797. // };
  798. // })
  799. // .ToList();
  800. // Include artists that are not in the database yet, e.g., just added via metadata editor
  801. // var foundArtists = artistItems.Items.Select(i => i.Item1.Name).ToList();
  802. dto.ArtistItems = hasArtist.Artists
  803. // .Except(foundArtists, new DistinctNameComparer())
  804. .Select(i =>
  805. {
  806. // This should not be necessary but we're seeing some cases of it
  807. if (string.IsNullOrEmpty(i))
  808. {
  809. return null;
  810. }
  811. var artist = _libraryManager.GetArtist(i, new DtoOptions(false)
  812. {
  813. EnableImages = false
  814. });
  815. if (artist != null)
  816. {
  817. return new NameGuidPair
  818. {
  819. Name = artist.Name,
  820. Id = artist.Id
  821. };
  822. }
  823. return null;
  824. }).Where(i => i != null).ToArray();
  825. }
  826. var hasAlbumArtist = item as IHasAlbumArtist;
  827. if (hasAlbumArtist != null)
  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.GetTrailerCount();
  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 == 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 == 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 == 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. }