DtoService.cs 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442
  1. using MediaBrowser.Common.Extensions;
  2. using MediaBrowser.Common.IO;
  3. using MediaBrowser.Controller.Channels;
  4. using MediaBrowser.Controller.Configuration;
  5. using MediaBrowser.Controller.Drawing;
  6. using MediaBrowser.Controller.Dto;
  7. using MediaBrowser.Controller.Entities;
  8. using MediaBrowser.Controller.Entities.Audio;
  9. using MediaBrowser.Controller.Entities.Movies;
  10. using MediaBrowser.Controller.Entities.TV;
  11. using MediaBrowser.Controller.Library;
  12. using MediaBrowser.Controller.LiveTv;
  13. using MediaBrowser.Controller.Persistence;
  14. using MediaBrowser.Controller.Playlists;
  15. using MediaBrowser.Controller.Providers;
  16. using MediaBrowser.Controller.Sync;
  17. using MediaBrowser.Model.Drawing;
  18. using MediaBrowser.Model.Dto;
  19. using MediaBrowser.Model.Entities;
  20. using MediaBrowser.Model.Logging;
  21. using MediaBrowser.Model.Querying;
  22. using MoreLinq;
  23. using System;
  24. using System.Collections.Generic;
  25. using System.IO;
  26. using System.Linq;
  27. namespace MediaBrowser.Server.Implementations.Dto
  28. {
  29. public class DtoService : IDtoService
  30. {
  31. private readonly ILogger _logger;
  32. private readonly ILibraryManager _libraryManager;
  33. private readonly IUserDataManager _userDataRepository;
  34. private readonly IItemRepository _itemRepo;
  35. private readonly IImageProcessor _imageProcessor;
  36. private readonly IServerConfigurationManager _config;
  37. private readonly IFileSystem _fileSystem;
  38. private readonly IProviderManager _providerManager;
  39. private readonly Func<IChannelManager> _channelManagerFactory;
  40. private readonly ISyncManager _syncManager;
  41. public DtoService(ILogger logger, ILibraryManager libraryManager, IUserDataManager userDataRepository, IItemRepository itemRepo, IImageProcessor imageProcessor, IServerConfigurationManager config, IFileSystem fileSystem, IProviderManager providerManager, Func<IChannelManager> channelManagerFactory, ISyncManager syncManager)
  42. {
  43. _logger = logger;
  44. _libraryManager = libraryManager;
  45. _userDataRepository = userDataRepository;
  46. _itemRepo = itemRepo;
  47. _imageProcessor = imageProcessor;
  48. _config = config;
  49. _fileSystem = fileSystem;
  50. _providerManager = providerManager;
  51. _channelManagerFactory = channelManagerFactory;
  52. _syncManager = syncManager;
  53. }
  54. /// <summary>
  55. /// Converts a BaseItem to a DTOBaseItem
  56. /// </summary>
  57. /// <param name="item">The item.</param>
  58. /// <param name="fields">The fields.</param>
  59. /// <param name="user">The user.</param>
  60. /// <param name="owner">The owner.</param>
  61. /// <returns>Task{DtoBaseItem}.</returns>
  62. /// <exception cref="System.ArgumentNullException">item</exception>
  63. public BaseItemDto GetBaseItemDto(BaseItem item, List<ItemFields> fields, User user = null, BaseItem owner = null)
  64. {
  65. var dto = GetBaseItemDtoInternal(item, fields, user, owner);
  66. var byName = item as IItemByName;
  67. if (byName != null && !(item is LiveTvChannel))
  68. {
  69. IEnumerable<BaseItem> libraryItems;
  70. var artist = item as MusicArtist;
  71. if (artist == null || artist.IsAccessedByName)
  72. {
  73. libraryItems = user != null ?
  74. user.RootFolder.GetRecursiveChildren(user) :
  75. _libraryManager.RootFolder.RecursiveChildren;
  76. }
  77. else
  78. {
  79. libraryItems = user != null ?
  80. artist.GetRecursiveChildren(user) :
  81. artist.RecursiveChildren;
  82. }
  83. SetItemByNameInfo(item, dto, byName.GetTaggedItems(libraryItems).ToList(), user);
  84. return dto;
  85. }
  86. return dto;
  87. }
  88. private BaseItemDto GetBaseItemDtoInternal(BaseItem item, List<ItemFields> fields, User user = null, BaseItem owner = null)
  89. {
  90. if (item == null)
  91. {
  92. throw new ArgumentNullException("item");
  93. }
  94. if (fields == null)
  95. {
  96. throw new ArgumentNullException("fields");
  97. }
  98. var dto = new BaseItemDto();
  99. dto.SupportsPlaylists = item.SupportsAddingToPlaylist;
  100. if (fields.Contains(ItemFields.People))
  101. {
  102. AttachPeople(dto, item);
  103. }
  104. if (fields.Contains(ItemFields.PrimaryImageAspectRatio))
  105. {
  106. try
  107. {
  108. AttachPrimaryImageAspectRatio(dto, item);
  109. }
  110. catch (Exception ex)
  111. {
  112. // Have to use a catch-all unfortunately because some .net image methods throw plain Exceptions
  113. _logger.ErrorException("Error generating PrimaryImageAspectRatio for {0}", ex, item.Name);
  114. }
  115. }
  116. if (fields.Contains(ItemFields.DisplayPreferencesId))
  117. {
  118. dto.DisplayPreferencesId = item.DisplayPreferencesId.ToString("N");
  119. }
  120. if (user != null)
  121. {
  122. AttachUserSpecificInfo(dto, item, user, fields);
  123. }
  124. var hasMediaSources = item as IHasMediaSources;
  125. if (hasMediaSources != null)
  126. {
  127. if (fields.Contains(ItemFields.MediaSources))
  128. {
  129. if (user == null)
  130. {
  131. dto.MediaSources = hasMediaSources.GetMediaSources(true).ToList();
  132. }
  133. else
  134. {
  135. dto.MediaSources = hasMediaSources.GetMediaSources(true, user).ToList();
  136. }
  137. }
  138. }
  139. if (fields.Contains(ItemFields.Studios))
  140. {
  141. AttachStudios(dto, item);
  142. }
  143. AttachBasicFields(dto, item, owner, fields);
  144. if (fields.Contains(ItemFields.SyncInfo))
  145. {
  146. dto.SupportsSync = _syncManager.SupportsSync(item);
  147. }
  148. if (fields.Contains(ItemFields.SoundtrackIds))
  149. {
  150. var hasSoundtracks = item as IHasSoundtracks;
  151. if (hasSoundtracks != null)
  152. {
  153. dto.SoundtrackIds = hasSoundtracks.SoundtrackIds
  154. .Select(i => i.ToString("N"))
  155. .ToArray();
  156. }
  157. }
  158. if (item is Playlist)
  159. {
  160. AttachLinkedChildImages(dto, (Folder)item, user);
  161. }
  162. return dto;
  163. }
  164. public BaseItemDto GetItemByNameDto<T>(T item, List<ItemFields> fields, List<BaseItem> taggedItems, User user = null)
  165. where T : BaseItem, IItemByName
  166. {
  167. var dto = GetBaseItemDtoInternal(item, fields, user);
  168. SetItemByNameInfo(item, dto, taggedItems, user);
  169. return dto;
  170. }
  171. private void SetItemByNameInfo(BaseItem item, BaseItemDto dto, List<BaseItem> taggedItems, User user = null)
  172. {
  173. if (item is MusicArtist || item is MusicGenre)
  174. {
  175. dto.AlbumCount = taggedItems.Count(i => i is MusicAlbum);
  176. dto.MusicVideoCount = taggedItems.Count(i => i is MusicVideo);
  177. dto.SongCount = taggedItems.Count(i => i is Audio);
  178. }
  179. else if (item is GameGenre)
  180. {
  181. dto.GameCount = taggedItems.Count(i => i is Game);
  182. }
  183. else
  184. {
  185. // This populates them all and covers Genre, Person, Studio, Year
  186. dto.AdultVideoCount = taggedItems.Count(i => i is AdultVideo);
  187. dto.AlbumCount = taggedItems.Count(i => i is MusicAlbum);
  188. dto.EpisodeCount = taggedItems.Count(i => i is Episode);
  189. dto.GameCount = taggedItems.Count(i => i is Game);
  190. dto.MovieCount = taggedItems.Count(i => i is Movie);
  191. dto.MusicVideoCount = taggedItems.Count(i => i is MusicVideo);
  192. dto.SeriesCount = taggedItems.Count(i => i is Series);
  193. dto.SongCount = taggedItems.Count(i => i is Audio);
  194. dto.TrailerCount = taggedItems.Count(i => i is Trailer);
  195. }
  196. dto.ChildCount = taggedItems.Count;
  197. }
  198. /// <summary>
  199. /// Attaches the user specific info.
  200. /// </summary>
  201. /// <param name="dto">The dto.</param>
  202. /// <param name="item">The item.</param>
  203. /// <param name="user">The user.</param>
  204. /// <param name="fields">The fields.</param>
  205. private void AttachUserSpecificInfo(BaseItemDto dto, BaseItem item, User user, List<ItemFields> fields)
  206. {
  207. if (item.IsFolder)
  208. {
  209. var userData = _userDataRepository.GetUserData(user.Id, item.GetUserDataKey());
  210. // Skip the user data manager because we've already looped through the recursive tree and don't want to do it twice
  211. // TODO: Improve in future
  212. dto.UserData = GetUserItemDataDto(userData);
  213. var folder = (Folder)item;
  214. dto.ChildCount = GetChildCount(folder, user);
  215. if (!(folder is UserRootFolder))
  216. {
  217. SetSpecialCounts(folder, user, dto, fields);
  218. }
  219. dto.UserData.Played = dto.PlayedPercentage.HasValue && dto.PlayedPercentage.Value >= 100;
  220. dto.UserData.PlayedPercentage = dto.PlayedPercentage;
  221. dto.UserData.UnplayedItemCount = dto.RecursiveUnplayedItemCount;
  222. }
  223. else
  224. {
  225. dto.UserData = _userDataRepository.GetUserDataDto(item, user);
  226. }
  227. dto.PlayAccess = item.GetPlayAccess(user);
  228. }
  229. private int GetChildCount(Folder folder, User user)
  230. {
  231. return folder.GetChildren(user, true)
  232. .Count();
  233. }
  234. public UserDto GetUserDto(User user)
  235. {
  236. if (user == null)
  237. {
  238. throw new ArgumentNullException("user");
  239. }
  240. var dto = new UserDto
  241. {
  242. Id = user.Id.ToString("N"),
  243. Name = user.Name,
  244. HasPassword = !String.IsNullOrEmpty(user.Password),
  245. LastActivityDate = user.LastActivityDate,
  246. LastLoginDate = user.LastLoginDate,
  247. Configuration = user.Configuration
  248. };
  249. var image = user.GetImageInfo(ImageType.Primary, 0);
  250. if (image != null)
  251. {
  252. dto.PrimaryImageTag = GetImageCacheTag(user, image);
  253. try
  254. {
  255. AttachPrimaryImageAspectRatio(dto, user);
  256. }
  257. catch (Exception ex)
  258. {
  259. // Have to use a catch-all unfortunately because some .net image methods throw plain Exceptions
  260. _logger.ErrorException("Error generating PrimaryImageAspectRatio for {0}", ex, user.Name);
  261. }
  262. }
  263. return dto;
  264. }
  265. /// <summary>
  266. /// Gets client-side Id of a server-side BaseItem
  267. /// </summary>
  268. /// <param name="item">The item.</param>
  269. /// <returns>System.String.</returns>
  270. /// <exception cref="System.ArgumentNullException">item</exception>
  271. public string GetDtoId(BaseItem item)
  272. {
  273. if (item == null)
  274. {
  275. throw new ArgumentNullException("item");
  276. }
  277. return item.Id.ToString("N");
  278. }
  279. /// <summary>
  280. /// Converts a UserItemData to a DTOUserItemData
  281. /// </summary>
  282. /// <param name="data">The data.</param>
  283. /// <returns>DtoUserItemData.</returns>
  284. /// <exception cref="System.ArgumentNullException"></exception>
  285. public UserItemDataDto GetUserItemDataDto(UserItemData data)
  286. {
  287. if (data == null)
  288. {
  289. throw new ArgumentNullException("data");
  290. }
  291. return new UserItemDataDto
  292. {
  293. IsFavorite = data.IsFavorite,
  294. Likes = data.Likes,
  295. PlaybackPositionTicks = data.PlaybackPositionTicks,
  296. PlayCount = data.PlayCount,
  297. Rating = data.Rating,
  298. Played = data.Played,
  299. LastPlayedDate = data.LastPlayedDate,
  300. Key = data.Key
  301. };
  302. }
  303. private void SetBookProperties(BaseItemDto dto, Book item)
  304. {
  305. dto.SeriesName = item.SeriesName;
  306. }
  307. private void SetMusicVideoProperties(BaseItemDto dto, MusicVideo item)
  308. {
  309. if (!string.IsNullOrEmpty(item.Album))
  310. {
  311. var parentAlbum = _libraryManager.RootFolder
  312. .GetRecursiveChildren()
  313. .Where(i => i is MusicAlbum)
  314. .FirstOrDefault(i => string.Equals(i.Name, item.Album, StringComparison.OrdinalIgnoreCase));
  315. if (parentAlbum != null)
  316. {
  317. dto.AlbumId = GetDtoId(parentAlbum);
  318. }
  319. }
  320. dto.Album = item.Album;
  321. dto.Artists = string.IsNullOrEmpty(item.Artist) ? new List<string>() : new List<string> { item.Artist };
  322. }
  323. private void SetGameProperties(BaseItemDto dto, Game item)
  324. {
  325. dto.Players = item.PlayersSupported;
  326. dto.GameSystem = item.GameSystem;
  327. dto.MultiPartGameFiles = item.MultiPartGameFiles;
  328. }
  329. private void SetGameSystemProperties(BaseItemDto dto, GameSystem item)
  330. {
  331. dto.GameSystem = item.GameSystemName;
  332. }
  333. /// <summary>
  334. /// Gets the backdrop image tags.
  335. /// </summary>
  336. /// <param name="item">The item.</param>
  337. /// <returns>List{System.String}.</returns>
  338. private List<string> GetBackdropImageTags(BaseItem item)
  339. {
  340. return GetCacheTags(item, ImageType.Backdrop).ToList();
  341. }
  342. /// <summary>
  343. /// Gets the screenshot image tags.
  344. /// </summary>
  345. /// <param name="item">The item.</param>
  346. /// <returns>List{Guid}.</returns>
  347. private List<string> GetScreenshotImageTags(BaseItem item)
  348. {
  349. var hasScreenshots = item as IHasScreenshots;
  350. if (hasScreenshots == null)
  351. {
  352. return new List<string>();
  353. }
  354. return GetCacheTags(item, ImageType.Screenshot).ToList();
  355. }
  356. private IEnumerable<string> GetCacheTags(BaseItem item, ImageType type)
  357. {
  358. return item.GetImages(type)
  359. .Select(p => GetImageCacheTag(item, p))
  360. .Where(i => i != null)
  361. .ToList();
  362. }
  363. private string GetImageCacheTag(BaseItem item, ImageType type)
  364. {
  365. try
  366. {
  367. return _imageProcessor.GetImageCacheTag(item, type);
  368. }
  369. catch (Exception ex)
  370. {
  371. _logger.ErrorException("Error getting {0} image info", ex, type);
  372. return null;
  373. }
  374. }
  375. private string GetImageCacheTag(BaseItem item, ItemImageInfo image)
  376. {
  377. try
  378. {
  379. return _imageProcessor.GetImageCacheTag(item, image);
  380. }
  381. catch (Exception ex)
  382. {
  383. _logger.ErrorException("Error getting {0} image info for {1}", ex, image.Type, image.Path);
  384. return null;
  385. }
  386. }
  387. /// <summary>
  388. /// Attaches People DTO's to a DTOBaseItem
  389. /// </summary>
  390. /// <param name="dto">The dto.</param>
  391. /// <param name="item">The item.</param>
  392. /// <returns>Task.</returns>
  393. private void AttachPeople(BaseItemDto dto, BaseItem item)
  394. {
  395. // Ordering by person type to ensure actors and artists are at the front.
  396. // This is taking advantage of the fact that they both begin with A
  397. // This should be improved in the future
  398. var people = item.People.OrderBy(i => i.SortOrder ?? int.MaxValue)
  399. .ThenBy(i =>
  400. {
  401. if (i.IsType(PersonType.Actor))
  402. {
  403. return 0;
  404. }
  405. if (i.IsType(PersonType.GuestStar))
  406. {
  407. return 1;
  408. }
  409. if (i.IsType(PersonType.Director))
  410. {
  411. return 2;
  412. }
  413. if (i.IsType(PersonType.Writer))
  414. {
  415. return 3;
  416. }
  417. if (i.IsType(PersonType.Producer))
  418. {
  419. return 4;
  420. }
  421. if (i.IsType(PersonType.Composer))
  422. {
  423. return 4;
  424. }
  425. return 10;
  426. })
  427. .ToList();
  428. // Attach People by transforming them into BaseItemPerson (DTO)
  429. dto.People = new BaseItemPerson[people.Count];
  430. var dictionary = people.Select(p => p.Name)
  431. .Distinct(StringComparer.OrdinalIgnoreCase).Select(c =>
  432. {
  433. try
  434. {
  435. return _libraryManager.GetPerson(c);
  436. }
  437. catch (IOException ex)
  438. {
  439. _logger.ErrorException("Error getting person {0}", ex, c);
  440. return null;
  441. }
  442. }).Where(i => i != null)
  443. .DistinctBy(i => i.Name)
  444. .ToDictionary(i => i.Name, StringComparer.OrdinalIgnoreCase);
  445. for (var i = 0; i < people.Count; i++)
  446. {
  447. var person = people[i];
  448. var baseItemPerson = new BaseItemPerson
  449. {
  450. Name = person.Name,
  451. Role = person.Role,
  452. Type = person.Type
  453. };
  454. Person entity;
  455. if (dictionary.TryGetValue(person.Name, out entity))
  456. {
  457. baseItemPerson.PrimaryImageTag = GetImageCacheTag(entity, ImageType.Primary);
  458. baseItemPerson.Id = entity.Id.ToString("N");
  459. }
  460. dto.People[i] = baseItemPerson;
  461. }
  462. }
  463. /// <summary>
  464. /// Attaches the studios.
  465. /// </summary>
  466. /// <param name="dto">The dto.</param>
  467. /// <param name="item">The item.</param>
  468. /// <returns>Task.</returns>
  469. private void AttachStudios(BaseItemDto dto, BaseItem item)
  470. {
  471. var studios = item.Studios.ToList();
  472. dto.Studios = new StudioDto[studios.Count];
  473. var dictionary = studios.Distinct(StringComparer.OrdinalIgnoreCase).Select(name =>
  474. {
  475. try
  476. {
  477. return _libraryManager.GetStudio(name);
  478. }
  479. catch (IOException ex)
  480. {
  481. _logger.ErrorException("Error getting studio {0}", ex, name);
  482. return null;
  483. }
  484. })
  485. .Where(i => i != null)
  486. .ToDictionary(i => i.Name, StringComparer.OrdinalIgnoreCase);
  487. for (var i = 0; i < studios.Count; i++)
  488. {
  489. var studio = studios[i];
  490. var studioDto = new StudioDto
  491. {
  492. Name = studio
  493. };
  494. Studio entity;
  495. if (dictionary.TryGetValue(studio, out entity))
  496. {
  497. studioDto.Id = entity.Id.ToString("N");
  498. studioDto.PrimaryImageTag = GetImageCacheTag(entity, ImageType.Primary);
  499. }
  500. dto.Studios[i] = studioDto;
  501. }
  502. }
  503. /// <summary>
  504. /// If an item does not any backdrops, this can be used to find the first parent that does have one
  505. /// </summary>
  506. /// <param name="item">The item.</param>
  507. /// <param name="owner">The owner.</param>
  508. /// <returns>BaseItem.</returns>
  509. private BaseItem GetParentBackdropItem(BaseItem item, BaseItem owner)
  510. {
  511. var parent = item.Parent ?? owner;
  512. while (parent != null)
  513. {
  514. if (parent.GetImages(ImageType.Backdrop).Any())
  515. {
  516. return parent;
  517. }
  518. parent = parent.Parent;
  519. }
  520. return null;
  521. }
  522. /// <summary>
  523. /// If an item does not have a logo, this can be used to find the first parent that does have one
  524. /// </summary>
  525. /// <param name="item">The item.</param>
  526. /// <param name="type">The type.</param>
  527. /// <param name="owner">The owner.</param>
  528. /// <returns>BaseItem.</returns>
  529. private BaseItem GetParentImageItem(BaseItem item, ImageType type, BaseItem owner)
  530. {
  531. var parent = item.Parent ?? owner;
  532. while (parent != null)
  533. {
  534. if (parent.HasImage(type))
  535. {
  536. return parent;
  537. }
  538. parent = parent.Parent;
  539. }
  540. return null;
  541. }
  542. /// <summary>
  543. /// Gets the chapter info dto.
  544. /// </summary>
  545. /// <param name="chapterInfo">The chapter info.</param>
  546. /// <param name="item">The item.</param>
  547. /// <returns>ChapterInfoDto.</returns>
  548. public ChapterInfoDto GetChapterInfoDto(ChapterInfo chapterInfo, BaseItem item)
  549. {
  550. var dto = new ChapterInfoDto
  551. {
  552. Name = chapterInfo.Name,
  553. StartPositionTicks = chapterInfo.StartPositionTicks
  554. };
  555. if (!string.IsNullOrEmpty(chapterInfo.ImagePath))
  556. {
  557. dto.ImageTag = GetImageCacheTag(item, new ItemImageInfo
  558. {
  559. Path = chapterInfo.ImagePath,
  560. Type = ImageType.Chapter,
  561. DateModified = _fileSystem.GetLastWriteTimeUtc(chapterInfo.ImagePath)
  562. });
  563. }
  564. return dto;
  565. }
  566. /// <summary>
  567. /// Sets simple property values on a DTOBaseItem
  568. /// </summary>
  569. /// <param name="dto">The dto.</param>
  570. /// <param name="item">The item.</param>
  571. /// <param name="owner">The owner.</param>
  572. /// <param name="fields">The fields.</param>
  573. private void AttachBasicFields(BaseItemDto dto, BaseItem item, BaseItem owner, List<ItemFields> fields)
  574. {
  575. if (fields.Contains(ItemFields.DateCreated))
  576. {
  577. dto.DateCreated = item.DateCreated;
  578. }
  579. if (fields.Contains(ItemFields.DisplayMediaType))
  580. {
  581. dto.DisplayMediaType = item.DisplayMediaType;
  582. }
  583. dto.IsUnidentified = item.IsUnidentified;
  584. if (fields.Contains(ItemFields.Settings))
  585. {
  586. dto.LockedFields = item.LockedFields;
  587. dto.LockData = item.IsLocked;
  588. dto.ForcedSortName = item.ForcedSortName;
  589. }
  590. var hasBudget = item as IHasBudget;
  591. if (hasBudget != null)
  592. {
  593. if (fields.Contains(ItemFields.Budget))
  594. {
  595. dto.Budget = hasBudget.Budget;
  596. }
  597. if (fields.Contains(ItemFields.Revenue))
  598. {
  599. dto.Revenue = hasBudget.Revenue;
  600. }
  601. }
  602. dto.EndDate = item.EndDate;
  603. if (fields.Contains(ItemFields.HomePageUrl))
  604. {
  605. dto.HomePageUrl = item.HomePageUrl;
  606. }
  607. if (fields.Contains(ItemFields.ExternalUrls))
  608. {
  609. dto.ExternalUrls = _providerManager.GetExternalUrls(item).ToArray();
  610. }
  611. if (fields.Contains(ItemFields.Tags))
  612. {
  613. var hasTags = item as IHasTags;
  614. if (hasTags != null)
  615. {
  616. dto.Tags = hasTags.Tags;
  617. }
  618. if (dto.Tags == null)
  619. {
  620. dto.Tags = new List<string>();
  621. }
  622. }
  623. if (fields.Contains(ItemFields.Keywords))
  624. {
  625. var hasTags = item as IHasKeywords;
  626. if (hasTags != null)
  627. {
  628. dto.Keywords = hasTags.Keywords;
  629. }
  630. if (dto.Keywords == null)
  631. {
  632. dto.Keywords = new List<string>();
  633. }
  634. }
  635. if (fields.Contains(ItemFields.ProductionLocations))
  636. {
  637. SetProductionLocations(item, dto);
  638. }
  639. var hasAspectRatio = item as IHasAspectRatio;
  640. if (hasAspectRatio != null)
  641. {
  642. dto.AspectRatio = hasAspectRatio.AspectRatio;
  643. }
  644. var hasMetascore = item as IHasMetascore;
  645. if (hasMetascore != null)
  646. {
  647. dto.Metascore = hasMetascore.Metascore;
  648. }
  649. if (fields.Contains(ItemFields.AwardSummary))
  650. {
  651. var hasAwards = item as IHasAwards;
  652. if (hasAwards != null)
  653. {
  654. dto.AwardSummary = hasAwards.AwardSummary;
  655. }
  656. }
  657. dto.BackdropImageTags = GetBackdropImageTags(item);
  658. if (fields.Contains(ItemFields.ScreenshotImageTags))
  659. {
  660. dto.ScreenshotImageTags = GetScreenshotImageTags(item);
  661. }
  662. if (fields.Contains(ItemFields.Genres))
  663. {
  664. dto.Genres = item.Genres;
  665. }
  666. dto.ImageTags = new Dictionary<ImageType, string>();
  667. // Prevent implicitly captured closure
  668. var currentItem = item;
  669. foreach (var image in currentItem.ImageInfos.Where(i => !currentItem.AllowsMultipleImages(i.Type)))
  670. {
  671. var tag = GetImageCacheTag(item, image);
  672. if (tag != null)
  673. {
  674. dto.ImageTags[image.Type] = tag;
  675. }
  676. }
  677. dto.Id = GetDtoId(item);
  678. dto.IndexNumber = item.IndexNumber;
  679. dto.IsFolder = item.IsFolder;
  680. dto.MediaType = item.MediaType;
  681. dto.LocationType = item.LocationType;
  682. var hasLang = item as IHasPreferredMetadataLanguage;
  683. if (hasLang != null)
  684. {
  685. dto.PreferredMetadataCountryCode = hasLang.PreferredMetadataCountryCode;
  686. dto.PreferredMetadataLanguage = hasLang.PreferredMetadataLanguage;
  687. }
  688. var hasCriticRating = item as IHasCriticRating;
  689. if (hasCriticRating != null)
  690. {
  691. dto.CriticRating = hasCriticRating.CriticRating;
  692. if (fields.Contains(ItemFields.CriticRatingSummary))
  693. {
  694. dto.CriticRatingSummary = hasCriticRating.CriticRatingSummary;
  695. }
  696. }
  697. var hasTrailers = item as IHasTrailers;
  698. if (hasTrailers != null)
  699. {
  700. dto.LocalTrailerCount = hasTrailers.LocalTrailerIds.Count;
  701. }
  702. var hasDisplayOrder = item as IHasDisplayOrder;
  703. if (hasDisplayOrder != null)
  704. {
  705. dto.DisplayOrder = hasDisplayOrder.DisplayOrder;
  706. }
  707. var collectionFolder = item as ICollectionFolder;
  708. if (collectionFolder != null)
  709. {
  710. dto.CollectionType = collectionFolder.CollectionType;
  711. }
  712. var userView = item as UserView;
  713. if (userView != null)
  714. {
  715. dto.CollectionType = userView.ViewType;
  716. }
  717. if (fields.Contains(ItemFields.RemoteTrailers))
  718. {
  719. dto.RemoteTrailers = hasTrailers != null ?
  720. hasTrailers.RemoteTrailers :
  721. new List<MediaUrl>();
  722. }
  723. dto.Name = item.Name;
  724. dto.OfficialRating = item.OfficialRating;
  725. if (fields.Contains(ItemFields.Overview))
  726. {
  727. dto.Overview = item.Overview;
  728. }
  729. if (fields.Contains(ItemFields.ShortOverview))
  730. {
  731. var hasShortOverview = item as IHasShortOverview;
  732. if (hasShortOverview != null)
  733. {
  734. dto.ShortOverview = hasShortOverview.ShortOverview;
  735. }
  736. }
  737. // If there are no backdrops, indicate what parent has them in case the Ui wants to allow inheritance
  738. if (dto.BackdropImageTags.Count == 0)
  739. {
  740. var parentWithBackdrop = GetParentBackdropItem(item, owner);
  741. if (parentWithBackdrop != null)
  742. {
  743. dto.ParentBackdropItemId = GetDtoId(parentWithBackdrop);
  744. dto.ParentBackdropImageTags = GetBackdropImageTags(parentWithBackdrop);
  745. }
  746. }
  747. if (item.Parent != null && fields.Contains(ItemFields.ParentId))
  748. {
  749. dto.ParentId = GetDtoId(item.Parent);
  750. }
  751. dto.ParentIndexNumber = item.ParentIndexNumber;
  752. // If there is no logo, indicate what parent has one in case the Ui wants to allow inheritance
  753. if (!dto.HasLogo)
  754. {
  755. var parentWithLogo = GetParentImageItem(item, ImageType.Logo, owner);
  756. if (parentWithLogo != null)
  757. {
  758. dto.ParentLogoItemId = GetDtoId(parentWithLogo);
  759. dto.ParentLogoImageTag = GetImageCacheTag(parentWithLogo, ImageType.Logo);
  760. }
  761. }
  762. // If there is no art, indicate what parent has one in case the Ui wants to allow inheritance
  763. if (!dto.HasArtImage)
  764. {
  765. var parentWithImage = GetParentImageItem(item, ImageType.Art, owner);
  766. if (parentWithImage != null)
  767. {
  768. dto.ParentArtItemId = GetDtoId(parentWithImage);
  769. dto.ParentArtImageTag = GetImageCacheTag(parentWithImage, ImageType.Art);
  770. }
  771. }
  772. // If there is no thumb, indicate what parent has one in case the Ui wants to allow inheritance
  773. if (!dto.HasThumb)
  774. {
  775. var parentWithImage = GetParentImageItem(item, ImageType.Thumb, owner);
  776. if (parentWithImage != null)
  777. {
  778. dto.ParentThumbItemId = GetDtoId(parentWithImage);
  779. dto.ParentThumbImageTag = GetImageCacheTag(parentWithImage, ImageType.Thumb);
  780. }
  781. }
  782. if (fields.Contains(ItemFields.Path))
  783. {
  784. dto.Path = GetMappedPath(item);
  785. }
  786. dto.PremiereDate = item.PremiereDate;
  787. dto.ProductionYear = item.ProductionYear;
  788. if (fields.Contains(ItemFields.ProviderIds))
  789. {
  790. dto.ProviderIds = item.ProviderIds;
  791. }
  792. dto.RunTimeTicks = item.RunTimeTicks;
  793. if (fields.Contains(ItemFields.SortName))
  794. {
  795. dto.SortName = item.SortName;
  796. }
  797. if (fields.Contains(ItemFields.CustomRating))
  798. {
  799. dto.CustomRating = item.CustomRating;
  800. }
  801. if (fields.Contains(ItemFields.Taglines))
  802. {
  803. var hasTagline = item as IHasTaglines;
  804. if (hasTagline != null)
  805. {
  806. dto.Taglines = hasTagline.Taglines;
  807. }
  808. if (dto.Taglines == null)
  809. {
  810. dto.Taglines = new List<string>();
  811. }
  812. }
  813. dto.Type = item.GetClientTypeName();
  814. dto.CommunityRating = item.CommunityRating;
  815. dto.VoteCount = item.VoteCount;
  816. if (item.IsFolder)
  817. {
  818. var folder = (Folder)item;
  819. if (fields.Contains(ItemFields.IndexOptions))
  820. {
  821. dto.IndexOptions = folder.IndexByOptionStrings.ToArray();
  822. }
  823. }
  824. var supportsPlaceHolders = item as ISupportsPlaceHolders;
  825. if (supportsPlaceHolders != null)
  826. {
  827. dto.IsPlaceHolder = supportsPlaceHolders.IsPlaceHolder;
  828. }
  829. // Add audio info
  830. var audio = item as Audio;
  831. if (audio != null)
  832. {
  833. dto.Album = audio.Album;
  834. dto.Artists = audio.Artists;
  835. var albumParent = audio.FindParent<MusicAlbum>();
  836. if (albumParent != null)
  837. {
  838. dto.AlbumId = GetDtoId(albumParent);
  839. dto.AlbumPrimaryImageTag = GetImageCacheTag(albumParent, ImageType.Primary);
  840. }
  841. dto.MediaSourceCount = 1;
  842. }
  843. var album = item as MusicAlbum;
  844. if (album != null)
  845. {
  846. dto.Artists = album.Artists;
  847. dto.SoundtrackIds = album.SoundtrackIds
  848. .Select(i => i.ToString("N"))
  849. .ToArray();
  850. }
  851. var hasAlbumArtist = item as IHasAlbumArtist;
  852. if (hasAlbumArtist != null)
  853. {
  854. dto.AlbumArtist = hasAlbumArtist.AlbumArtists.FirstOrDefault();
  855. }
  856. // Add video info
  857. var video = item as Video;
  858. if (video != null)
  859. {
  860. dto.VideoType = video.VideoType;
  861. dto.Video3DFormat = video.Video3DFormat;
  862. dto.IsoType = video.IsoType;
  863. dto.IsHD = video.IsHD;
  864. dto.PartCount = video.AdditionalPartIds.Count + 1;
  865. dto.MediaSourceCount = video.MediaSourceCount;
  866. if (fields.Contains(ItemFields.Chapters))
  867. {
  868. List<ChapterInfoDto> chapters;
  869. if (dto.MediaSources != null && dto.MediaSources.Count > 0)
  870. {
  871. chapters = _itemRepo.GetChapters(item.Id).Select(c => GetChapterInfoDto(c, item)).ToList();
  872. }
  873. else
  874. {
  875. chapters = _itemRepo.GetChapters(video.Id)
  876. .Select(c => GetChapterInfoDto(c, item))
  877. .ToList();
  878. }
  879. dto.Chapters = chapters;
  880. }
  881. }
  882. if (fields.Contains(ItemFields.MediaStreams))
  883. {
  884. // Add VideoInfo
  885. var iHasMediaSources = item as IHasMediaSources;
  886. if (iHasMediaSources != null)
  887. {
  888. List<MediaStream> mediaStreams;
  889. if (dto.MediaSources != null && dto.MediaSources.Count > 0)
  890. {
  891. mediaStreams = dto.MediaSources.Where(i => new Guid(i.Id) == item.Id)
  892. .SelectMany(i => i.MediaStreams)
  893. .ToList();
  894. }
  895. else
  896. {
  897. mediaStreams = iHasMediaSources.GetMediaSources(true).First().MediaStreams;
  898. }
  899. dto.MediaStreams = mediaStreams;
  900. }
  901. }
  902. // Add MovieInfo
  903. var movie = item as Movie;
  904. if (movie != null)
  905. {
  906. var specialFeatureCount = movie.SpecialFeatureIds.Count;
  907. if (specialFeatureCount > 0)
  908. {
  909. dto.SpecialFeatureCount = specialFeatureCount;
  910. }
  911. if (fields.Contains(ItemFields.TmdbCollectionName))
  912. {
  913. dto.TmdbCollectionName = movie.TmdbCollectionName;
  914. }
  915. }
  916. // Add EpisodeInfo
  917. var episode = item as Episode;
  918. if (episode != null)
  919. {
  920. dto.IndexNumberEnd = episode.IndexNumberEnd;
  921. dto.DvdSeasonNumber = episode.DvdSeasonNumber;
  922. dto.DvdEpisodeNumber = episode.DvdEpisodeNumber;
  923. dto.AirsAfterSeasonNumber = episode.AirsAfterSeasonNumber;
  924. dto.AirsBeforeEpisodeNumber = episode.AirsBeforeEpisodeNumber;
  925. dto.AirsBeforeSeasonNumber = episode.AirsBeforeSeasonNumber;
  926. dto.AbsoluteEpisodeNumber = episode.AbsoluteEpisodeNumber;
  927. var seasonId = episode.SeasonId;
  928. if (seasonId.HasValue)
  929. {
  930. dto.SeasonId = seasonId.Value.ToString("N");
  931. }
  932. }
  933. // Add SeriesInfo
  934. var series = item as Series;
  935. if (series != null)
  936. {
  937. dto.AirDays = series.AirDays;
  938. dto.AirTime = series.AirTime;
  939. dto.Status = series.Status;
  940. dto.SpecialFeatureCount = series.SpecialFeatureIds.Count;
  941. dto.SeasonCount = series.SeasonCount;
  942. if (fields.Contains(ItemFields.Settings))
  943. {
  944. dto.DisplaySpecialsWithSeasons = series.DisplaySpecialsWithSeasons;
  945. }
  946. dto.AnimeSeriesIndex = series.AnimeSeriesIndex;
  947. }
  948. if (episode != null)
  949. {
  950. series = episode.Series;
  951. if (series != null)
  952. {
  953. dto.SeriesId = GetDtoId(series);
  954. dto.SeriesName = series.Name;
  955. dto.AirTime = series.AirTime;
  956. dto.SeriesStudio = series.Studios.FirstOrDefault();
  957. dto.SeriesThumbImageTag = GetImageCacheTag(series, ImageType.Thumb);
  958. dto.SeriesPrimaryImageTag = GetImageCacheTag(series, ImageType.Primary);
  959. }
  960. }
  961. // Add SeasonInfo
  962. var season = item as Season;
  963. if (season != null)
  964. {
  965. series = season.Series;
  966. if (series != null)
  967. {
  968. dto.SeriesId = GetDtoId(series);
  969. dto.SeriesName = series.Name;
  970. dto.AirTime = series.AirTime;
  971. dto.SeriesStudio = series.Studios.FirstOrDefault();
  972. dto.SeriesPrimaryImageTag = GetImageCacheTag(series, ImageType.Primary);
  973. }
  974. }
  975. var game = item as Game;
  976. if (game != null)
  977. {
  978. SetGameProperties(dto, game);
  979. }
  980. var gameSystem = item as GameSystem;
  981. if (gameSystem != null)
  982. {
  983. SetGameSystemProperties(dto, gameSystem);
  984. }
  985. var musicVideo = item as MusicVideo;
  986. if (musicVideo != null)
  987. {
  988. SetMusicVideoProperties(dto, musicVideo);
  989. }
  990. var book = item as Book;
  991. if (book != null)
  992. {
  993. SetBookProperties(dto, book);
  994. }
  995. var tvChannel = item as LiveTvChannel;
  996. if (tvChannel != null)
  997. {
  998. dto.MediaSources = tvChannel.GetMediaSources(true).ToList();
  999. }
  1000. var channelItem = item as IChannelItem;
  1001. if (channelItem != null)
  1002. {
  1003. dto.ChannelId = channelItem.ChannelId;
  1004. dto.ChannelName = _channelManagerFactory().GetChannel(channelItem.ChannelId).Name;
  1005. }
  1006. }
  1007. private void AttachLinkedChildImages(BaseItemDto dto, Folder folder, User user)
  1008. {
  1009. List<BaseItem> linkedChildren = null;
  1010. if (dto.BackdropImageTags.Count == 0)
  1011. {
  1012. if (linkedChildren == null)
  1013. {
  1014. linkedChildren = user == null
  1015. ? folder.GetRecursiveChildren().ToList()
  1016. : folder.GetRecursiveChildren(user, true).ToList();
  1017. }
  1018. var parentWithBackdrop = linkedChildren.FirstOrDefault(i => i.GetImages(ImageType.Backdrop).Any());
  1019. if (parentWithBackdrop != null)
  1020. {
  1021. dto.ParentBackdropItemId = GetDtoId(parentWithBackdrop);
  1022. dto.ParentBackdropImageTags = GetBackdropImageTags(parentWithBackdrop);
  1023. }
  1024. }
  1025. if (!dto.ImageTags.ContainsKey(ImageType.Primary))
  1026. {
  1027. if (linkedChildren == null)
  1028. {
  1029. linkedChildren = user == null
  1030. ? folder.GetRecursiveChildren().ToList()
  1031. : folder.GetRecursiveChildren(user, true).ToList();
  1032. }
  1033. var parentWithImage = linkedChildren.FirstOrDefault(i => i.GetImages(ImageType.Primary).Any());
  1034. if (parentWithImage != null)
  1035. {
  1036. dto.ParentPrimaryImageItemId = GetDtoId(parentWithImage);
  1037. dto.ParentPrimaryImageTag = GetImageCacheTag(parentWithImage, ImageType.Primary);
  1038. }
  1039. }
  1040. }
  1041. private string GetMappedPath(IHasMetadata item)
  1042. {
  1043. var path = item.Path;
  1044. var locationType = item.LocationType;
  1045. if (locationType == LocationType.FileSystem || locationType == LocationType.Offline)
  1046. {
  1047. foreach (var map in _config.Configuration.PathSubstitutions)
  1048. {
  1049. path = _fileSystem.SubstitutePath(path, map.From, map.To);
  1050. }
  1051. }
  1052. return path;
  1053. }
  1054. private void SetProductionLocations(BaseItem item, BaseItemDto dto)
  1055. {
  1056. var hasProductionLocations = item as IHasProductionLocations;
  1057. if (hasProductionLocations != null)
  1058. {
  1059. dto.ProductionLocations = hasProductionLocations.ProductionLocations;
  1060. }
  1061. var person = item as Person;
  1062. if (person != null)
  1063. {
  1064. dto.ProductionLocations = new List<string>();
  1065. if (!string.IsNullOrEmpty(person.PlaceOfBirth))
  1066. {
  1067. dto.ProductionLocations.Add(person.PlaceOfBirth);
  1068. }
  1069. }
  1070. if (dto.ProductionLocations == null)
  1071. {
  1072. dto.ProductionLocations = new List<string>();
  1073. }
  1074. }
  1075. /// <summary>
  1076. /// Since it can be slow to make all of these calculations independently, this method will provide a way to do them all at once
  1077. /// </summary>
  1078. /// <param name="folder">The folder.</param>
  1079. /// <param name="user">The user.</param>
  1080. /// <param name="dto">The dto.</param>
  1081. /// <param name="fields">The fields.</param>
  1082. /// <returns>Task.</returns>
  1083. private void SetSpecialCounts(Folder folder, User user, BaseItemDto dto, List<ItemFields> fields)
  1084. {
  1085. var recursiveItemCount = 0;
  1086. var unplayed = 0;
  1087. long runtime = 0;
  1088. DateTime? dateLastMediaAdded = null;
  1089. double totalPercentPlayed = 0;
  1090. IEnumerable<BaseItem> children;
  1091. var season = folder as Season;
  1092. if (season != null)
  1093. {
  1094. children = season.GetEpisodes(user).Where(i => i.LocationType != LocationType.Virtual);
  1095. }
  1096. else
  1097. {
  1098. children = folder.GetRecursiveChildren(user)
  1099. .Where(i => !i.IsFolder && i.LocationType != LocationType.Virtual);
  1100. }
  1101. // Loop through each recursive child
  1102. foreach (var child in children)
  1103. {
  1104. if (!dateLastMediaAdded.HasValue)
  1105. {
  1106. dateLastMediaAdded = child.DateCreated;
  1107. }
  1108. else
  1109. {
  1110. dateLastMediaAdded = new[] { dateLastMediaAdded.Value, child.DateCreated }.Max();
  1111. }
  1112. var userdata = _userDataRepository.GetUserData(user.Id, child.GetUserDataKey());
  1113. recursiveItemCount++;
  1114. var isUnplayed = true;
  1115. // Incrememt totalPercentPlayed
  1116. if (userdata != null)
  1117. {
  1118. if (userdata.Played)
  1119. {
  1120. totalPercentPlayed += 100;
  1121. isUnplayed = false;
  1122. }
  1123. else if (userdata.PlaybackPositionTicks > 0 && child.RunTimeTicks.HasValue && child.RunTimeTicks.Value > 0)
  1124. {
  1125. double itemPercent = userdata.PlaybackPositionTicks;
  1126. itemPercent /= child.RunTimeTicks.Value;
  1127. totalPercentPlayed += itemPercent;
  1128. }
  1129. }
  1130. if (isUnplayed)
  1131. {
  1132. unplayed++;
  1133. }
  1134. runtime += child.RunTimeTicks ?? 0;
  1135. }
  1136. dto.RecursiveItemCount = recursiveItemCount;
  1137. dto.RecursiveUnplayedItemCount = unplayed;
  1138. if (recursiveItemCount > 0)
  1139. {
  1140. dto.PlayedPercentage = totalPercentPlayed / recursiveItemCount;
  1141. }
  1142. if (runtime > 0 && fields.Contains(ItemFields.CumulativeRunTimeTicks))
  1143. {
  1144. dto.CumulativeRunTimeTicks = runtime;
  1145. }
  1146. if (fields.Contains(ItemFields.DateLastMediaAdded))
  1147. {
  1148. dto.DateLastMediaAdded = dateLastMediaAdded;
  1149. }
  1150. }
  1151. /// <summary>
  1152. /// Attaches the primary image aspect ratio.
  1153. /// </summary>
  1154. /// <param name="dto">The dto.</param>
  1155. /// <param name="item">The item.</param>
  1156. /// <returns>Task.</returns>
  1157. public void AttachPrimaryImageAspectRatio(IItemDto dto, IHasImages item)
  1158. {
  1159. var imageInfo = item.GetImageInfo(ImageType.Primary, 0);
  1160. if (imageInfo == null)
  1161. {
  1162. return;
  1163. }
  1164. var path = imageInfo.Path;
  1165. // See if we can avoid a file system lookup by looking for the file in ResolveArgs
  1166. var dateModified = imageInfo.DateModified;
  1167. ImageSize size;
  1168. try
  1169. {
  1170. size = _imageProcessor.GetImageSize(path, dateModified);
  1171. }
  1172. catch (FileNotFoundException)
  1173. {
  1174. _logger.Error("Image file does not exist: {0}", path);
  1175. return;
  1176. }
  1177. catch (Exception ex)
  1178. {
  1179. _logger.ErrorException("Failed to determine primary image aspect ratio for {0}", ex, path);
  1180. return;
  1181. }
  1182. dto.OriginalPrimaryImageAspectRatio = size.Width / size.Height;
  1183. var supportedEnhancers = _imageProcessor.GetSupportedEnhancers(item, ImageType.Primary).ToList();
  1184. foreach (var enhancer in supportedEnhancers)
  1185. {
  1186. try
  1187. {
  1188. size = enhancer.GetEnhancedImageSize(item, ImageType.Primary, 0, size);
  1189. }
  1190. catch (Exception ex)
  1191. {
  1192. _logger.ErrorException("Error in image enhancer: {0}", ex, enhancer.GetType().Name);
  1193. }
  1194. }
  1195. dto.PrimaryImageAspectRatio = size.Width / size.Height;
  1196. }
  1197. }
  1198. }