DtoService.cs 50 KB

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