DtoService.cs 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432
  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.ContainsKey(image.Type))
  580. {
  581. dto.ImageBlurHashes[image.Type] = new Dictionary<string, string>();
  582. }
  583. dto.ImageBlurHashes[image.Type][tag] = image.BlurHash;
  584. }
  585. return tag;
  586. }
  587. private string[] GetTagsAndFillBlurhashes(BaseItemDto dto, BaseItem item, ImageType imageType, int limit)
  588. {
  589. return GetTagsAndFillBlurhashes(dto, item, imageType, item.GetImages(imageType).Take(limit).ToList());
  590. }
  591. private string[] GetTagsAndFillBlurhashes(BaseItemDto dto, BaseItem item, ImageType imageType, List<ItemImageInfo> images)
  592. {
  593. var tags = GetImageTags(item, images);
  594. var hashes = new Dictionary<string, string>();
  595. for (int i = 0; i < images.Count; i++)
  596. {
  597. var img = images[i];
  598. if (!string.IsNullOrEmpty(img.BlurHash))
  599. {
  600. var tag = tags[i];
  601. hashes[tag] = img.BlurHash;
  602. }
  603. }
  604. if (hashes.Count > 0)
  605. {
  606. dto.ImageBlurHashes ??= new Dictionary<ImageType, Dictionary<string, string>>();
  607. dto.ImageBlurHashes[imageType] = hashes;
  608. }
  609. return tags;
  610. }
  611. /// <summary>
  612. /// Sets simple property values on a DTOBaseItem.
  613. /// </summary>
  614. /// <param name="dto">The dto.</param>
  615. /// <param name="item">The item.</param>
  616. /// <param name="owner">The owner.</param>
  617. /// <param name="options">The options.</param>
  618. private void AttachBasicFields(BaseItemDto dto, BaseItem item, BaseItem owner, DtoOptions options)
  619. {
  620. if (options.ContainsField(ItemFields.DateCreated))
  621. {
  622. dto.DateCreated = item.DateCreated;
  623. }
  624. if (options.ContainsField(ItemFields.Settings))
  625. {
  626. dto.LockedFields = item.LockedFields;
  627. dto.LockData = item.IsLocked;
  628. dto.ForcedSortName = item.ForcedSortName;
  629. }
  630. dto.Container = item.Container;
  631. dto.EndDate = item.EndDate;
  632. if (options.ContainsField(ItemFields.ExternalUrls))
  633. {
  634. dto.ExternalUrls = _providerManager.GetExternalUrls(item).ToArray();
  635. }
  636. if (options.ContainsField(ItemFields.Tags))
  637. {
  638. dto.Tags = item.Tags;
  639. }
  640. if (item is IHasAspectRatio hasAspectRatio)
  641. {
  642. dto.AspectRatio = hasAspectRatio.AspectRatio;
  643. }
  644. dto.ImageBlurHashes = new Dictionary<ImageType, Dictionary<string, string>>();
  645. var backdropLimit = options.GetImageLimit(ImageType.Backdrop);
  646. if (backdropLimit > 0)
  647. {
  648. dto.BackdropImageTags = GetTagsAndFillBlurhashes(dto, item, ImageType.Backdrop, backdropLimit);
  649. }
  650. if (options.ContainsField(ItemFields.Genres))
  651. {
  652. dto.Genres = item.Genres;
  653. AttachGenreItems(dto, item);
  654. }
  655. if (options.EnableImages)
  656. {
  657. dto.ImageTags = new Dictionary<ImageType, string>();
  658. // Prevent implicitly captured closure
  659. var currentItem = item;
  660. foreach (var image in currentItem.ImageInfos.Where(i => !currentItem.AllowsMultipleImages(i.Type)))
  661. {
  662. if (options.GetImageLimit(image.Type) > 0)
  663. {
  664. var tag = GetTagAndFillBlurhash(dto, item, image);
  665. if (tag is not null)
  666. {
  667. dto.ImageTags[image.Type] = tag;
  668. }
  669. }
  670. }
  671. }
  672. dto.Id = item.Id;
  673. dto.IndexNumber = item.IndexNumber;
  674. dto.ParentIndexNumber = item.ParentIndexNumber;
  675. if (item.IsFolder)
  676. {
  677. dto.IsFolder = true;
  678. }
  679. else if (item is IHasMediaSources)
  680. {
  681. dto.IsFolder = false;
  682. }
  683. dto.MediaType = item.MediaType;
  684. if (item is not LiveTvProgram)
  685. {
  686. dto.LocationType = item.LocationType;
  687. }
  688. dto.Audio = item.Audio;
  689. if (options.ContainsField(ItemFields.Settings))
  690. {
  691. dto.PreferredMetadataCountryCode = item.PreferredMetadataCountryCode;
  692. dto.PreferredMetadataLanguage = item.PreferredMetadataLanguage;
  693. }
  694. dto.CriticRating = item.CriticRating;
  695. if (item is IHasDisplayOrder hasDisplayOrder)
  696. {
  697. dto.DisplayOrder = hasDisplayOrder.DisplayOrder;
  698. }
  699. if (item is IHasCollectionType hasCollectionType)
  700. {
  701. dto.CollectionType = hasCollectionType.CollectionType;
  702. }
  703. if (options.ContainsField(ItemFields.RemoteTrailers))
  704. {
  705. dto.RemoteTrailers = item.RemoteTrailers;
  706. }
  707. dto.Name = item.Name;
  708. dto.OfficialRating = item.OfficialRating;
  709. if (options.ContainsField(ItemFields.Overview))
  710. {
  711. dto.Overview = item.Overview;
  712. }
  713. if (options.ContainsField(ItemFields.OriginalTitle))
  714. {
  715. dto.OriginalTitle = item.OriginalTitle;
  716. }
  717. if (options.ContainsField(ItemFields.ParentId))
  718. {
  719. dto.ParentId = item.DisplayParentId;
  720. }
  721. AddInheritedImages(dto, item, options, owner);
  722. if (options.ContainsField(ItemFields.Path))
  723. {
  724. dto.Path = GetMappedPath(item, owner);
  725. }
  726. if (options.ContainsField(ItemFields.EnableMediaSourceDisplay))
  727. {
  728. dto.EnableMediaSourceDisplay = item.EnableMediaSourceDisplay;
  729. }
  730. dto.PremiereDate = item.PremiereDate;
  731. dto.ProductionYear = item.ProductionYear;
  732. if (options.ContainsField(ItemFields.ProviderIds))
  733. {
  734. dto.ProviderIds = item.ProviderIds;
  735. }
  736. dto.RunTimeTicks = item.RunTimeTicks;
  737. if (options.ContainsField(ItemFields.SortName))
  738. {
  739. dto.SortName = item.SortName;
  740. }
  741. if (options.ContainsField(ItemFields.CustomRating))
  742. {
  743. dto.CustomRating = item.CustomRating;
  744. }
  745. if (options.ContainsField(ItemFields.Taglines))
  746. {
  747. if (!string.IsNullOrEmpty(item.Tagline))
  748. {
  749. dto.Taglines = new string[] { item.Tagline };
  750. }
  751. dto.Taglines ??= Array.Empty<string>();
  752. }
  753. dto.Type = item.GetBaseItemKind();
  754. if ((item.CommunityRating ?? 0) > 0)
  755. {
  756. dto.CommunityRating = item.CommunityRating;
  757. }
  758. if (item is ISupportsPlaceHolders supportsPlaceHolders && supportsPlaceHolders.IsPlaceHolder)
  759. {
  760. dto.IsPlaceHolder = supportsPlaceHolders.IsPlaceHolder;
  761. }
  762. dto.LUFS = item.LUFS;
  763. // Add audio info
  764. if (item is Audio audio)
  765. {
  766. dto.Album = audio.Album;
  767. if (audio.ExtraType.HasValue)
  768. {
  769. dto.ExtraType = audio.ExtraType.Value.ToString();
  770. }
  771. var albumParent = audio.AlbumEntity;
  772. if (albumParent is not null)
  773. {
  774. dto.AlbumId = albumParent.Id;
  775. dto.AlbumPrimaryImageTag = GetTagAndFillBlurhash(dto, albumParent, ImageType.Primary);
  776. }
  777. // if (options.ContainsField(ItemFields.MediaSourceCount))
  778. // {
  779. // Songs always have one
  780. // }
  781. }
  782. if (item is IHasArtist hasArtist)
  783. {
  784. dto.Artists = hasArtist.Artists;
  785. // var artistItems = _libraryManager.GetArtists(new InternalItemsQuery
  786. // {
  787. // EnableTotalRecordCount = false,
  788. // ItemIds = new[] { item.Id.ToString("N", CultureInfo.InvariantCulture) }
  789. // });
  790. // dto.ArtistItems = artistItems.Items
  791. // .Select(i =>
  792. // {
  793. // var artist = i.Item1;
  794. // return new NameIdPair
  795. // {
  796. // Name = artist.Name,
  797. // Id = artist.Id.ToString("N", CultureInfo.InvariantCulture)
  798. // };
  799. // })
  800. // .ToList();
  801. // Include artists that are not in the database yet, e.g., just added via metadata editor
  802. // var foundArtists = artistItems.Items.Select(i => i.Item1.Name).ToList();
  803. dto.ArtistItems = hasArtist.Artists
  804. // .Except(foundArtists, new DistinctNameComparer())
  805. .Select(i =>
  806. {
  807. // This should not be necessary but we're seeing some cases of it
  808. if (string.IsNullOrEmpty(i))
  809. {
  810. return null;
  811. }
  812. var artist = _libraryManager.GetArtist(i, new DtoOptions(false)
  813. {
  814. EnableImages = false
  815. });
  816. if (artist is not null)
  817. {
  818. return new NameGuidPair
  819. {
  820. Name = artist.Name,
  821. Id = artist.Id
  822. };
  823. }
  824. return null;
  825. }).Where(i => i is not null).ToArray();
  826. }
  827. if (item is IHasAlbumArtist hasAlbumArtist)
  828. {
  829. dto.AlbumArtist = hasAlbumArtist.AlbumArtists.FirstOrDefault();
  830. // var artistItems = _libraryManager.GetAlbumArtists(new InternalItemsQuery
  831. // {
  832. // EnableTotalRecordCount = false,
  833. // ItemIds = new[] { item.Id.ToString("N", CultureInfo.InvariantCulture) }
  834. // });
  835. // dto.AlbumArtists = artistItems.Items
  836. // .Select(i =>
  837. // {
  838. // var artist = i.Item1;
  839. // return new NameIdPair
  840. // {
  841. // Name = artist.Name,
  842. // Id = artist.Id.ToString("N", CultureInfo.InvariantCulture)
  843. // };
  844. // })
  845. // .ToList();
  846. dto.AlbumArtists = hasAlbumArtist.AlbumArtists
  847. // .Except(foundArtists, new DistinctNameComparer())
  848. .Select(i =>
  849. {
  850. // This should not be necessary but we're seeing some cases of it
  851. if (string.IsNullOrEmpty(i))
  852. {
  853. return null;
  854. }
  855. var artist = _libraryManager.GetArtist(i, new DtoOptions(false)
  856. {
  857. EnableImages = false
  858. });
  859. if (artist is not null)
  860. {
  861. return new NameGuidPair
  862. {
  863. Name = artist.Name,
  864. Id = artist.Id
  865. };
  866. }
  867. return null;
  868. }).Where(i => i is not null).ToArray();
  869. }
  870. // Add video info
  871. if (item is Video video)
  872. {
  873. dto.VideoType = video.VideoType;
  874. dto.Video3DFormat = video.Video3DFormat;
  875. dto.IsoType = video.IsoType;
  876. if (video.HasSubtitles)
  877. {
  878. dto.HasSubtitles = video.HasSubtitles;
  879. }
  880. if (video.AdditionalParts.Length != 0)
  881. {
  882. dto.PartCount = video.AdditionalParts.Length + 1;
  883. }
  884. if (options.ContainsField(ItemFields.MediaSourceCount))
  885. {
  886. var mediaSourceCount = video.MediaSourceCount;
  887. if (mediaSourceCount != 1)
  888. {
  889. dto.MediaSourceCount = mediaSourceCount;
  890. }
  891. }
  892. if (options.ContainsField(ItemFields.Chapters))
  893. {
  894. dto.Chapters = _itemRepo.GetChapters(item);
  895. }
  896. if (options.ContainsField(ItemFields.Trickplay))
  897. {
  898. dto.Trickplay = _trickplayManager.GetTrickplayManifest(item).GetAwaiter().GetResult();
  899. }
  900. if (video.ExtraType.HasValue)
  901. {
  902. dto.ExtraType = video.ExtraType.Value.ToString();
  903. }
  904. }
  905. if (options.ContainsField(ItemFields.MediaStreams))
  906. {
  907. // Add VideoInfo
  908. if (item is IHasMediaSources)
  909. {
  910. MediaStream[] mediaStreams;
  911. if (dto.MediaSources is not null && dto.MediaSources.Length > 0)
  912. {
  913. if (item.SourceType == SourceType.Channel)
  914. {
  915. mediaStreams = dto.MediaSources[0].MediaStreams.ToArray();
  916. }
  917. else
  918. {
  919. string id = item.Id.ToString("N", CultureInfo.InvariantCulture);
  920. mediaStreams = dto.MediaSources.Where(i => string.Equals(i.Id, id, StringComparison.OrdinalIgnoreCase))
  921. .SelectMany(i => i.MediaStreams)
  922. .ToArray();
  923. }
  924. }
  925. else
  926. {
  927. mediaStreams = _mediaSourceManager.GetStaticMediaSources(item, true)[0].MediaStreams.ToArray();
  928. }
  929. dto.MediaStreams = mediaStreams;
  930. }
  931. }
  932. BaseItem[] allExtras = null;
  933. if (options.ContainsField(ItemFields.SpecialFeatureCount))
  934. {
  935. allExtras = item.GetExtras().ToArray();
  936. dto.SpecialFeatureCount = allExtras.Count(i => i.ExtraType.HasValue && BaseItem.DisplayExtraTypes.Contains(i.ExtraType.Value));
  937. }
  938. if (options.ContainsField(ItemFields.LocalTrailerCount))
  939. {
  940. if (item is IHasTrailers hasTrailers)
  941. {
  942. dto.LocalTrailerCount = hasTrailers.LocalTrailers.Count;
  943. }
  944. else
  945. {
  946. dto.LocalTrailerCount = (allExtras ?? item.GetExtras()).Count(i => i.ExtraType == ExtraType.Trailer);
  947. }
  948. }
  949. // Add EpisodeInfo
  950. if (item is Episode episode)
  951. {
  952. dto.IndexNumberEnd = episode.IndexNumberEnd;
  953. dto.SeriesName = episode.SeriesName;
  954. if (options.ContainsField(ItemFields.SpecialEpisodeNumbers))
  955. {
  956. dto.AirsAfterSeasonNumber = episode.AirsAfterSeasonNumber;
  957. dto.AirsBeforeEpisodeNumber = episode.AirsBeforeEpisodeNumber;
  958. dto.AirsBeforeSeasonNumber = episode.AirsBeforeSeasonNumber;
  959. }
  960. dto.SeasonName = episode.SeasonName;
  961. dto.SeasonId = episode.SeasonId;
  962. dto.SeriesId = episode.SeriesId;
  963. Series episodeSeries = null;
  964. // this block will add the series poster for episodes without a poster
  965. // TODO maybe remove the if statement entirely
  966. // if (options.ContainsField(ItemFields.SeriesPrimaryImage))
  967. {
  968. episodeSeries ??= episode.Series;
  969. if (episodeSeries is not null)
  970. {
  971. dto.SeriesPrimaryImageTag = GetTagAndFillBlurhash(dto, episodeSeries, ImageType.Primary);
  972. if (dto.ImageTags is null || !dto.ImageTags.ContainsKey(ImageType.Primary))
  973. {
  974. AttachPrimaryImageAspectRatio(dto, episodeSeries);
  975. }
  976. }
  977. }
  978. if (options.ContainsField(ItemFields.SeriesStudio))
  979. {
  980. episodeSeries ??= episode.Series;
  981. if (episodeSeries is not null)
  982. {
  983. dto.SeriesStudio = episodeSeries.Studios.FirstOrDefault();
  984. }
  985. }
  986. }
  987. // Add SeriesInfo
  988. if (item is Series series)
  989. {
  990. dto.AirDays = series.AirDays;
  991. dto.AirTime = series.AirTime;
  992. dto.Status = series.Status?.ToString();
  993. }
  994. // Add SeasonInfo
  995. if (item is Season season)
  996. {
  997. dto.SeriesName = season.SeriesName;
  998. dto.SeriesId = season.SeriesId;
  999. series = null;
  1000. if (options.ContainsField(ItemFields.SeriesStudio))
  1001. {
  1002. series ??= season.Series;
  1003. if (series is not null)
  1004. {
  1005. dto.SeriesStudio = series.Studios.FirstOrDefault();
  1006. }
  1007. }
  1008. // this block will add the series poster for seasons without a poster
  1009. // TODO maybe remove the if statement entirely
  1010. // if (options.ContainsField(ItemFields.SeriesPrimaryImage))
  1011. {
  1012. series ??= season.Series;
  1013. if (series is not null)
  1014. {
  1015. dto.SeriesPrimaryImageTag = GetTagAndFillBlurhash(dto, series, ImageType.Primary);
  1016. if (dto.ImageTags is null || !dto.ImageTags.ContainsKey(ImageType.Primary))
  1017. {
  1018. AttachPrimaryImageAspectRatio(dto, series);
  1019. }
  1020. }
  1021. }
  1022. }
  1023. if (item is MusicVideo musicVideo)
  1024. {
  1025. SetMusicVideoProperties(dto, musicVideo);
  1026. }
  1027. if (item is Book book)
  1028. {
  1029. SetBookProperties(dto, book);
  1030. }
  1031. if (options.ContainsField(ItemFields.ProductionLocations))
  1032. {
  1033. if (item.ProductionLocations.Length > 0 || item is Movie)
  1034. {
  1035. dto.ProductionLocations = item.ProductionLocations;
  1036. }
  1037. }
  1038. if (options.ContainsField(ItemFields.Width))
  1039. {
  1040. var width = item.Width;
  1041. if (width > 0)
  1042. {
  1043. dto.Width = width;
  1044. }
  1045. }
  1046. if (options.ContainsField(ItemFields.Height))
  1047. {
  1048. var height = item.Height;
  1049. if (height > 0)
  1050. {
  1051. dto.Height = height;
  1052. }
  1053. }
  1054. if (options.ContainsField(ItemFields.IsHD))
  1055. {
  1056. // Compatibility
  1057. if (item.IsHD)
  1058. {
  1059. dto.IsHD = true;
  1060. }
  1061. }
  1062. if (item is Photo photo)
  1063. {
  1064. SetPhotoProperties(dto, photo);
  1065. }
  1066. dto.ChannelId = item.ChannelId;
  1067. if (item.SourceType == SourceType.Channel)
  1068. {
  1069. var channel = _libraryManager.GetItemById(item.ChannelId);
  1070. if (channel is not null)
  1071. {
  1072. dto.ChannelName = channel.Name;
  1073. }
  1074. }
  1075. }
  1076. private BaseItem GetImageDisplayParent(BaseItem currentItem, BaseItem originalItem)
  1077. {
  1078. if (currentItem is MusicAlbum musicAlbum)
  1079. {
  1080. var artist = musicAlbum.GetMusicArtist(new DtoOptions(false));
  1081. if (artist is not null)
  1082. {
  1083. return artist;
  1084. }
  1085. }
  1086. var parent = currentItem.DisplayParent ?? currentItem.GetOwner() ?? currentItem.GetParent();
  1087. if (parent is null && originalItem is not UserRootFolder && originalItem is not UserView && originalItem is not AggregateFolder && originalItem is not ICollectionFolder && originalItem is not Channel)
  1088. {
  1089. parent = _libraryManager.GetCollectionFolders(originalItem).FirstOrDefault();
  1090. }
  1091. return parent;
  1092. }
  1093. private void AddInheritedImages(BaseItemDto dto, BaseItem item, DtoOptions options, BaseItem owner)
  1094. {
  1095. if (!item.SupportsInheritedParentImages)
  1096. {
  1097. return;
  1098. }
  1099. var logoLimit = options.GetImageLimit(ImageType.Logo);
  1100. var artLimit = options.GetImageLimit(ImageType.Art);
  1101. var thumbLimit = options.GetImageLimit(ImageType.Thumb);
  1102. var backdropLimit = options.GetImageLimit(ImageType.Backdrop);
  1103. // For now. Emby apps are not using this
  1104. artLimit = 0;
  1105. if (logoLimit == 0 && artLimit == 0 && thumbLimit == 0 && backdropLimit == 0)
  1106. {
  1107. return;
  1108. }
  1109. BaseItem parent = null;
  1110. var isFirst = true;
  1111. var imageTags = dto.ImageTags;
  1112. while ((!(imageTags is not null && imageTags.ContainsKey(ImageType.Logo)) && logoLimit > 0)
  1113. || (!(imageTags is not null && imageTags.ContainsKey(ImageType.Art)) && artLimit > 0)
  1114. || (!(imageTags is not null && imageTags.ContainsKey(ImageType.Thumb)) && thumbLimit > 0)
  1115. || parent is Series)
  1116. {
  1117. parent ??= isFirst ? GetImageDisplayParent(item, item) ?? owner : parent;
  1118. if (parent is null)
  1119. {
  1120. break;
  1121. }
  1122. var allImages = parent.ImageInfos;
  1123. if (logoLimit > 0 && !(imageTags is not null && imageTags.ContainsKey(ImageType.Logo)) && dto.ParentLogoItemId is null)
  1124. {
  1125. var image = allImages.FirstOrDefault(i => i.Type == ImageType.Logo);
  1126. if (image is not null)
  1127. {
  1128. dto.ParentLogoItemId = parent.Id;
  1129. dto.ParentLogoImageTag = GetTagAndFillBlurhash(dto, parent, image);
  1130. }
  1131. }
  1132. if (artLimit > 0 && !(imageTags is not null && imageTags.ContainsKey(ImageType.Art)) && dto.ParentArtItemId is null)
  1133. {
  1134. var image = allImages.FirstOrDefault(i => i.Type == ImageType.Art);
  1135. if (image is not null)
  1136. {
  1137. dto.ParentArtItemId = parent.Id;
  1138. dto.ParentArtImageTag = GetTagAndFillBlurhash(dto, parent, image);
  1139. }
  1140. }
  1141. 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)
  1142. {
  1143. var image = allImages.FirstOrDefault(i => i.Type == ImageType.Thumb);
  1144. if (image is not null)
  1145. {
  1146. dto.ParentThumbItemId = parent.Id;
  1147. dto.ParentThumbImageTag = GetTagAndFillBlurhash(dto, parent, image);
  1148. }
  1149. }
  1150. if (backdropLimit > 0 && !((dto.BackdropImageTags is not null && dto.BackdropImageTags.Length > 0) || (dto.ParentBackdropImageTags is not null && dto.ParentBackdropImageTags.Length > 0)))
  1151. {
  1152. var images = allImages.Where(i => i.Type == ImageType.Backdrop).Take(backdropLimit).ToList();
  1153. if (images.Count > 0)
  1154. {
  1155. dto.ParentBackdropItemId = parent.Id;
  1156. dto.ParentBackdropImageTags = GetTagsAndFillBlurhashes(dto, parent, ImageType.Backdrop, images);
  1157. }
  1158. }
  1159. isFirst = false;
  1160. if (!parent.SupportsInheritedParentImages)
  1161. {
  1162. break;
  1163. }
  1164. parent = GetImageDisplayParent(parent, item);
  1165. }
  1166. }
  1167. private string GetMappedPath(BaseItem item, BaseItem ownerItem)
  1168. {
  1169. var path = item.Path;
  1170. if (item.IsFileProtocol)
  1171. {
  1172. path = _libraryManager.GetPathAfterNetworkSubstitution(path, ownerItem ?? item);
  1173. }
  1174. return path;
  1175. }
  1176. /// <summary>
  1177. /// Attaches the primary image aspect ratio.
  1178. /// </summary>
  1179. /// <param name="dto">The dto.</param>
  1180. /// <param name="item">The item.</param>
  1181. public void AttachPrimaryImageAspectRatio(IItemDto dto, BaseItem item)
  1182. {
  1183. dto.PrimaryImageAspectRatio = GetPrimaryImageAspectRatio(item);
  1184. }
  1185. public double? GetPrimaryImageAspectRatio(BaseItem item)
  1186. {
  1187. var imageInfo = item.GetImageInfo(ImageType.Primary, 0);
  1188. if (imageInfo is null)
  1189. {
  1190. return null;
  1191. }
  1192. if (!imageInfo.IsLocalFile)
  1193. {
  1194. return item.GetDefaultPrimaryImageAspectRatio();
  1195. }
  1196. try
  1197. {
  1198. var size = _imageProcessor.GetImageDimensions(item, imageInfo);
  1199. var width = size.Width;
  1200. var height = size.Height;
  1201. if (width > 0 && height > 0)
  1202. {
  1203. return (double)width / height;
  1204. }
  1205. }
  1206. catch (Exception ex)
  1207. {
  1208. _logger.LogError(ex, "Failed to determine primary image aspect ratio for {ImagePath}", imageInfo.Path);
  1209. }
  1210. return item.GetDefaultPrimaryImageAspectRatio();
  1211. }
  1212. }
  1213. }