DtoService.cs 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437
  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(new[] { ',' });
  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[] { typeof(MusicAlbum).Name },
  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. }
  971. }
  972. if (options.ContainsField(ItemFields.SeriesStudio))
  973. {
  974. episodeSeries = episodeSeries ?? episode.Series;
  975. if (episodeSeries != null)
  976. {
  977. dto.SeriesStudio = episodeSeries.Studios.FirstOrDefault();
  978. }
  979. }
  980. }
  981. // Add SeriesInfo
  982. if (item is Series series)
  983. {
  984. dto.AirDays = series.AirDays;
  985. dto.AirTime = series.AirTime;
  986. dto.Status = series.Status.HasValue ? series.Status.Value.ToString() : null;
  987. }
  988. // Add SeasonInfo
  989. if (item is Season season)
  990. {
  991. dto.SeriesName = season.SeriesName;
  992. dto.SeriesId = season.SeriesId;
  993. series = null;
  994. if (options.ContainsField(ItemFields.SeriesStudio))
  995. {
  996. series = series ?? season.Series;
  997. if (series != null)
  998. {
  999. dto.SeriesStudio = series.Studios.FirstOrDefault();
  1000. }
  1001. }
  1002. // this block will add the series poster for seasons without a poster
  1003. // TODO maybe remove the if statement entirely
  1004. // if (options.ContainsField(ItemFields.SeriesPrimaryImage))
  1005. {
  1006. series = series ?? season.Series;
  1007. if (series != null)
  1008. {
  1009. dto.SeriesPrimaryImageTag = GetTagAndFillBlurhash(dto, series, ImageType.Primary);
  1010. }
  1011. }
  1012. }
  1013. if (item is MusicVideo musicVideo)
  1014. {
  1015. SetMusicVideoProperties(dto, musicVideo);
  1016. }
  1017. if (item is Book book)
  1018. {
  1019. SetBookProperties(dto, book);
  1020. }
  1021. if (options.ContainsField(ItemFields.ProductionLocations))
  1022. {
  1023. if (item.ProductionLocations.Length > 0 || item is Movie)
  1024. {
  1025. dto.ProductionLocations = item.ProductionLocations;
  1026. }
  1027. }
  1028. if (options.ContainsField(ItemFields.Width))
  1029. {
  1030. var width = item.Width;
  1031. if (width > 0)
  1032. {
  1033. dto.Width = width;
  1034. }
  1035. }
  1036. if (options.ContainsField(ItemFields.Height))
  1037. {
  1038. var height = item.Height;
  1039. if (height > 0)
  1040. {
  1041. dto.Height = height;
  1042. }
  1043. }
  1044. if (options.ContainsField(ItemFields.IsHD))
  1045. {
  1046. // Compatibility
  1047. if (item.IsHD)
  1048. {
  1049. dto.IsHD = true;
  1050. }
  1051. }
  1052. if (item is Photo photo)
  1053. {
  1054. SetPhotoProperties(dto, photo);
  1055. }
  1056. dto.ChannelId = item.ChannelId;
  1057. if (item.SourceType == SourceType.Channel)
  1058. {
  1059. var channel = _libraryManager.GetItemById(item.ChannelId);
  1060. if (channel != null)
  1061. {
  1062. dto.ChannelName = channel.Name;
  1063. }
  1064. }
  1065. }
  1066. private BaseItem GetImageDisplayParent(BaseItem currentItem, BaseItem originalItem)
  1067. {
  1068. if (currentItem is MusicAlbum musicAlbum)
  1069. {
  1070. var artist = musicAlbum.GetMusicArtist(new DtoOptions(false));
  1071. if (artist != null)
  1072. {
  1073. return artist;
  1074. }
  1075. }
  1076. var parent = currentItem.DisplayParent ?? currentItem.GetOwner() ?? currentItem.GetParent();
  1077. if (parent == null && !(originalItem is UserRootFolder) && !(originalItem is UserView) && !(originalItem is AggregateFolder) && !(originalItem is ICollectionFolder) && !(originalItem is Channel))
  1078. {
  1079. parent = _libraryManager.GetCollectionFolders(originalItem).FirstOrDefault();
  1080. }
  1081. return parent;
  1082. }
  1083. private void AddInheritedImages(BaseItemDto dto, BaseItem item, DtoOptions options, BaseItem owner)
  1084. {
  1085. if (!item.SupportsInheritedParentImages)
  1086. {
  1087. return;
  1088. }
  1089. var logoLimit = options.GetImageLimit(ImageType.Logo);
  1090. var artLimit = options.GetImageLimit(ImageType.Art);
  1091. var thumbLimit = options.GetImageLimit(ImageType.Thumb);
  1092. var backdropLimit = options.GetImageLimit(ImageType.Backdrop);
  1093. // For now. Emby apps are not using this
  1094. artLimit = 0;
  1095. if (logoLimit == 0 && artLimit == 0 && thumbLimit == 0 && backdropLimit == 0)
  1096. {
  1097. return;
  1098. }
  1099. BaseItem parent = null;
  1100. var isFirst = true;
  1101. var imageTags = dto.ImageTags;
  1102. 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) &&
  1103. (parent = parent ?? (isFirst ? GetImageDisplayParent(item, item) ?? owner : parent)) != null)
  1104. {
  1105. if (parent == null)
  1106. {
  1107. break;
  1108. }
  1109. var allImages = parent.ImageInfos;
  1110. if (logoLimit > 0 && !(imageTags != null && imageTags.ContainsKey(ImageType.Logo)) && dto.ParentLogoItemId == null)
  1111. {
  1112. var image = allImages.FirstOrDefault(i => i.Type == ImageType.Logo);
  1113. if (image != null)
  1114. {
  1115. dto.ParentLogoItemId = GetDtoId(parent);
  1116. dto.ParentLogoImageTag = GetTagAndFillBlurhash(dto, parent, image);
  1117. }
  1118. }
  1119. if (artLimit > 0 && !(imageTags != null && imageTags.ContainsKey(ImageType.Art)) && dto.ParentArtItemId == null)
  1120. {
  1121. var image = allImages.FirstOrDefault(i => i.Type == ImageType.Art);
  1122. if (image != null)
  1123. {
  1124. dto.ParentArtItemId = GetDtoId(parent);
  1125. dto.ParentArtImageTag = GetTagAndFillBlurhash(dto, parent, image);
  1126. }
  1127. }
  1128. if (thumbLimit > 0 && !(imageTags != null && imageTags.ContainsKey(ImageType.Thumb)) && (dto.ParentThumbItemId == null || parent is Series) && !(parent is ICollectionFolder) && !(parent is UserView))
  1129. {
  1130. var image = allImages.FirstOrDefault(i => i.Type == ImageType.Thumb);
  1131. if (image != null)
  1132. {
  1133. dto.ParentThumbItemId = GetDtoId(parent);
  1134. dto.ParentThumbImageTag = GetTagAndFillBlurhash(dto, parent, image);
  1135. }
  1136. }
  1137. if (backdropLimit > 0 && !((dto.BackdropImageTags != null && dto.BackdropImageTags.Length > 0) || (dto.ParentBackdropImageTags != null && dto.ParentBackdropImageTags.Length > 0)))
  1138. {
  1139. var images = allImages.Where(i => i.Type == ImageType.Backdrop).Take(backdropLimit).ToList();
  1140. if (images.Count > 0)
  1141. {
  1142. dto.ParentBackdropItemId = GetDtoId(parent);
  1143. dto.ParentBackdropImageTags = GetTagsAndFillBlurhashes(dto, parent, ImageType.Backdrop, images);
  1144. }
  1145. }
  1146. isFirst = false;
  1147. if (!parent.SupportsInheritedParentImages)
  1148. {
  1149. break;
  1150. }
  1151. parent = GetImageDisplayParent(parent, item);
  1152. }
  1153. }
  1154. private string GetMappedPath(BaseItem item, BaseItem ownerItem)
  1155. {
  1156. var path = item.Path;
  1157. if (item.IsFileProtocol)
  1158. {
  1159. path = _libraryManager.GetPathAfterNetworkSubstitution(path, ownerItem ?? item);
  1160. }
  1161. return path;
  1162. }
  1163. /// <summary>
  1164. /// Attaches the primary image aspect ratio.
  1165. /// </summary>
  1166. /// <param name="dto">The dto.</param>
  1167. /// <param name="item">The item.</param>
  1168. /// <returns>Task.</returns>
  1169. public void AttachPrimaryImageAspectRatio(IItemDto dto, BaseItem item)
  1170. {
  1171. dto.PrimaryImageAspectRatio = GetPrimaryImageAspectRatio(item);
  1172. }
  1173. public double? GetPrimaryImageAspectRatio(BaseItem item)
  1174. {
  1175. var imageInfo = item.GetImageInfo(ImageType.Primary, 0);
  1176. if (imageInfo == null)
  1177. {
  1178. return null;
  1179. }
  1180. ImageDimensions size;
  1181. var defaultAspectRatio = item.GetDefaultPrimaryImageAspectRatio();
  1182. if (defaultAspectRatio > 0)
  1183. {
  1184. return defaultAspectRatio;
  1185. }
  1186. if (!imageInfo.IsLocalFile)
  1187. {
  1188. return null;
  1189. }
  1190. try
  1191. {
  1192. size = _imageProcessor.GetImageDimensions(item, imageInfo);
  1193. if (size.Width <= 0 || size.Height <= 0)
  1194. {
  1195. return null;
  1196. }
  1197. }
  1198. catch (Exception ex)
  1199. {
  1200. _logger.LogError(ex, "Failed to determine primary image aspect ratio for {0}", imageInfo.Path);
  1201. return null;
  1202. }
  1203. var width = size.Width;
  1204. var height = size.Height;
  1205. if (width <= 0 || height <= 0)
  1206. {
  1207. return null;
  1208. }
  1209. return width / height;
  1210. }
  1211. }
  1212. }