DtoService.cs 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481
  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="System.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="System.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. Person entity;
  555. if (dictionary.TryGetValue(person.Name, out entity))
  556. {
  557. baseItemPerson.PrimaryImageTag = GetImageCacheTag(entity, ImageType.Primary);
  558. baseItemPerson.Id = entity.Id.ToString("N");
  559. list.Add(baseItemPerson);
  560. }
  561. }
  562. dto.People = list.ToArray();
  563. }
  564. /// <summary>
  565. /// Attaches the studios.
  566. /// </summary>
  567. /// <param name="dto">The dto.</param>
  568. /// <param name="item">The item.</param>
  569. /// <returns>Task.</returns>
  570. private void AttachStudios(BaseItemDto dto, BaseItem item)
  571. {
  572. dto.Studios = item.Studios
  573. .Where(i => !string.IsNullOrEmpty(i))
  574. .Select(i => new NameGuidPair
  575. {
  576. Name = i,
  577. Id = _libraryManager.GetStudioId(i)
  578. })
  579. .ToArray();
  580. }
  581. private void AttachGenreItems(BaseItemDto dto, BaseItem item)
  582. {
  583. dto.GenreItems = item.Genres
  584. .Where(i => !string.IsNullOrEmpty(i))
  585. .Select(i => new NameGuidPair
  586. {
  587. Name = i,
  588. Id = GetGenreId(i, item)
  589. })
  590. .ToArray();
  591. }
  592. private Guid GetGenreId(string name, BaseItem owner)
  593. {
  594. if (owner is IHasMusicGenres)
  595. {
  596. return _libraryManager.GetMusicGenreId(name);
  597. }
  598. if (owner is Game || owner is GameSystem)
  599. {
  600. return _libraryManager.GetGameGenreId(name);
  601. }
  602. return _libraryManager.GetGenreId(name);
  603. }
  604. /// <summary>
  605. /// Sets simple property values on a DTOBaseItem
  606. /// </summary>
  607. /// <param name="dto">The dto.</param>
  608. /// <param name="item">The item.</param>
  609. /// <param name="owner">The owner.</param>
  610. /// <param name="options">The options.</param>
  611. private void AttachBasicFields(BaseItemDto dto, BaseItem item, BaseItem owner, DtoOptions options)
  612. {
  613. if (options.ContainsField(ItemFields.DateCreated))
  614. {
  615. dto.DateCreated = item.DateCreated;
  616. }
  617. if (options.ContainsField(ItemFields.Settings))
  618. {
  619. dto.LockedFields = item.LockedFields;
  620. dto.LockData = item.IsLocked;
  621. dto.ForcedSortName = item.ForcedSortName;
  622. }
  623. dto.Container = item.Container;
  624. dto.EndDate = item.EndDate;
  625. if (options.ContainsField(ItemFields.ExternalUrls))
  626. {
  627. dto.ExternalUrls = _providerManager.GetExternalUrls(item).ToArray();
  628. }
  629. if (options.ContainsField(ItemFields.Tags))
  630. {
  631. dto.Tags = item.Tags;
  632. }
  633. var hasAspectRatio = item as IHasAspectRatio;
  634. if (hasAspectRatio != null)
  635. {
  636. dto.AspectRatio = hasAspectRatio.AspectRatio;
  637. }
  638. var backdropLimit = options.GetImageLimit(ImageType.Backdrop);
  639. if (backdropLimit > 0)
  640. {
  641. dto.BackdropImageTags = GetImageTags(item, item.GetImages(ImageType.Backdrop).Take(backdropLimit).ToList());
  642. }
  643. if (options.ContainsField(ItemFields.ScreenshotImageTags))
  644. {
  645. var screenshotLimit = options.GetImageLimit(ImageType.Screenshot);
  646. if (screenshotLimit > 0)
  647. {
  648. dto.ScreenshotImageTags = GetImageTags(item, item.GetImages(ImageType.Screenshot).Take(screenshotLimit).ToList());
  649. }
  650. }
  651. if (options.ContainsField(ItemFields.Genres))
  652. {
  653. dto.Genres = item.Genres;
  654. AttachGenreItems(dto, item);
  655. }
  656. if (options.EnableImages)
  657. {
  658. dto.ImageTags = new Dictionary<ImageType, string>();
  659. // Prevent implicitly captured closure
  660. var currentItem = item;
  661. foreach (var image in currentItem.ImageInfos.Where(i => !currentItem.AllowsMultipleImages(i.Type))
  662. .ToList())
  663. {
  664. if (options.GetImageLimit(image.Type) > 0)
  665. {
  666. var tag = GetImageCacheTag(item, image);
  667. if (tag != null)
  668. {
  669. dto.ImageTags[image.Type] = tag;
  670. }
  671. }
  672. }
  673. }
  674. dto.Id = item.Id;
  675. dto.IndexNumber = item.IndexNumber;
  676. dto.ParentIndexNumber = item.ParentIndexNumber;
  677. if (item.IsFolder)
  678. {
  679. dto.IsFolder = true;
  680. }
  681. else if (item is IHasMediaSources)
  682. {
  683. dto.IsFolder = false;
  684. }
  685. dto.MediaType = item.MediaType;
  686. if (!(item is LiveTvProgram))
  687. {
  688. dto.LocationType = item.LocationType;
  689. }
  690. dto.Audio = item.Audio;
  691. if (options.ContainsField(ItemFields.Settings))
  692. {
  693. dto.PreferredMetadataCountryCode = item.PreferredMetadataCountryCode;
  694. dto.PreferredMetadataLanguage = item.PreferredMetadataLanguage;
  695. }
  696. dto.CriticRating = item.CriticRating;
  697. var hasDisplayOrder = item as IHasDisplayOrder;
  698. if (hasDisplayOrder != null)
  699. {
  700. dto.DisplayOrder = hasDisplayOrder.DisplayOrder;
  701. }
  702. var hasCollectionType = item as IHasCollectionType;
  703. if (hasCollectionType != null)
  704. {
  705. dto.CollectionType = hasCollectionType.CollectionType;
  706. }
  707. if (options.ContainsField(ItemFields.RemoteTrailers))
  708. {
  709. dto.RemoteTrailers = item.RemoteTrailers;
  710. }
  711. dto.Name = item.Name;
  712. dto.OfficialRating = item.OfficialRating;
  713. if (options.ContainsField(ItemFields.Overview))
  714. {
  715. dto.Overview = item.Overview;
  716. }
  717. if (options.ContainsField(ItemFields.OriginalTitle))
  718. {
  719. dto.OriginalTitle = item.OriginalTitle;
  720. }
  721. if (options.ContainsField(ItemFields.ParentId))
  722. {
  723. dto.ParentId = item.DisplayParentId;
  724. }
  725. AddInheritedImages(dto, item, options, owner);
  726. if (options.ContainsField(ItemFields.Path))
  727. {
  728. dto.Path = GetMappedPath(item, owner);
  729. }
  730. if (options.ContainsField(ItemFields.EnableMediaSourceDisplay))
  731. {
  732. dto.EnableMediaSourceDisplay = item.EnableMediaSourceDisplay;
  733. }
  734. dto.PremiereDate = item.PremiereDate;
  735. dto.ProductionYear = item.ProductionYear;
  736. if (options.ContainsField(ItemFields.ProviderIds))
  737. {
  738. dto.ProviderIds = item.ProviderIds;
  739. }
  740. dto.RunTimeTicks = item.RunTimeTicks;
  741. if (options.ContainsField(ItemFields.SortName))
  742. {
  743. dto.SortName = item.SortName;
  744. }
  745. if (options.ContainsField(ItemFields.CustomRating))
  746. {
  747. dto.CustomRating = item.CustomRating;
  748. }
  749. if (options.ContainsField(ItemFields.Taglines))
  750. {
  751. if (!string.IsNullOrEmpty(item.Tagline))
  752. {
  753. dto.Taglines = new string[] { item.Tagline };
  754. }
  755. if (dto.Taglines == null)
  756. {
  757. dto.Taglines = Array.Empty<string>();
  758. }
  759. }
  760. dto.Type = item.GetClientTypeName();
  761. if ((item.CommunityRating ?? 0) > 0)
  762. {
  763. dto.CommunityRating = item.CommunityRating;
  764. }
  765. var supportsPlaceHolders = item as ISupportsPlaceHolders;
  766. if (supportsPlaceHolders != null && supportsPlaceHolders.IsPlaceHolder)
  767. {
  768. dto.IsPlaceHolder = supportsPlaceHolders.IsPlaceHolder;
  769. }
  770. // Add audio info
  771. var audio = item as Audio;
  772. if (audio != null)
  773. {
  774. dto.Album = audio.Album;
  775. if (audio.ExtraType.HasValue)
  776. {
  777. dto.ExtraType = audio.ExtraType.Value.ToString();
  778. }
  779. var albumParent = audio.AlbumEntity;
  780. if (albumParent != null)
  781. {
  782. dto.AlbumId = albumParent.Id;
  783. dto.AlbumPrimaryImageTag = GetImageCacheTag(albumParent, ImageType.Primary);
  784. }
  785. //if (options.ContainsField(ItemFields.MediaSourceCount))
  786. //{
  787. // Songs always have one
  788. //}
  789. }
  790. var hasArtist = item as IHasArtist;
  791. if (hasArtist != null)
  792. {
  793. dto.Artists = hasArtist.Artists;
  794. //var artistItems = _libraryManager.GetArtists(new InternalItemsQuery
  795. //{
  796. // EnableTotalRecordCount = false,
  797. // ItemIds = new[] { item.Id.ToString("N") }
  798. //});
  799. //dto.ArtistItems = artistItems.Items
  800. // .Select(i =>
  801. // {
  802. // var artist = i.Item1;
  803. // return new NameIdPair
  804. // {
  805. // Name = artist.Name,
  806. // Id = artist.Id.ToString("N")
  807. // };
  808. // })
  809. // .ToList();
  810. // Include artists that are not in the database yet, e.g., just added via metadata editor
  811. //var foundArtists = artistItems.Items.Select(i => i.Item1.Name).ToList();
  812. dto.ArtistItems = hasArtist.Artists
  813. //.Except(foundArtists, new DistinctNameComparer())
  814. .Select(i =>
  815. {
  816. // This should not be necessary but we're seeing some cases of it
  817. if (string.IsNullOrEmpty(i))
  818. {
  819. return null;
  820. }
  821. var artist = _libraryManager.GetArtist(i, new DtoOptions(false)
  822. {
  823. EnableImages = false
  824. });
  825. if (artist != null)
  826. {
  827. return new NameGuidPair
  828. {
  829. Name = artist.Name,
  830. Id = artist.Id
  831. };
  832. }
  833. return null;
  834. }).Where(i => i != null).ToArray();
  835. }
  836. var hasAlbumArtist = item as IHasAlbumArtist;
  837. if (hasAlbumArtist != null)
  838. {
  839. dto.AlbumArtist = hasAlbumArtist.AlbumArtists.FirstOrDefault();
  840. //var artistItems = _libraryManager.GetAlbumArtists(new InternalItemsQuery
  841. //{
  842. // EnableTotalRecordCount = false,
  843. // ItemIds = new[] { item.Id.ToString("N") }
  844. //});
  845. //dto.AlbumArtists = artistItems.Items
  846. // .Select(i =>
  847. // {
  848. // var artist = i.Item1;
  849. // return new NameIdPair
  850. // {
  851. // Name = artist.Name,
  852. // Id = artist.Id.ToString("N")
  853. // };
  854. // })
  855. // .ToList();
  856. dto.AlbumArtists = hasAlbumArtist.AlbumArtists
  857. //.Except(foundArtists, new DistinctNameComparer())
  858. .Select(i =>
  859. {
  860. // This should not be necessary but we're seeing some cases of it
  861. if (string.IsNullOrEmpty(i))
  862. {
  863. return null;
  864. }
  865. var artist = _libraryManager.GetArtist(i, new DtoOptions(false)
  866. {
  867. EnableImages = false
  868. });
  869. if (artist != null)
  870. {
  871. return new NameGuidPair
  872. {
  873. Name = artist.Name,
  874. Id = artist.Id
  875. };
  876. }
  877. return null;
  878. }).Where(i => i != null).ToArray();
  879. }
  880. // Add video info
  881. var video = item as Video;
  882. if (video != null)
  883. {
  884. dto.VideoType = video.VideoType;
  885. dto.Video3DFormat = video.Video3DFormat;
  886. dto.IsoType = video.IsoType;
  887. if (video.HasSubtitles)
  888. {
  889. dto.HasSubtitles = video.HasSubtitles;
  890. }
  891. if (video.AdditionalParts.Length != 0)
  892. {
  893. dto.PartCount = video.AdditionalParts.Length + 1;
  894. }
  895. if (options.ContainsField(ItemFields.MediaSourceCount))
  896. {
  897. var mediaSourceCount = video.MediaSourceCount;
  898. if (mediaSourceCount != 1)
  899. {
  900. dto.MediaSourceCount = mediaSourceCount;
  901. }
  902. }
  903. if (options.ContainsField(ItemFields.Chapters))
  904. {
  905. dto.Chapters = _itemRepo.GetChapters(item);
  906. }
  907. if (video.ExtraType.HasValue)
  908. {
  909. dto.ExtraType = video.ExtraType.Value.ToString();
  910. }
  911. }
  912. if (options.ContainsField(ItemFields.MediaStreams))
  913. {
  914. // Add VideoInfo
  915. var iHasMediaSources = item as IHasMediaSources;
  916. if (iHasMediaSources != null)
  917. {
  918. MediaStream[] mediaStreams;
  919. if (dto.MediaSources != null && dto.MediaSources.Length > 0)
  920. {
  921. if (item.SourceType == SourceType.Channel)
  922. {
  923. mediaStreams = dto.MediaSources[0].MediaStreams.ToArray();
  924. }
  925. else
  926. {
  927. mediaStreams = dto.MediaSources.Where(i => string.Equals(i.Id, item.Id.ToString("N"), StringComparison.OrdinalIgnoreCase))
  928. .SelectMany(i => i.MediaStreams)
  929. .ToArray();
  930. }
  931. }
  932. else
  933. {
  934. mediaStreams = _mediaSourceManager().GetStaticMediaSources(item, true).First().MediaStreams.ToArray();
  935. }
  936. dto.MediaStreams = mediaStreams;
  937. }
  938. }
  939. BaseItem[] allExtras = null;
  940. if (options.ContainsField(ItemFields.SpecialFeatureCount))
  941. {
  942. if (allExtras == null)
  943. {
  944. allExtras = item.GetExtras().ToArray();
  945. }
  946. dto.SpecialFeatureCount = allExtras.Count(i => i.ExtraType.HasValue && BaseItem.DisplayExtraTypes.Contains(i.ExtraType.Value));
  947. }
  948. if (options.ContainsField(ItemFields.LocalTrailerCount))
  949. {
  950. if (allExtras == null)
  951. {
  952. allExtras = item.GetExtras().ToArray();
  953. }
  954. dto.LocalTrailerCount = allExtras.Count(i => i.ExtraType.HasValue && i.ExtraType.Value == ExtraType.Trailer);
  955. }
  956. // Add EpisodeInfo
  957. var episode = item as Episode;
  958. if (episode != null)
  959. {
  960. dto.IndexNumberEnd = episode.IndexNumberEnd;
  961. dto.SeriesName = episode.SeriesName;
  962. if (options.ContainsField(ItemFields.SpecialEpisodeNumbers))
  963. {
  964. dto.AirsAfterSeasonNumber = episode.AirsAfterSeasonNumber;
  965. dto.AirsBeforeEpisodeNumber = episode.AirsBeforeEpisodeNumber;
  966. dto.AirsBeforeSeasonNumber = episode.AirsBeforeSeasonNumber;
  967. }
  968. dto.SeasonName = episode.SeasonName;
  969. dto.SeasonId = episode.SeasonId;
  970. dto.SeriesId = episode.SeriesId;
  971. Series episodeSeries = null;
  972. //if (options.ContainsField(ItemFields.SeriesPrimaryImage))
  973. {
  974. episodeSeries = episodeSeries ?? episode.Series;
  975. if (episodeSeries != null)
  976. {
  977. dto.SeriesPrimaryImageTag = GetImageCacheTag(episodeSeries, ImageType.Primary);
  978. }
  979. }
  980. if (options.ContainsField(ItemFields.SeriesStudio))
  981. {
  982. episodeSeries = episodeSeries ?? episode.Series;
  983. if (episodeSeries != null)
  984. {
  985. dto.SeriesStudio = episodeSeries.Studios.FirstOrDefault();
  986. }
  987. }
  988. }
  989. // Add SeriesInfo
  990. var series = item as Series;
  991. if (series != null)
  992. {
  993. dto.AirDays = series.AirDays;
  994. dto.AirTime = series.AirTime;
  995. dto.Status = series.Status.HasValue ? series.Status.Value.ToString() : null;
  996. }
  997. // Add SeasonInfo
  998. var season = item as Season;
  999. if (season != null)
  1000. {
  1001. dto.SeriesName = season.SeriesName;
  1002. dto.SeriesId = season.SeriesId;
  1003. series = null;
  1004. if (options.ContainsField(ItemFields.SeriesStudio))
  1005. {
  1006. series = series ?? season.Series;
  1007. if (series != null)
  1008. {
  1009. dto.SeriesStudio = series.Studios.FirstOrDefault();
  1010. }
  1011. }
  1012. //if (options.ContainsField(ItemFields.SeriesPrimaryImage))
  1013. {
  1014. series = series ?? season.Series;
  1015. if (series != null)
  1016. {
  1017. dto.SeriesPrimaryImageTag = GetImageCacheTag(series, ImageType.Primary);
  1018. }
  1019. }
  1020. }
  1021. var game = item as Game;
  1022. if (game != null)
  1023. {
  1024. SetGameProperties(dto, game);
  1025. }
  1026. var gameSystem = item as GameSystem;
  1027. if (gameSystem != null)
  1028. {
  1029. SetGameSystemProperties(dto, gameSystem);
  1030. }
  1031. var musicVideo = item as MusicVideo;
  1032. if (musicVideo != null)
  1033. {
  1034. SetMusicVideoProperties(dto, musicVideo);
  1035. }
  1036. var book = item as Book;
  1037. if (book != null)
  1038. {
  1039. SetBookProperties(dto, book);
  1040. }
  1041. if (options.ContainsField(ItemFields.ProductionLocations))
  1042. {
  1043. if (item.ProductionLocations.Length > 0 || item is Movie)
  1044. {
  1045. dto.ProductionLocations = item.ProductionLocations;
  1046. }
  1047. }
  1048. if (options.ContainsField(ItemFields.Width))
  1049. {
  1050. var width = item.Width;
  1051. if (width > 0)
  1052. {
  1053. dto.Width = width;
  1054. }
  1055. }
  1056. if (options.ContainsField(ItemFields.Height))
  1057. {
  1058. var height = item.Height;
  1059. if (height > 0)
  1060. {
  1061. dto.Height = height;
  1062. }
  1063. }
  1064. if (options.ContainsField(ItemFields.IsHD))
  1065. {
  1066. // Compatibility
  1067. if (item.IsHD)
  1068. {
  1069. dto.IsHD = true;
  1070. }
  1071. }
  1072. var photo = item as Photo;
  1073. if (photo != null)
  1074. {
  1075. SetPhotoProperties(dto, photo);
  1076. }
  1077. dto.ChannelId = item.ChannelId;
  1078. if (item.SourceType == SourceType.Channel)
  1079. {
  1080. var channel = _libraryManager.GetItemById(item.ChannelId);
  1081. if (channel != null)
  1082. {
  1083. dto.ChannelName = channel.Name;
  1084. }
  1085. }
  1086. }
  1087. private BaseItem GetImageDisplayParent(BaseItem currentItem, BaseItem originalItem)
  1088. {
  1089. var musicAlbum = currentItem as MusicAlbum;
  1090. if (musicAlbum != null)
  1091. {
  1092. var artist = musicAlbum.GetMusicArtist(new DtoOptions(false));
  1093. if (artist != null)
  1094. {
  1095. return artist;
  1096. }
  1097. }
  1098. var parent = currentItem.DisplayParent ?? currentItem.GetOwner() ?? currentItem.GetParent();
  1099. if (parent == null && !(originalItem is UserRootFolder) && !(originalItem is UserView) && !(originalItem is AggregateFolder) && !(originalItem is ICollectionFolder) && !(originalItem is Channel))
  1100. {
  1101. parent = _libraryManager.GetCollectionFolders(originalItem).FirstOrDefault();
  1102. }
  1103. return parent;
  1104. }
  1105. private void AddInheritedImages(BaseItemDto dto, BaseItem item, DtoOptions options, BaseItem owner)
  1106. {
  1107. if (!item.SupportsInheritedParentImages)
  1108. {
  1109. return;
  1110. }
  1111. var logoLimit = options.GetImageLimit(ImageType.Logo);
  1112. var artLimit = options.GetImageLimit(ImageType.Art);
  1113. var thumbLimit = options.GetImageLimit(ImageType.Thumb);
  1114. var backdropLimit = options.GetImageLimit(ImageType.Backdrop);
  1115. // For now. Emby apps are not using this
  1116. artLimit = 0;
  1117. if (logoLimit == 0 && artLimit == 0 && thumbLimit == 0 && backdropLimit == 0)
  1118. {
  1119. return;
  1120. }
  1121. BaseItem parent = null;
  1122. var isFirst = true;
  1123. var imageTags = dto.ImageTags;
  1124. 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) &&
  1125. (parent = parent ?? (isFirst ? GetImageDisplayParent(item, item) ?? owner : parent)) != null)
  1126. {
  1127. if (parent == null)
  1128. {
  1129. break;
  1130. }
  1131. var allImages = parent.ImageInfos;
  1132. if (logoLimit > 0 && !(imageTags != null && imageTags.ContainsKey(ImageType.Logo)) && dto.ParentLogoItemId == null)
  1133. {
  1134. var image = allImages.FirstOrDefault(i => i.Type == ImageType.Logo);
  1135. if (image != null)
  1136. {
  1137. dto.ParentLogoItemId = GetDtoId(parent);
  1138. dto.ParentLogoImageTag = GetImageCacheTag(parent, image);
  1139. }
  1140. }
  1141. if (artLimit > 0 && !(imageTags != null && imageTags.ContainsKey(ImageType.Art)) && dto.ParentArtItemId == null)
  1142. {
  1143. var image = allImages.FirstOrDefault(i => i.Type == ImageType.Art);
  1144. if (image != null)
  1145. {
  1146. dto.ParentArtItemId = GetDtoId(parent);
  1147. dto.ParentArtImageTag = GetImageCacheTag(parent, image);
  1148. }
  1149. }
  1150. if (thumbLimit > 0 && !(imageTags != null && imageTags.ContainsKey(ImageType.Thumb)) && (dto.ParentThumbItemId == null || parent is Series) && !(parent is ICollectionFolder) && !(parent is UserView))
  1151. {
  1152. var image = allImages.FirstOrDefault(i => i.Type == ImageType.Thumb);
  1153. if (image != null)
  1154. {
  1155. dto.ParentThumbItemId = GetDtoId(parent);
  1156. dto.ParentThumbImageTag = GetImageCacheTag(parent, image);
  1157. }
  1158. }
  1159. if (backdropLimit > 0 && !((dto.BackdropImageTags != null && dto.BackdropImageTags.Length > 0) || (dto.ParentBackdropImageTags != null && dto.ParentBackdropImageTags.Length > 0)))
  1160. {
  1161. var images = allImages.Where(i => i.Type == ImageType.Backdrop).Take(backdropLimit).ToList();
  1162. if (images.Count > 0)
  1163. {
  1164. dto.ParentBackdropItemId = GetDtoId(parent);
  1165. dto.ParentBackdropImageTags = GetImageTags(parent, images);
  1166. }
  1167. }
  1168. isFirst = false;
  1169. if (!parent.SupportsInheritedParentImages)
  1170. {
  1171. break;
  1172. }
  1173. parent = GetImageDisplayParent(parent, item);
  1174. }
  1175. }
  1176. private string GetMappedPath(BaseItem item, BaseItem ownerItem)
  1177. {
  1178. var path = item.Path;
  1179. if (item.IsFileProtocol)
  1180. {
  1181. path = _libraryManager.GetPathAfterNetworkSubstitution(path, ownerItem ?? item);
  1182. }
  1183. return path;
  1184. }
  1185. /// <summary>
  1186. /// Attaches the primary image aspect ratio.
  1187. /// </summary>
  1188. /// <param name="dto">The dto.</param>
  1189. /// <param name="item">The item.</param>
  1190. /// <returns>Task.</returns>
  1191. public void AttachPrimaryImageAspectRatio(IItemDto dto, BaseItem item)
  1192. {
  1193. dto.PrimaryImageAspectRatio = GetPrimaryImageAspectRatio(item);
  1194. }
  1195. public double? GetPrimaryImageAspectRatio(BaseItem item)
  1196. {
  1197. var imageInfo = item.GetImageInfo(ImageType.Primary, 0);
  1198. if (imageInfo == null)
  1199. {
  1200. return null;
  1201. }
  1202. var supportedEnhancers = _imageProcessor.GetSupportedEnhancers(item, ImageType.Primary);
  1203. ImageSize size;
  1204. var defaultAspectRatio = item.GetDefaultPrimaryImageAspectRatio();
  1205. if (defaultAspectRatio > 0)
  1206. {
  1207. if (supportedEnhancers.Length == 0)
  1208. {
  1209. return defaultAspectRatio;
  1210. }
  1211. double dummyWidth = 200;
  1212. double dummyHeight = dummyWidth / defaultAspectRatio;
  1213. size = new ImageSize(dummyWidth, dummyHeight);
  1214. }
  1215. else
  1216. {
  1217. if (!imageInfo.IsLocalFile)
  1218. {
  1219. return null;
  1220. }
  1221. try
  1222. {
  1223. size = _imageProcessor.GetImageSize(item, imageInfo);
  1224. if (size.Width <= 0 || size.Height <= 0)
  1225. {
  1226. return null;
  1227. }
  1228. }
  1229. catch (Exception ex)
  1230. {
  1231. _logger.LogError(ex, "Failed to determine primary image aspect ratio for {0}", imageInfo.Path);
  1232. return null;
  1233. }
  1234. }
  1235. foreach (var enhancer in supportedEnhancers)
  1236. {
  1237. try
  1238. {
  1239. size = enhancer.GetEnhancedImageSize(item, ImageType.Primary, 0, size);
  1240. }
  1241. catch (Exception ex)
  1242. {
  1243. _logger.LogError(ex, "Error in image enhancer: {0}", enhancer.GetType().Name);
  1244. }
  1245. }
  1246. var width = size.Width;
  1247. var height = size.Height;
  1248. if (width.Equals(0) || height.Equals(0))
  1249. {
  1250. return null;
  1251. }
  1252. return width / height;
  1253. }
  1254. }
  1255. }