DtoService.cs 51 KB

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