DtoService.cs 49 KB

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