DtoService.cs 50 KB

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