DtoService.cs 49 KB

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