DtoService.cs 50 KB

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