DtoService.cs 50 KB

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