DtoService.cs 50 KB

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