DtoService.cs 50 KB

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