DtoService.cs 50 KB

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