DtoService.cs 50 KB

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