DtoService.cs 50 KB

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