DtoService.cs 51 KB

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