DtoService.cs 48 KB

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