DtoService.cs 50 KB

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