DtoService.cs 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492
  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 if (item is GameGenre)
  327. {
  328. dto.GameCount = taggedItems.Count(i => i is Game);
  329. }
  330. else
  331. {
  332. // This populates them all and covers Genre, Person, Studio, Year
  333. dto.ArtistCount = taggedItems.Count(i => i is MusicArtist);
  334. dto.AlbumCount = taggedItems.Count(i => i is MusicAlbum);
  335. dto.EpisodeCount = taggedItems.Count(i => i is Episode);
  336. dto.GameCount = taggedItems.Count(i => i is Game);
  337. dto.MovieCount = taggedItems.Count(i => i is Movie);
  338. dto.TrailerCount = taggedItems.Count(i => i is Trailer);
  339. dto.MusicVideoCount = taggedItems.Count(i => i is MusicVideo);
  340. dto.SeriesCount = taggedItems.Count(i => i is Series);
  341. dto.ProgramCount = taggedItems.Count(i => i is LiveTvProgram);
  342. dto.SongCount = taggedItems.Count(i => i is Audio);
  343. }
  344. dto.ChildCount = taggedItems.Count;
  345. }
  346. /// <summary>
  347. /// Attaches the user specific info.
  348. /// </summary>
  349. private void AttachUserSpecificInfo(BaseItemDto dto, BaseItem item, User user, DtoOptions options)
  350. {
  351. if (item.IsFolder)
  352. {
  353. var folder = (Folder)item;
  354. if (options.EnableUserData)
  355. {
  356. dto.UserData = _userDataRepository.GetUserDataDto(item, dto, user, options);
  357. }
  358. if (!dto.ChildCount.HasValue && item.SourceType == SourceType.Library)
  359. {
  360. // For these types we can try to optimize and assume these values will be equal
  361. if (item is MusicAlbum || item is Season || item is Playlist)
  362. {
  363. dto.ChildCount = dto.RecursiveItemCount;
  364. }
  365. if (options.ContainsField(ItemFields.ChildCount))
  366. {
  367. dto.ChildCount = dto.ChildCount ?? GetChildCount(folder, user);
  368. }
  369. }
  370. if (options.ContainsField(ItemFields.CumulativeRunTimeTicks))
  371. {
  372. dto.CumulativeRunTimeTicks = item.RunTimeTicks;
  373. }
  374. if (options.ContainsField(ItemFields.DateLastMediaAdded))
  375. {
  376. dto.DateLastMediaAdded = folder.DateLastMediaAdded;
  377. }
  378. }
  379. else
  380. {
  381. if (options.EnableUserData)
  382. {
  383. dto.UserData = _userDataRepository.GetUserDataDto(item, user);
  384. }
  385. }
  386. if (options.ContainsField(ItemFields.PlayAccess))
  387. {
  388. dto.PlayAccess = item.GetPlayAccess(user);
  389. }
  390. if (options.ContainsField(ItemFields.BasicSyncInfo))
  391. {
  392. var userCanSync = user != null && user.Policy.EnableContentDownloading;
  393. if (userCanSync && item.SupportsExternalTransfer)
  394. {
  395. dto.SupportsSync = true;
  396. }
  397. }
  398. }
  399. private static int GetChildCount(Folder folder, User user)
  400. {
  401. // Right now this is too slow to calculate for top level folders on a per-user basis
  402. // Just return something so that apps that are expecting a value won't think the folders are empty
  403. if (folder is ICollectionFolder || folder is UserView)
  404. {
  405. return new Random().Next(1, 10);
  406. }
  407. return folder.GetChildCount(user);
  408. }
  409. /// <summary>
  410. /// Gets client-side Id of a server-side BaseItem
  411. /// </summary>
  412. /// <param name="item">The item.</param>
  413. /// <returns>System.String.</returns>
  414. /// <exception cref="ArgumentNullException">item</exception>
  415. public string GetDtoId(BaseItem item)
  416. {
  417. return item.Id.ToString("N");
  418. }
  419. private static void SetBookProperties(BaseItemDto dto, Book item)
  420. {
  421. dto.SeriesName = item.SeriesName;
  422. }
  423. private static void SetPhotoProperties(BaseItemDto dto, Photo item)
  424. {
  425. dto.CameraMake = item.CameraMake;
  426. dto.CameraModel = item.CameraModel;
  427. dto.Software = item.Software;
  428. dto.ExposureTime = item.ExposureTime;
  429. dto.FocalLength = item.FocalLength;
  430. dto.ImageOrientation = item.Orientation;
  431. dto.Aperture = item.Aperture;
  432. dto.ShutterSpeed = item.ShutterSpeed;
  433. dto.Latitude = item.Latitude;
  434. dto.Longitude = item.Longitude;
  435. dto.Altitude = item.Altitude;
  436. dto.IsoSpeedRating = item.IsoSpeedRating;
  437. var album = item.AlbumEntity;
  438. if (album != null)
  439. {
  440. dto.Album = album.Name;
  441. dto.AlbumId = album.Id;
  442. }
  443. }
  444. private void SetMusicVideoProperties(BaseItemDto dto, MusicVideo item)
  445. {
  446. if (!string.IsNullOrEmpty(item.Album))
  447. {
  448. var parentAlbumIds = _libraryManager.GetItemIds(new InternalItemsQuery
  449. {
  450. IncludeItemTypes = new[] { typeof(MusicAlbum).Name },
  451. Name = item.Album,
  452. Limit = 1
  453. });
  454. if (parentAlbumIds.Count > 0)
  455. {
  456. dto.AlbumId = parentAlbumIds[0];
  457. }
  458. }
  459. dto.Album = item.Album;
  460. }
  461. private static void SetGameProperties(BaseItemDto dto, Game item)
  462. {
  463. dto.GameSystem = item.GameSystem;
  464. dto.MultiPartGameFiles = item.MultiPartGameFiles;
  465. }
  466. private static void SetGameSystemProperties(BaseItemDto dto, GameSystem item)
  467. {
  468. dto.GameSystem = item.GameSystemName;
  469. }
  470. private string[] GetImageTags(BaseItem item, List<ItemImageInfo> images)
  471. {
  472. return images
  473. .Select(p => GetImageCacheTag(item, p))
  474. .Where(i => i != null)
  475. .ToArray();
  476. }
  477. private string GetImageCacheTag(BaseItem item, ImageType type)
  478. {
  479. try
  480. {
  481. return _imageProcessor.GetImageCacheTag(item, type);
  482. }
  483. catch (Exception ex)
  484. {
  485. _logger.LogError(ex, "Error getting {type} image info", type);
  486. return null;
  487. }
  488. }
  489. private string GetImageCacheTag(BaseItem item, ItemImageInfo image)
  490. {
  491. try
  492. {
  493. return _imageProcessor.GetImageCacheTag(item, image);
  494. }
  495. catch (Exception ex)
  496. {
  497. _logger.LogError(ex, "Error getting {imageType} image info for {path}", image.Type, image.Path);
  498. return null;
  499. }
  500. }
  501. /// <summary>
  502. /// Attaches People DTO's to a DTOBaseItem
  503. /// </summary>
  504. /// <param name="dto">The dto.</param>
  505. /// <param name="item">The item.</param>
  506. /// <returns>Task.</returns>
  507. private void AttachPeople(BaseItemDto dto, BaseItem item)
  508. {
  509. // Ordering by person type to ensure actors and artists are at the front.
  510. // This is taking advantage of the fact that they both begin with A
  511. // This should be improved in the future
  512. var people = _libraryManager.GetPeople(item).OrderBy(i => i.SortOrder ?? int.MaxValue)
  513. .ThenBy(i =>
  514. {
  515. if (i.IsType(PersonType.Actor))
  516. {
  517. return 0;
  518. }
  519. if (i.IsType(PersonType.GuestStar))
  520. {
  521. return 1;
  522. }
  523. if (i.IsType(PersonType.Director))
  524. {
  525. return 2;
  526. }
  527. if (i.IsType(PersonType.Writer))
  528. {
  529. return 3;
  530. }
  531. if (i.IsType(PersonType.Producer))
  532. {
  533. return 4;
  534. }
  535. if (i.IsType(PersonType.Composer))
  536. {
  537. return 4;
  538. }
  539. return 10;
  540. })
  541. .ToList();
  542. var list = new List<BaseItemPerson>();
  543. var dictionary = people.Select(p => p.Name)
  544. .Distinct(StringComparer.OrdinalIgnoreCase).Select(c =>
  545. {
  546. try
  547. {
  548. return _libraryManager.GetPerson(c);
  549. }
  550. catch (Exception ex)
  551. {
  552. _logger.LogError(ex, "Error getting person {Name}", c);
  553. return null;
  554. }
  555. }).Where(i => i != null)
  556. .DistinctBy(i => i.Name, StringComparer.OrdinalIgnoreCase)
  557. .ToDictionary(i => i.Name, StringComparer.OrdinalIgnoreCase);
  558. for (var i = 0; i < people.Count; i++)
  559. {
  560. var person = people[i];
  561. var baseItemPerson = new BaseItemPerson
  562. {
  563. Name = person.Name,
  564. Role = person.Role,
  565. Type = person.Type
  566. };
  567. if (dictionary.TryGetValue(person.Name, out Person entity))
  568. {
  569. baseItemPerson.PrimaryImageTag = GetImageCacheTag(entity, ImageType.Primary);
  570. baseItemPerson.Id = entity.Id.ToString("N");
  571. list.Add(baseItemPerson);
  572. }
  573. }
  574. dto.People = list.ToArray();
  575. }
  576. /// <summary>
  577. /// Attaches the studios.
  578. /// </summary>
  579. /// <param name="dto">The dto.</param>
  580. /// <param name="item">The item.</param>
  581. /// <returns>Task.</returns>
  582. private void AttachStudios(BaseItemDto dto, BaseItem item)
  583. {
  584. dto.Studios = item.Studios
  585. .Where(i => !string.IsNullOrEmpty(i))
  586. .Select(i => new NameGuidPair
  587. {
  588. Name = i,
  589. Id = _libraryManager.GetStudioId(i)
  590. })
  591. .ToArray();
  592. }
  593. private void AttachGenreItems(BaseItemDto dto, BaseItem item)
  594. {
  595. dto.GenreItems = item.Genres
  596. .Where(i => !string.IsNullOrEmpty(i))
  597. .Select(i => new NameGuidPair
  598. {
  599. Name = i,
  600. Id = GetGenreId(i, item)
  601. })
  602. .ToArray();
  603. }
  604. private Guid GetGenreId(string name, BaseItem owner)
  605. {
  606. if (owner is IHasMusicGenres)
  607. {
  608. return _libraryManager.GetMusicGenreId(name);
  609. }
  610. if (owner is Game || owner is GameSystem)
  611. {
  612. return _libraryManager.GetGameGenreId(name);
  613. }
  614. return _libraryManager.GetGenreId(name);
  615. }
  616. /// <summary>
  617. /// Sets simple property values on a DTOBaseItem
  618. /// </summary>
  619. /// <param name="dto">The dto.</param>
  620. /// <param name="item">The item.</param>
  621. /// <param name="owner">The owner.</param>
  622. /// <param name="options">The options.</param>
  623. private void AttachBasicFields(BaseItemDto dto, BaseItem item, BaseItem owner, DtoOptions options)
  624. {
  625. if (options.ContainsField(ItemFields.DateCreated))
  626. {
  627. dto.DateCreated = item.DateCreated;
  628. }
  629. if (options.ContainsField(ItemFields.Settings))
  630. {
  631. dto.LockedFields = item.LockedFields;
  632. dto.LockData = item.IsLocked;
  633. dto.ForcedSortName = item.ForcedSortName;
  634. }
  635. dto.Container = item.Container;
  636. dto.EndDate = item.EndDate;
  637. if (options.ContainsField(ItemFields.ExternalUrls))
  638. {
  639. dto.ExternalUrls = _providerManager.GetExternalUrls(item).ToArray();
  640. }
  641. if (options.ContainsField(ItemFields.Tags))
  642. {
  643. dto.Tags = item.Tags;
  644. }
  645. var hasAspectRatio = item as IHasAspectRatio;
  646. if (hasAspectRatio != null)
  647. {
  648. dto.AspectRatio = hasAspectRatio.AspectRatio;
  649. }
  650. var backdropLimit = options.GetImageLimit(ImageType.Backdrop);
  651. if (backdropLimit > 0)
  652. {
  653. dto.BackdropImageTags = GetImageTags(item, item.GetImages(ImageType.Backdrop).Take(backdropLimit).ToList());
  654. }
  655. if (options.ContainsField(ItemFields.ScreenshotImageTags))
  656. {
  657. var screenshotLimit = options.GetImageLimit(ImageType.Screenshot);
  658. if (screenshotLimit > 0)
  659. {
  660. dto.ScreenshotImageTags = GetImageTags(item, item.GetImages(ImageType.Screenshot).Take(screenshotLimit).ToList());
  661. }
  662. }
  663. if (options.ContainsField(ItemFields.Genres))
  664. {
  665. dto.Genres = item.Genres;
  666. AttachGenreItems(dto, item);
  667. }
  668. if (options.EnableImages)
  669. {
  670. dto.ImageTags = new Dictionary<ImageType, string>();
  671. // Prevent implicitly captured closure
  672. var currentItem = item;
  673. foreach (var image in currentItem.ImageInfos.Where(i => !currentItem.AllowsMultipleImages(i.Type))
  674. .ToList())
  675. {
  676. if (options.GetImageLimit(image.Type) > 0)
  677. {
  678. var tag = GetImageCacheTag(item, image);
  679. if (tag != null)
  680. {
  681. dto.ImageTags[image.Type] = tag;
  682. }
  683. }
  684. }
  685. }
  686. dto.Id = item.Id;
  687. dto.IndexNumber = item.IndexNumber;
  688. dto.ParentIndexNumber = item.ParentIndexNumber;
  689. if (item.IsFolder)
  690. {
  691. dto.IsFolder = true;
  692. }
  693. else if (item is IHasMediaSources)
  694. {
  695. dto.IsFolder = false;
  696. }
  697. dto.MediaType = item.MediaType;
  698. if (!(item is LiveTvProgram))
  699. {
  700. dto.LocationType = item.LocationType;
  701. }
  702. dto.Audio = item.Audio;
  703. if (options.ContainsField(ItemFields.Settings))
  704. {
  705. dto.PreferredMetadataCountryCode = item.PreferredMetadataCountryCode;
  706. dto.PreferredMetadataLanguage = item.PreferredMetadataLanguage;
  707. }
  708. dto.CriticRating = item.CriticRating;
  709. var hasDisplayOrder = item as IHasDisplayOrder;
  710. if (hasDisplayOrder != null)
  711. {
  712. dto.DisplayOrder = hasDisplayOrder.DisplayOrder;
  713. }
  714. var hasCollectionType = item as IHasCollectionType;
  715. if (hasCollectionType != null)
  716. {
  717. dto.CollectionType = hasCollectionType.CollectionType;
  718. }
  719. if (options.ContainsField(ItemFields.RemoteTrailers))
  720. {
  721. dto.RemoteTrailers = item.RemoteTrailers;
  722. }
  723. dto.Name = item.Name;
  724. dto.OfficialRating = item.OfficialRating;
  725. if (options.ContainsField(ItemFields.Overview))
  726. {
  727. dto.Overview = item.Overview;
  728. }
  729. if (options.ContainsField(ItemFields.OriginalTitle))
  730. {
  731. dto.OriginalTitle = item.OriginalTitle;
  732. }
  733. if (options.ContainsField(ItemFields.ParentId))
  734. {
  735. dto.ParentId = item.DisplayParentId;
  736. }
  737. AddInheritedImages(dto, item, options, owner);
  738. if (options.ContainsField(ItemFields.Path))
  739. {
  740. dto.Path = GetMappedPath(item, owner);
  741. }
  742. if (options.ContainsField(ItemFields.EnableMediaSourceDisplay))
  743. {
  744. dto.EnableMediaSourceDisplay = item.EnableMediaSourceDisplay;
  745. }
  746. dto.PremiereDate = item.PremiereDate;
  747. dto.ProductionYear = item.ProductionYear;
  748. if (options.ContainsField(ItemFields.ProviderIds))
  749. {
  750. dto.ProviderIds = item.ProviderIds;
  751. }
  752. dto.RunTimeTicks = item.RunTimeTicks;
  753. if (options.ContainsField(ItemFields.SortName))
  754. {
  755. dto.SortName = item.SortName;
  756. }
  757. if (options.ContainsField(ItemFields.CustomRating))
  758. {
  759. dto.CustomRating = item.CustomRating;
  760. }
  761. if (options.ContainsField(ItemFields.Taglines))
  762. {
  763. if (!string.IsNullOrEmpty(item.Tagline))
  764. {
  765. dto.Taglines = new string[] { item.Tagline };
  766. }
  767. if (dto.Taglines == null)
  768. {
  769. dto.Taglines = Array.Empty<string>();
  770. }
  771. }
  772. dto.Type = item.GetClientTypeName();
  773. if ((item.CommunityRating ?? 0) > 0)
  774. {
  775. dto.CommunityRating = item.CommunityRating;
  776. }
  777. var supportsPlaceHolders = item as ISupportsPlaceHolders;
  778. if (supportsPlaceHolders != null && supportsPlaceHolders.IsPlaceHolder)
  779. {
  780. dto.IsPlaceHolder = supportsPlaceHolders.IsPlaceHolder;
  781. }
  782. // Add audio info
  783. var audio = item as Audio;
  784. if (audio != null)
  785. {
  786. dto.Album = audio.Album;
  787. if (audio.ExtraType.HasValue)
  788. {
  789. dto.ExtraType = audio.ExtraType.Value.ToString();
  790. }
  791. var albumParent = audio.AlbumEntity;
  792. if (albumParent != null)
  793. {
  794. dto.AlbumId = albumParent.Id;
  795. dto.AlbumPrimaryImageTag = GetImageCacheTag(albumParent, ImageType.Primary);
  796. }
  797. //if (options.ContainsField(ItemFields.MediaSourceCount))
  798. //{
  799. // Songs always have one
  800. //}
  801. }
  802. var hasArtist = item as IHasArtist;
  803. if (hasArtist != null)
  804. {
  805. dto.Artists = hasArtist.Artists;
  806. //var artistItems = _libraryManager.GetArtists(new InternalItemsQuery
  807. //{
  808. // EnableTotalRecordCount = false,
  809. // ItemIds = new[] { item.Id.ToString("N") }
  810. //});
  811. //dto.ArtistItems = artistItems.Items
  812. // .Select(i =>
  813. // {
  814. // var artist = i.Item1;
  815. // return new NameIdPair
  816. // {
  817. // Name = artist.Name,
  818. // Id = artist.Id.ToString("N")
  819. // };
  820. // })
  821. // .ToList();
  822. // Include artists that are not in the database yet, e.g., just added via metadata editor
  823. //var foundArtists = artistItems.Items.Select(i => i.Item1.Name).ToList();
  824. dto.ArtistItems = hasArtist.Artists
  825. //.Except(foundArtists, new DistinctNameComparer())
  826. .Select(i =>
  827. {
  828. // This should not be necessary but we're seeing some cases of it
  829. if (string.IsNullOrEmpty(i))
  830. {
  831. return null;
  832. }
  833. var artist = _libraryManager.GetArtist(i, new DtoOptions(false)
  834. {
  835. EnableImages = false
  836. });
  837. if (artist != null)
  838. {
  839. return new NameGuidPair
  840. {
  841. Name = artist.Name,
  842. Id = artist.Id
  843. };
  844. }
  845. return null;
  846. }).Where(i => i != null).ToArray();
  847. }
  848. var hasAlbumArtist = item as IHasAlbumArtist;
  849. if (hasAlbumArtist != null)
  850. {
  851. dto.AlbumArtist = hasAlbumArtist.AlbumArtists.FirstOrDefault();
  852. //var artistItems = _libraryManager.GetAlbumArtists(new InternalItemsQuery
  853. //{
  854. // EnableTotalRecordCount = false,
  855. // ItemIds = new[] { item.Id.ToString("N") }
  856. //});
  857. //dto.AlbumArtists = artistItems.Items
  858. // .Select(i =>
  859. // {
  860. // var artist = i.Item1;
  861. // return new NameIdPair
  862. // {
  863. // Name = artist.Name,
  864. // Id = artist.Id.ToString("N")
  865. // };
  866. // })
  867. // .ToList();
  868. dto.AlbumArtists = hasAlbumArtist.AlbumArtists
  869. //.Except(foundArtists, new DistinctNameComparer())
  870. .Select(i =>
  871. {
  872. // This should not be necessary but we're seeing some cases of it
  873. if (string.IsNullOrEmpty(i))
  874. {
  875. return null;
  876. }
  877. var artist = _libraryManager.GetArtist(i, new DtoOptions(false)
  878. {
  879. EnableImages = false
  880. });
  881. if (artist != null)
  882. {
  883. return new NameGuidPair
  884. {
  885. Name = artist.Name,
  886. Id = artist.Id
  887. };
  888. }
  889. return null;
  890. }).Where(i => i != null).ToArray();
  891. }
  892. // Add video info
  893. var video = item as Video;
  894. if (video != null)
  895. {
  896. dto.VideoType = video.VideoType;
  897. dto.Video3DFormat = video.Video3DFormat;
  898. dto.IsoType = video.IsoType;
  899. if (video.HasSubtitles)
  900. {
  901. dto.HasSubtitles = video.HasSubtitles;
  902. }
  903. if (video.AdditionalParts.Length != 0)
  904. {
  905. dto.PartCount = video.AdditionalParts.Length + 1;
  906. }
  907. if (options.ContainsField(ItemFields.MediaSourceCount))
  908. {
  909. var mediaSourceCount = video.MediaSourceCount;
  910. if (mediaSourceCount != 1)
  911. {
  912. dto.MediaSourceCount = mediaSourceCount;
  913. }
  914. }
  915. if (options.ContainsField(ItemFields.Chapters))
  916. {
  917. dto.Chapters = _itemRepo.GetChapters(item);
  918. }
  919. if (video.ExtraType.HasValue)
  920. {
  921. dto.ExtraType = video.ExtraType.Value.ToString();
  922. }
  923. }
  924. if (options.ContainsField(ItemFields.MediaStreams))
  925. {
  926. // Add VideoInfo
  927. var iHasMediaSources = item as IHasMediaSources;
  928. if (iHasMediaSources != null)
  929. {
  930. MediaStream[] mediaStreams;
  931. if (dto.MediaSources != null && dto.MediaSources.Length > 0)
  932. {
  933. if (item.SourceType == SourceType.Channel)
  934. {
  935. mediaStreams = dto.MediaSources[0].MediaStreams.ToArray();
  936. }
  937. else
  938. {
  939. mediaStreams = dto.MediaSources.Where(i => string.Equals(i.Id, item.Id.ToString("N"), StringComparison.OrdinalIgnoreCase))
  940. .SelectMany(i => i.MediaStreams)
  941. .ToArray();
  942. }
  943. }
  944. else
  945. {
  946. mediaStreams = _mediaSourceManager().GetStaticMediaSources(item, true).First().MediaStreams.ToArray();
  947. }
  948. dto.MediaStreams = mediaStreams;
  949. }
  950. }
  951. BaseItem[] allExtras = null;
  952. if (options.ContainsField(ItemFields.SpecialFeatureCount))
  953. {
  954. if (allExtras == null)
  955. {
  956. allExtras = item.GetExtras().ToArray();
  957. }
  958. dto.SpecialFeatureCount = allExtras.Count(i => i.ExtraType.HasValue && BaseItem.DisplayExtraTypes.Contains(i.ExtraType.Value));
  959. }
  960. if (options.ContainsField(ItemFields.LocalTrailerCount))
  961. {
  962. if (allExtras == null)
  963. {
  964. allExtras = item.GetExtras().ToArray();
  965. }
  966. dto.LocalTrailerCount = allExtras.Count(i => i.ExtraType.HasValue && i.ExtraType.Value == ExtraType.Trailer);
  967. }
  968. // Add EpisodeInfo
  969. var episode = item as Episode;
  970. if (episode != null)
  971. {
  972. dto.IndexNumberEnd = episode.IndexNumberEnd;
  973. dto.SeriesName = episode.SeriesName;
  974. if (options.ContainsField(ItemFields.SpecialEpisodeNumbers))
  975. {
  976. dto.AirsAfterSeasonNumber = episode.AirsAfterSeasonNumber;
  977. dto.AirsBeforeEpisodeNumber = episode.AirsBeforeEpisodeNumber;
  978. dto.AirsBeforeSeasonNumber = episode.AirsBeforeSeasonNumber;
  979. }
  980. dto.SeasonName = episode.SeasonName;
  981. dto.SeasonId = episode.SeasonId;
  982. dto.SeriesId = episode.SeriesId;
  983. Series episodeSeries = null;
  984. //if (options.ContainsField(ItemFields.SeriesPrimaryImage))
  985. {
  986. episodeSeries = episodeSeries ?? episode.Series;
  987. if (episodeSeries != null)
  988. {
  989. dto.SeriesPrimaryImageTag = GetImageCacheTag(episodeSeries, ImageType.Primary);
  990. }
  991. }
  992. if (options.ContainsField(ItemFields.SeriesStudio))
  993. {
  994. episodeSeries = episodeSeries ?? episode.Series;
  995. if (episodeSeries != null)
  996. {
  997. dto.SeriesStudio = episodeSeries.Studios.FirstOrDefault();
  998. }
  999. }
  1000. }
  1001. // Add SeriesInfo
  1002. var series = item as Series;
  1003. if (series != null)
  1004. {
  1005. dto.AirDays = series.AirDays;
  1006. dto.AirTime = series.AirTime;
  1007. dto.Status = series.Status.HasValue ? series.Status.Value.ToString() : null;
  1008. }
  1009. // Add SeasonInfo
  1010. var season = item as Season;
  1011. if (season != null)
  1012. {
  1013. dto.SeriesName = season.SeriesName;
  1014. dto.SeriesId = season.SeriesId;
  1015. series = null;
  1016. if (options.ContainsField(ItemFields.SeriesStudio))
  1017. {
  1018. series = series ?? season.Series;
  1019. if (series != null)
  1020. {
  1021. dto.SeriesStudio = series.Studios.FirstOrDefault();
  1022. }
  1023. }
  1024. //if (options.ContainsField(ItemFields.SeriesPrimaryImage))
  1025. {
  1026. series = series ?? season.Series;
  1027. if (series != null)
  1028. {
  1029. dto.SeriesPrimaryImageTag = GetImageCacheTag(series, ImageType.Primary);
  1030. }
  1031. }
  1032. }
  1033. var game = item as Game;
  1034. if (game != null)
  1035. {
  1036. SetGameProperties(dto, game);
  1037. }
  1038. var gameSystem = item as GameSystem;
  1039. if (gameSystem != null)
  1040. {
  1041. SetGameSystemProperties(dto, gameSystem);
  1042. }
  1043. var musicVideo = item as MusicVideo;
  1044. if (musicVideo != null)
  1045. {
  1046. SetMusicVideoProperties(dto, musicVideo);
  1047. }
  1048. var book = item as Book;
  1049. if (book != null)
  1050. {
  1051. SetBookProperties(dto, book);
  1052. }
  1053. if (options.ContainsField(ItemFields.ProductionLocations))
  1054. {
  1055. if (item.ProductionLocations.Length > 0 || item is Movie)
  1056. {
  1057. dto.ProductionLocations = item.ProductionLocations;
  1058. }
  1059. }
  1060. if (options.ContainsField(ItemFields.Width))
  1061. {
  1062. var width = item.Width;
  1063. if (width > 0)
  1064. {
  1065. dto.Width = width;
  1066. }
  1067. }
  1068. if (options.ContainsField(ItemFields.Height))
  1069. {
  1070. var height = item.Height;
  1071. if (height > 0)
  1072. {
  1073. dto.Height = height;
  1074. }
  1075. }
  1076. if (options.ContainsField(ItemFields.IsHD))
  1077. {
  1078. // Compatibility
  1079. if (item.IsHD)
  1080. {
  1081. dto.IsHD = true;
  1082. }
  1083. }
  1084. var photo = item as Photo;
  1085. if (photo != null)
  1086. {
  1087. SetPhotoProperties(dto, photo);
  1088. }
  1089. dto.ChannelId = item.ChannelId;
  1090. if (item.SourceType == SourceType.Channel)
  1091. {
  1092. var channel = _libraryManager.GetItemById(item.ChannelId);
  1093. if (channel != null)
  1094. {
  1095. dto.ChannelName = channel.Name;
  1096. }
  1097. }
  1098. }
  1099. private BaseItem GetImageDisplayParent(BaseItem currentItem, BaseItem originalItem)
  1100. {
  1101. var musicAlbum = currentItem as MusicAlbum;
  1102. if (musicAlbum != null)
  1103. {
  1104. var artist = musicAlbum.GetMusicArtist(new DtoOptions(false));
  1105. if (artist != null)
  1106. {
  1107. return artist;
  1108. }
  1109. }
  1110. var parent = currentItem.DisplayParent ?? currentItem.GetOwner() ?? currentItem.GetParent();
  1111. if (parent == null && !(originalItem is UserRootFolder) && !(originalItem is UserView) && !(originalItem is AggregateFolder) && !(originalItem is ICollectionFolder) && !(originalItem is Channel))
  1112. {
  1113. parent = _libraryManager.GetCollectionFolders(originalItem).FirstOrDefault();
  1114. }
  1115. return parent;
  1116. }
  1117. private void AddInheritedImages(BaseItemDto dto, BaseItem item, DtoOptions options, BaseItem owner)
  1118. {
  1119. if (!item.SupportsInheritedParentImages)
  1120. {
  1121. return;
  1122. }
  1123. var logoLimit = options.GetImageLimit(ImageType.Logo);
  1124. var artLimit = options.GetImageLimit(ImageType.Art);
  1125. var thumbLimit = options.GetImageLimit(ImageType.Thumb);
  1126. var backdropLimit = options.GetImageLimit(ImageType.Backdrop);
  1127. // For now. Emby apps are not using this
  1128. artLimit = 0;
  1129. if (logoLimit == 0 && artLimit == 0 && thumbLimit == 0 && backdropLimit == 0)
  1130. {
  1131. return;
  1132. }
  1133. BaseItem parent = null;
  1134. var isFirst = true;
  1135. var imageTags = dto.ImageTags;
  1136. 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) &&
  1137. (parent = parent ?? (isFirst ? GetImageDisplayParent(item, item) ?? owner : parent)) != null)
  1138. {
  1139. if (parent == null)
  1140. {
  1141. break;
  1142. }
  1143. var allImages = parent.ImageInfos;
  1144. if (logoLimit > 0 && !(imageTags != null && imageTags.ContainsKey(ImageType.Logo)) && dto.ParentLogoItemId == null)
  1145. {
  1146. var image = allImages.FirstOrDefault(i => i.Type == ImageType.Logo);
  1147. if (image != null)
  1148. {
  1149. dto.ParentLogoItemId = GetDtoId(parent);
  1150. dto.ParentLogoImageTag = GetImageCacheTag(parent, image);
  1151. }
  1152. }
  1153. if (artLimit > 0 && !(imageTags != null && imageTags.ContainsKey(ImageType.Art)) && dto.ParentArtItemId == null)
  1154. {
  1155. var image = allImages.FirstOrDefault(i => i.Type == ImageType.Art);
  1156. if (image != null)
  1157. {
  1158. dto.ParentArtItemId = GetDtoId(parent);
  1159. dto.ParentArtImageTag = GetImageCacheTag(parent, image);
  1160. }
  1161. }
  1162. if (thumbLimit > 0 && !(imageTags != null && imageTags.ContainsKey(ImageType.Thumb)) && (dto.ParentThumbItemId == null || parent is Series) && !(parent is ICollectionFolder) && !(parent is UserView))
  1163. {
  1164. var image = allImages.FirstOrDefault(i => i.Type == ImageType.Thumb);
  1165. if (image != null)
  1166. {
  1167. dto.ParentThumbItemId = GetDtoId(parent);
  1168. dto.ParentThumbImageTag = GetImageCacheTag(parent, image);
  1169. }
  1170. }
  1171. if (backdropLimit > 0 && !((dto.BackdropImageTags != null && dto.BackdropImageTags.Length > 0) || (dto.ParentBackdropImageTags != null && dto.ParentBackdropImageTags.Length > 0)))
  1172. {
  1173. var images = allImages.Where(i => i.Type == ImageType.Backdrop).Take(backdropLimit).ToList();
  1174. if (images.Count > 0)
  1175. {
  1176. dto.ParentBackdropItemId = GetDtoId(parent);
  1177. dto.ParentBackdropImageTags = GetImageTags(parent, images);
  1178. }
  1179. }
  1180. isFirst = false;
  1181. if (!parent.SupportsInheritedParentImages)
  1182. {
  1183. break;
  1184. }
  1185. parent = GetImageDisplayParent(parent, item);
  1186. }
  1187. }
  1188. private string GetMappedPath(BaseItem item, BaseItem ownerItem)
  1189. {
  1190. var path = item.Path;
  1191. if (item.IsFileProtocol)
  1192. {
  1193. path = _libraryManager.GetPathAfterNetworkSubstitution(path, ownerItem ?? item);
  1194. }
  1195. return path;
  1196. }
  1197. /// <summary>
  1198. /// Attaches the primary image aspect ratio.
  1199. /// </summary>
  1200. /// <param name="dto">The dto.</param>
  1201. /// <param name="item">The item.</param>
  1202. /// <returns>Task.</returns>
  1203. public void AttachPrimaryImageAspectRatio(IItemDto dto, BaseItem item)
  1204. {
  1205. dto.PrimaryImageAspectRatio = GetPrimaryImageAspectRatio(item);
  1206. }
  1207. public double? GetPrimaryImageAspectRatio(BaseItem item)
  1208. {
  1209. var imageInfo = item.GetImageInfo(ImageType.Primary, 0);
  1210. if (imageInfo == null)
  1211. {
  1212. return null;
  1213. }
  1214. var supportedEnhancers = _imageProcessor.GetSupportedEnhancers(item, ImageType.Primary);
  1215. ImageSize size;
  1216. var defaultAspectRatio = item.GetDefaultPrimaryImageAspectRatio();
  1217. if (defaultAspectRatio > 0)
  1218. {
  1219. if (supportedEnhancers.Length == 0)
  1220. {
  1221. return defaultAspectRatio;
  1222. }
  1223. double dummyWidth = 200;
  1224. double dummyHeight = dummyWidth / defaultAspectRatio;
  1225. size = new ImageSize(dummyWidth, dummyHeight);
  1226. }
  1227. else
  1228. {
  1229. if (!imageInfo.IsLocalFile)
  1230. {
  1231. return null;
  1232. }
  1233. try
  1234. {
  1235. size = _imageProcessor.GetImageSize(item, imageInfo);
  1236. if (size.Width <= 0 || size.Height <= 0)
  1237. {
  1238. return null;
  1239. }
  1240. }
  1241. catch (Exception ex)
  1242. {
  1243. _logger.LogError(ex, "Failed to determine primary image aspect ratio for {0}", imageInfo.Path);
  1244. return null;
  1245. }
  1246. }
  1247. foreach (var enhancer in supportedEnhancers)
  1248. {
  1249. try
  1250. {
  1251. size = enhancer.GetEnhancedImageSize(item, ImageType.Primary, 0, size);
  1252. }
  1253. catch (Exception ex)
  1254. {
  1255. _logger.LogError(ex, "Error in image enhancer: {0}", enhancer.GetType().Name);
  1256. }
  1257. }
  1258. var width = size.Width;
  1259. var height = size.Height;
  1260. if (width.Equals(0) || height.Equals(0))
  1261. {
  1262. return null;
  1263. }
  1264. return width / height;
  1265. }
  1266. }
  1267. }