DtoService.cs 51 KB

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