DtoService.cs 50 KB

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