DtoService.cs 51 KB

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