DtoService.cs 51 KB

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