DtoService.cs 49 KB

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