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