DtoService.cs 50 KB

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