DtoService.cs 49 KB

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