DtoService.cs 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443
  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. // These are just far too slow.
  216. // TODO: Disable for CollectionFolder
  217. if (!(folder is UserRootFolder) && !(folder is UserView))
  218. {
  219. SetSpecialCounts(folder, user, dto, fields);
  220. }
  221. dto.UserData.Played = dto.UserData.PlayedPercentage.HasValue && dto.UserData.PlayedPercentage.Value >= 100;
  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 (Exception 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.UserData.UnplayedItemCount = unplayed;
  1138. dto.RecursiveUnplayedItemCount = unplayed;
  1139. if (recursiveItemCount > 0)
  1140. {
  1141. dto.UserData.PlayedPercentage = totalPercentPlayed / recursiveItemCount;
  1142. }
  1143. if (runtime > 0 && fields.Contains(ItemFields.CumulativeRunTimeTicks))
  1144. {
  1145. dto.CumulativeRunTimeTicks = runtime;
  1146. }
  1147. if (fields.Contains(ItemFields.DateLastMediaAdded))
  1148. {
  1149. dto.DateLastMediaAdded = dateLastMediaAdded;
  1150. }
  1151. }
  1152. /// <summary>
  1153. /// Attaches the primary image aspect ratio.
  1154. /// </summary>
  1155. /// <param name="dto">The dto.</param>
  1156. /// <param name="item">The item.</param>
  1157. /// <returns>Task.</returns>
  1158. public void AttachPrimaryImageAspectRatio(IItemDto dto, IHasImages item)
  1159. {
  1160. var imageInfo = item.GetImageInfo(ImageType.Primary, 0);
  1161. if (imageInfo == null)
  1162. {
  1163. return;
  1164. }
  1165. var path = imageInfo.Path;
  1166. // See if we can avoid a file system lookup by looking for the file in ResolveArgs
  1167. var dateModified = imageInfo.DateModified;
  1168. ImageSize size;
  1169. try
  1170. {
  1171. size = _imageProcessor.GetImageSize(path, dateModified);
  1172. }
  1173. catch (FileNotFoundException)
  1174. {
  1175. _logger.Error("Image file does not exist: {0}", path);
  1176. return;
  1177. }
  1178. catch (Exception ex)
  1179. {
  1180. _logger.ErrorException("Failed to determine primary image aspect ratio for {0}", ex, path);
  1181. return;
  1182. }
  1183. dto.OriginalPrimaryImageAspectRatio = size.Width / size.Height;
  1184. var supportedEnhancers = _imageProcessor.GetSupportedEnhancers(item, ImageType.Primary).ToList();
  1185. foreach (var enhancer in supportedEnhancers)
  1186. {
  1187. try
  1188. {
  1189. size = enhancer.GetEnhancedImageSize(item, ImageType.Primary, 0, size);
  1190. }
  1191. catch (Exception ex)
  1192. {
  1193. _logger.ErrorException("Error in image enhancer: {0}", ex, enhancer.GetType().Name);
  1194. }
  1195. }
  1196. dto.PrimaryImageAspectRatio = size.Width / size.Height;
  1197. }
  1198. }
  1199. }