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