DtoService.cs 51 KB

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