DtoService.cs 51 KB

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