DtoService.cs 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459
  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 SetPhotoProperties(BaseItemDto dto, Photo item)
  308. {
  309. dto.Width = item.Width;
  310. dto.Height = item.Height;
  311. dto.CameraMake = item.CameraMake;
  312. dto.CameraModel = item.CameraModel;
  313. dto.Software = item.Software;
  314. dto.ExposureTime = item.ExposureTime;
  315. dto.FocalLength = item.FocalLength;
  316. dto.ImageOrientation = item.Orientation;
  317. dto.Aperture = item.Aperture;
  318. dto.ShutterSpeed = item.ShutterSpeed;
  319. }
  320. private void SetMusicVideoProperties(BaseItemDto dto, MusicVideo item)
  321. {
  322. if (!string.IsNullOrEmpty(item.Album))
  323. {
  324. var parentAlbum = _libraryManager.RootFolder
  325. .GetRecursiveChildren()
  326. .Where(i => i is MusicAlbum)
  327. .FirstOrDefault(i => string.Equals(i.Name, item.Album, StringComparison.OrdinalIgnoreCase));
  328. if (parentAlbum != null)
  329. {
  330. dto.AlbumId = GetDtoId(parentAlbum);
  331. }
  332. }
  333. dto.Album = item.Album;
  334. dto.Artists = string.IsNullOrEmpty(item.Artist) ? new List<string>() : new List<string> { item.Artist };
  335. }
  336. private void SetGameProperties(BaseItemDto dto, Game item)
  337. {
  338. dto.Players = item.PlayersSupported;
  339. dto.GameSystem = item.GameSystem;
  340. dto.MultiPartGameFiles = item.MultiPartGameFiles;
  341. }
  342. private void SetGameSystemProperties(BaseItemDto dto, GameSystem item)
  343. {
  344. dto.GameSystem = item.GameSystemName;
  345. }
  346. /// <summary>
  347. /// Gets the backdrop image tags.
  348. /// </summary>
  349. /// <param name="item">The item.</param>
  350. /// <returns>List{System.String}.</returns>
  351. private List<string> GetBackdropImageTags(BaseItem item)
  352. {
  353. return GetCacheTags(item, ImageType.Backdrop).ToList();
  354. }
  355. /// <summary>
  356. /// Gets the screenshot image tags.
  357. /// </summary>
  358. /// <param name="item">The item.</param>
  359. /// <returns>List{Guid}.</returns>
  360. private List<string> GetScreenshotImageTags(BaseItem item)
  361. {
  362. var hasScreenshots = item as IHasScreenshots;
  363. if (hasScreenshots == null)
  364. {
  365. return new List<string>();
  366. }
  367. return GetCacheTags(item, ImageType.Screenshot).ToList();
  368. }
  369. private IEnumerable<string> GetCacheTags(BaseItem item, ImageType type)
  370. {
  371. return item.GetImages(type)
  372. .Select(p => GetImageCacheTag(item, p))
  373. .Where(i => i != null)
  374. .ToList();
  375. }
  376. private string GetImageCacheTag(BaseItem item, ImageType type)
  377. {
  378. try
  379. {
  380. return _imageProcessor.GetImageCacheTag(item, type);
  381. }
  382. catch (Exception ex)
  383. {
  384. _logger.ErrorException("Error getting {0} image info", ex, type);
  385. return null;
  386. }
  387. }
  388. private string GetImageCacheTag(BaseItem item, ItemImageInfo image)
  389. {
  390. try
  391. {
  392. return _imageProcessor.GetImageCacheTag(item, image);
  393. }
  394. catch (Exception ex)
  395. {
  396. _logger.ErrorException("Error getting {0} image info for {1}", ex, image.Type, image.Path);
  397. return null;
  398. }
  399. }
  400. /// <summary>
  401. /// Attaches People DTO's to a DTOBaseItem
  402. /// </summary>
  403. /// <param name="dto">The dto.</param>
  404. /// <param name="item">The item.</param>
  405. /// <returns>Task.</returns>
  406. private void AttachPeople(BaseItemDto dto, BaseItem item)
  407. {
  408. // Ordering by person type to ensure actors and artists are at the front.
  409. // This is taking advantage of the fact that they both begin with A
  410. // This should be improved in the future
  411. var people = item.People.OrderBy(i => i.SortOrder ?? int.MaxValue)
  412. .ThenBy(i =>
  413. {
  414. if (i.IsType(PersonType.Actor))
  415. {
  416. return 0;
  417. }
  418. if (i.IsType(PersonType.GuestStar))
  419. {
  420. return 1;
  421. }
  422. if (i.IsType(PersonType.Director))
  423. {
  424. return 2;
  425. }
  426. if (i.IsType(PersonType.Writer))
  427. {
  428. return 3;
  429. }
  430. if (i.IsType(PersonType.Producer))
  431. {
  432. return 4;
  433. }
  434. if (i.IsType(PersonType.Composer))
  435. {
  436. return 4;
  437. }
  438. return 10;
  439. })
  440. .ToList();
  441. // Attach People by transforming them into BaseItemPerson (DTO)
  442. dto.People = new BaseItemPerson[people.Count];
  443. var dictionary = people.Select(p => p.Name)
  444. .Distinct(StringComparer.OrdinalIgnoreCase).Select(c =>
  445. {
  446. try
  447. {
  448. return _libraryManager.GetPerson(c);
  449. }
  450. catch (Exception ex)
  451. {
  452. _logger.ErrorException("Error getting person {0}", ex, c);
  453. return null;
  454. }
  455. }).Where(i => i != null)
  456. .DistinctBy(i => i.Name)
  457. .ToDictionary(i => i.Name, StringComparer.OrdinalIgnoreCase);
  458. for (var i = 0; i < people.Count; i++)
  459. {
  460. var person = people[i];
  461. var baseItemPerson = new BaseItemPerson
  462. {
  463. Name = person.Name,
  464. Role = person.Role,
  465. Type = person.Type
  466. };
  467. Person entity;
  468. if (dictionary.TryGetValue(person.Name, out entity))
  469. {
  470. baseItemPerson.PrimaryImageTag = GetImageCacheTag(entity, ImageType.Primary);
  471. baseItemPerson.Id = entity.Id.ToString("N");
  472. }
  473. dto.People[i] = baseItemPerson;
  474. }
  475. }
  476. /// <summary>
  477. /// Attaches the studios.
  478. /// </summary>
  479. /// <param name="dto">The dto.</param>
  480. /// <param name="item">The item.</param>
  481. /// <returns>Task.</returns>
  482. private void AttachStudios(BaseItemDto dto, BaseItem item)
  483. {
  484. var studios = item.Studios.ToList();
  485. dto.Studios = new StudioDto[studios.Count];
  486. var dictionary = studios.Distinct(StringComparer.OrdinalIgnoreCase).Select(name =>
  487. {
  488. try
  489. {
  490. return _libraryManager.GetStudio(name);
  491. }
  492. catch (IOException ex)
  493. {
  494. _logger.ErrorException("Error getting studio {0}", ex, name);
  495. return null;
  496. }
  497. })
  498. .Where(i => i != null)
  499. .ToDictionary(i => i.Name, StringComparer.OrdinalIgnoreCase);
  500. for (var i = 0; i < studios.Count; i++)
  501. {
  502. var studio = studios[i];
  503. var studioDto = new StudioDto
  504. {
  505. Name = studio
  506. };
  507. Studio entity;
  508. if (dictionary.TryGetValue(studio, out entity))
  509. {
  510. studioDto.Id = entity.Id.ToString("N");
  511. studioDto.PrimaryImageTag = GetImageCacheTag(entity, ImageType.Primary);
  512. }
  513. dto.Studios[i] = studioDto;
  514. }
  515. }
  516. /// <summary>
  517. /// If an item does not any backdrops, this can be used to find the first parent that does have one
  518. /// </summary>
  519. /// <param name="item">The item.</param>
  520. /// <param name="owner">The owner.</param>
  521. /// <returns>BaseItem.</returns>
  522. private BaseItem GetParentBackdropItem(BaseItem item, BaseItem owner)
  523. {
  524. var parent = item.Parent ?? owner;
  525. while (parent != null)
  526. {
  527. if (parent.GetImages(ImageType.Backdrop).Any())
  528. {
  529. return parent;
  530. }
  531. parent = parent.Parent;
  532. }
  533. return null;
  534. }
  535. /// <summary>
  536. /// If an item does not have a logo, this can be used to find the first parent that does have one
  537. /// </summary>
  538. /// <param name="item">The item.</param>
  539. /// <param name="type">The type.</param>
  540. /// <param name="owner">The owner.</param>
  541. /// <returns>BaseItem.</returns>
  542. private BaseItem GetParentImageItem(BaseItem item, ImageType type, BaseItem owner)
  543. {
  544. var parent = item.Parent ?? owner;
  545. while (parent != null)
  546. {
  547. if (parent.HasImage(type))
  548. {
  549. return parent;
  550. }
  551. parent = parent.Parent;
  552. }
  553. return null;
  554. }
  555. /// <summary>
  556. /// Gets the chapter info dto.
  557. /// </summary>
  558. /// <param name="chapterInfo">The chapter info.</param>
  559. /// <param name="item">The item.</param>
  560. /// <returns>ChapterInfoDto.</returns>
  561. public ChapterInfoDto GetChapterInfoDto(ChapterInfo chapterInfo, BaseItem item)
  562. {
  563. var dto = new ChapterInfoDto
  564. {
  565. Name = chapterInfo.Name,
  566. StartPositionTicks = chapterInfo.StartPositionTicks
  567. };
  568. if (!string.IsNullOrEmpty(chapterInfo.ImagePath))
  569. {
  570. dto.ImageTag = GetImageCacheTag(item, new ItemImageInfo
  571. {
  572. Path = chapterInfo.ImagePath,
  573. Type = ImageType.Chapter,
  574. DateModified = _fileSystem.GetLastWriteTimeUtc(chapterInfo.ImagePath)
  575. });
  576. }
  577. return dto;
  578. }
  579. /// <summary>
  580. /// Sets simple property values on a DTOBaseItem
  581. /// </summary>
  582. /// <param name="dto">The dto.</param>
  583. /// <param name="item">The item.</param>
  584. /// <param name="owner">The owner.</param>
  585. /// <param name="fields">The fields.</param>
  586. private void AttachBasicFields(BaseItemDto dto, BaseItem item, BaseItem owner, List<ItemFields> fields)
  587. {
  588. if (fields.Contains(ItemFields.DateCreated))
  589. {
  590. dto.DateCreated = item.DateCreated;
  591. }
  592. if (fields.Contains(ItemFields.DisplayMediaType))
  593. {
  594. dto.DisplayMediaType = item.DisplayMediaType;
  595. }
  596. dto.IsUnidentified = item.IsUnidentified;
  597. if (fields.Contains(ItemFields.Settings))
  598. {
  599. dto.LockedFields = item.LockedFields;
  600. dto.LockData = item.IsLocked;
  601. dto.ForcedSortName = item.ForcedSortName;
  602. }
  603. var hasBudget = item as IHasBudget;
  604. if (hasBudget != null)
  605. {
  606. if (fields.Contains(ItemFields.Budget))
  607. {
  608. dto.Budget = hasBudget.Budget;
  609. }
  610. if (fields.Contains(ItemFields.Revenue))
  611. {
  612. dto.Revenue = hasBudget.Revenue;
  613. }
  614. }
  615. dto.EndDate = item.EndDate;
  616. if (fields.Contains(ItemFields.HomePageUrl))
  617. {
  618. dto.HomePageUrl = item.HomePageUrl;
  619. }
  620. if (fields.Contains(ItemFields.ExternalUrls))
  621. {
  622. dto.ExternalUrls = _providerManager.GetExternalUrls(item).ToArray();
  623. }
  624. if (fields.Contains(ItemFields.Tags))
  625. {
  626. var hasTags = item as IHasTags;
  627. if (hasTags != null)
  628. {
  629. dto.Tags = hasTags.Tags;
  630. }
  631. if (dto.Tags == null)
  632. {
  633. dto.Tags = new List<string>();
  634. }
  635. }
  636. if (fields.Contains(ItemFields.Keywords))
  637. {
  638. var hasTags = item as IHasKeywords;
  639. if (hasTags != null)
  640. {
  641. dto.Keywords = hasTags.Keywords;
  642. }
  643. if (dto.Keywords == null)
  644. {
  645. dto.Keywords = new List<string>();
  646. }
  647. }
  648. if (fields.Contains(ItemFields.ProductionLocations))
  649. {
  650. SetProductionLocations(item, dto);
  651. }
  652. var hasAspectRatio = item as IHasAspectRatio;
  653. if (hasAspectRatio != null)
  654. {
  655. dto.AspectRatio = hasAspectRatio.AspectRatio;
  656. }
  657. var hasMetascore = item as IHasMetascore;
  658. if (hasMetascore != null)
  659. {
  660. dto.Metascore = hasMetascore.Metascore;
  661. }
  662. if (fields.Contains(ItemFields.AwardSummary))
  663. {
  664. var hasAwards = item as IHasAwards;
  665. if (hasAwards != null)
  666. {
  667. dto.AwardSummary = hasAwards.AwardSummary;
  668. }
  669. }
  670. dto.BackdropImageTags = GetBackdropImageTags(item);
  671. if (fields.Contains(ItemFields.ScreenshotImageTags))
  672. {
  673. dto.ScreenshotImageTags = GetScreenshotImageTags(item);
  674. }
  675. if (fields.Contains(ItemFields.Genres))
  676. {
  677. dto.Genres = item.Genres;
  678. }
  679. dto.ImageTags = new Dictionary<ImageType, string>();
  680. // Prevent implicitly captured closure
  681. var currentItem = item;
  682. foreach (var image in currentItem.ImageInfos.Where(i => !currentItem.AllowsMultipleImages(i.Type)))
  683. {
  684. var tag = GetImageCacheTag(item, image);
  685. if (tag != null)
  686. {
  687. dto.ImageTags[image.Type] = tag;
  688. }
  689. }
  690. dto.Id = GetDtoId(item);
  691. dto.IndexNumber = item.IndexNumber;
  692. dto.IsFolder = item.IsFolder;
  693. dto.MediaType = item.MediaType;
  694. dto.LocationType = item.LocationType;
  695. var hasLang = item as IHasPreferredMetadataLanguage;
  696. if (hasLang != null)
  697. {
  698. dto.PreferredMetadataCountryCode = hasLang.PreferredMetadataCountryCode;
  699. dto.PreferredMetadataLanguage = hasLang.PreferredMetadataLanguage;
  700. }
  701. var hasCriticRating = item as IHasCriticRating;
  702. if (hasCriticRating != null)
  703. {
  704. dto.CriticRating = hasCriticRating.CriticRating;
  705. if (fields.Contains(ItemFields.CriticRatingSummary))
  706. {
  707. dto.CriticRatingSummary = hasCriticRating.CriticRatingSummary;
  708. }
  709. }
  710. var hasTrailers = item as IHasTrailers;
  711. if (hasTrailers != null)
  712. {
  713. dto.LocalTrailerCount = hasTrailers.LocalTrailerIds.Count;
  714. }
  715. var hasDisplayOrder = item as IHasDisplayOrder;
  716. if (hasDisplayOrder != null)
  717. {
  718. dto.DisplayOrder = hasDisplayOrder.DisplayOrder;
  719. }
  720. var collectionFolder = item as ICollectionFolder;
  721. if (collectionFolder != null)
  722. {
  723. dto.CollectionType = collectionFolder.CollectionType;
  724. }
  725. var userView = item as UserView;
  726. if (userView != null)
  727. {
  728. dto.CollectionType = userView.ViewType;
  729. }
  730. if (fields.Contains(ItemFields.RemoteTrailers))
  731. {
  732. dto.RemoteTrailers = hasTrailers != null ?
  733. hasTrailers.RemoteTrailers :
  734. new List<MediaUrl>();
  735. }
  736. dto.Name = item.Name;
  737. dto.OfficialRating = item.OfficialRating;
  738. if (fields.Contains(ItemFields.Overview))
  739. {
  740. dto.Overview = item.Overview;
  741. }
  742. if (fields.Contains(ItemFields.ShortOverview))
  743. {
  744. var hasShortOverview = item as IHasShortOverview;
  745. if (hasShortOverview != null)
  746. {
  747. dto.ShortOverview = hasShortOverview.ShortOverview;
  748. }
  749. }
  750. // If there are no backdrops, indicate what parent has them in case the Ui wants to allow inheritance
  751. if (dto.BackdropImageTags.Count == 0)
  752. {
  753. var parentWithBackdrop = GetParentBackdropItem(item, owner);
  754. if (parentWithBackdrop != null)
  755. {
  756. dto.ParentBackdropItemId = GetDtoId(parentWithBackdrop);
  757. dto.ParentBackdropImageTags = GetBackdropImageTags(parentWithBackdrop);
  758. }
  759. }
  760. if (item.Parent != null && fields.Contains(ItemFields.ParentId))
  761. {
  762. dto.ParentId = GetDtoId(item.Parent);
  763. }
  764. dto.ParentIndexNumber = item.ParentIndexNumber;
  765. // If there is no logo, indicate what parent has one in case the Ui wants to allow inheritance
  766. if (!dto.HasLogo)
  767. {
  768. var parentWithLogo = GetParentImageItem(item, ImageType.Logo, owner);
  769. if (parentWithLogo != null)
  770. {
  771. dto.ParentLogoItemId = GetDtoId(parentWithLogo);
  772. dto.ParentLogoImageTag = GetImageCacheTag(parentWithLogo, ImageType.Logo);
  773. }
  774. }
  775. // If there is no art, indicate what parent has one in case the Ui wants to allow inheritance
  776. if (!dto.HasArtImage)
  777. {
  778. var parentWithImage = GetParentImageItem(item, ImageType.Art, owner);
  779. if (parentWithImage != null)
  780. {
  781. dto.ParentArtItemId = GetDtoId(parentWithImage);
  782. dto.ParentArtImageTag = GetImageCacheTag(parentWithImage, ImageType.Art);
  783. }
  784. }
  785. // If there is no thumb, indicate what parent has one in case the Ui wants to allow inheritance
  786. if (!dto.HasThumb)
  787. {
  788. var parentWithImage = GetParentImageItem(item, ImageType.Thumb, owner);
  789. if (parentWithImage != null)
  790. {
  791. dto.ParentThumbItemId = GetDtoId(parentWithImage);
  792. dto.ParentThumbImageTag = GetImageCacheTag(parentWithImage, ImageType.Thumb);
  793. }
  794. }
  795. if (fields.Contains(ItemFields.Path))
  796. {
  797. dto.Path = GetMappedPath(item);
  798. }
  799. dto.PremiereDate = item.PremiereDate;
  800. dto.ProductionYear = item.ProductionYear;
  801. if (fields.Contains(ItemFields.ProviderIds))
  802. {
  803. dto.ProviderIds = item.ProviderIds;
  804. }
  805. dto.RunTimeTicks = item.RunTimeTicks;
  806. if (fields.Contains(ItemFields.SortName))
  807. {
  808. dto.SortName = item.SortName;
  809. }
  810. if (fields.Contains(ItemFields.CustomRating))
  811. {
  812. dto.CustomRating = item.CustomRating;
  813. }
  814. if (fields.Contains(ItemFields.Taglines))
  815. {
  816. var hasTagline = item as IHasTaglines;
  817. if (hasTagline != null)
  818. {
  819. dto.Taglines = hasTagline.Taglines;
  820. }
  821. if (dto.Taglines == null)
  822. {
  823. dto.Taglines = new List<string>();
  824. }
  825. }
  826. dto.Type = item.GetClientTypeName();
  827. dto.CommunityRating = item.CommunityRating;
  828. dto.VoteCount = item.VoteCount;
  829. if (item.IsFolder)
  830. {
  831. var folder = (Folder)item;
  832. if (fields.Contains(ItemFields.IndexOptions))
  833. {
  834. dto.IndexOptions = folder.IndexByOptionStrings.ToArray();
  835. }
  836. }
  837. var supportsPlaceHolders = item as ISupportsPlaceHolders;
  838. if (supportsPlaceHolders != null)
  839. {
  840. dto.IsPlaceHolder = supportsPlaceHolders.IsPlaceHolder;
  841. }
  842. // Add audio info
  843. var audio = item as Audio;
  844. if (audio != null)
  845. {
  846. dto.Album = audio.Album;
  847. dto.Artists = audio.Artists;
  848. var albumParent = audio.FindParent<MusicAlbum>();
  849. if (albumParent != null)
  850. {
  851. dto.AlbumId = GetDtoId(albumParent);
  852. dto.AlbumPrimaryImageTag = GetImageCacheTag(albumParent, ImageType.Primary);
  853. }
  854. dto.MediaSourceCount = 1;
  855. }
  856. var album = item as MusicAlbum;
  857. if (album != null)
  858. {
  859. dto.Artists = album.Artists;
  860. dto.SoundtrackIds = album.SoundtrackIds
  861. .Select(i => i.ToString("N"))
  862. .ToArray();
  863. }
  864. var hasAlbumArtist = item as IHasAlbumArtist;
  865. if (hasAlbumArtist != null)
  866. {
  867. dto.AlbumArtist = hasAlbumArtist.AlbumArtists.FirstOrDefault();
  868. }
  869. // Add video info
  870. var video = item as Video;
  871. if (video != null)
  872. {
  873. dto.VideoType = video.VideoType;
  874. dto.Video3DFormat = video.Video3DFormat;
  875. dto.IsoType = video.IsoType;
  876. dto.IsHD = video.IsHD;
  877. dto.PartCount = video.AdditionalPartIds.Count + 1;
  878. dto.MediaSourceCount = video.MediaSourceCount;
  879. if (fields.Contains(ItemFields.Chapters))
  880. {
  881. List<ChapterInfoDto> chapters;
  882. if (dto.MediaSources != null && dto.MediaSources.Count > 0)
  883. {
  884. chapters = _itemRepo.GetChapters(item.Id).Select(c => GetChapterInfoDto(c, item)).ToList();
  885. }
  886. else
  887. {
  888. chapters = _itemRepo.GetChapters(video.Id)
  889. .Select(c => GetChapterInfoDto(c, item))
  890. .ToList();
  891. }
  892. dto.Chapters = chapters;
  893. }
  894. }
  895. if (fields.Contains(ItemFields.MediaStreams))
  896. {
  897. // Add VideoInfo
  898. var iHasMediaSources = item as IHasMediaSources;
  899. if (iHasMediaSources != null)
  900. {
  901. List<MediaStream> mediaStreams;
  902. if (dto.MediaSources != null && dto.MediaSources.Count > 0)
  903. {
  904. mediaStreams = dto.MediaSources.Where(i => new Guid(i.Id) == item.Id)
  905. .SelectMany(i => i.MediaStreams)
  906. .ToList();
  907. }
  908. else
  909. {
  910. mediaStreams = iHasMediaSources.GetMediaSources(true).First().MediaStreams;
  911. }
  912. dto.MediaStreams = mediaStreams;
  913. }
  914. }
  915. // Add MovieInfo
  916. var movie = item as Movie;
  917. if (movie != null)
  918. {
  919. var specialFeatureCount = movie.SpecialFeatureIds.Count;
  920. if (specialFeatureCount > 0)
  921. {
  922. dto.SpecialFeatureCount = specialFeatureCount;
  923. }
  924. if (fields.Contains(ItemFields.TmdbCollectionName))
  925. {
  926. dto.TmdbCollectionName = movie.TmdbCollectionName;
  927. }
  928. }
  929. // Add EpisodeInfo
  930. var episode = item as Episode;
  931. if (episode != null)
  932. {
  933. dto.IndexNumberEnd = episode.IndexNumberEnd;
  934. dto.DvdSeasonNumber = episode.DvdSeasonNumber;
  935. dto.DvdEpisodeNumber = episode.DvdEpisodeNumber;
  936. dto.AirsAfterSeasonNumber = episode.AirsAfterSeasonNumber;
  937. dto.AirsBeforeEpisodeNumber = episode.AirsBeforeEpisodeNumber;
  938. dto.AirsBeforeSeasonNumber = episode.AirsBeforeSeasonNumber;
  939. dto.AbsoluteEpisodeNumber = episode.AbsoluteEpisodeNumber;
  940. var seasonId = episode.SeasonId;
  941. if (seasonId.HasValue)
  942. {
  943. dto.SeasonId = seasonId.Value.ToString("N");
  944. }
  945. }
  946. // Add SeriesInfo
  947. var series = item as Series;
  948. if (series != null)
  949. {
  950. dto.AirDays = series.AirDays;
  951. dto.AirTime = series.AirTime;
  952. dto.Status = series.Status;
  953. dto.SpecialFeatureCount = series.SpecialFeatureIds.Count;
  954. dto.SeasonCount = series.SeasonCount;
  955. if (fields.Contains(ItemFields.Settings))
  956. {
  957. dto.DisplaySpecialsWithSeasons = series.DisplaySpecialsWithSeasons;
  958. }
  959. dto.AnimeSeriesIndex = series.AnimeSeriesIndex;
  960. }
  961. if (episode != null)
  962. {
  963. series = episode.Series;
  964. if (series != null)
  965. {
  966. dto.SeriesId = GetDtoId(series);
  967. dto.SeriesName = series.Name;
  968. dto.AirTime = series.AirTime;
  969. dto.SeriesStudio = series.Studios.FirstOrDefault();
  970. dto.SeriesThumbImageTag = GetImageCacheTag(series, ImageType.Thumb);
  971. dto.SeriesPrimaryImageTag = GetImageCacheTag(series, ImageType.Primary);
  972. }
  973. }
  974. // Add SeasonInfo
  975. var season = item as Season;
  976. if (season != null)
  977. {
  978. series = season.Series;
  979. if (series != null)
  980. {
  981. dto.SeriesId = GetDtoId(series);
  982. dto.SeriesName = series.Name;
  983. dto.AirTime = series.AirTime;
  984. dto.SeriesStudio = series.Studios.FirstOrDefault();
  985. dto.SeriesPrimaryImageTag = GetImageCacheTag(series, ImageType.Primary);
  986. }
  987. }
  988. var game = item as Game;
  989. if (game != null)
  990. {
  991. SetGameProperties(dto, game);
  992. }
  993. var gameSystem = item as GameSystem;
  994. if (gameSystem != null)
  995. {
  996. SetGameSystemProperties(dto, gameSystem);
  997. }
  998. var musicVideo = item as MusicVideo;
  999. if (musicVideo != null)
  1000. {
  1001. SetMusicVideoProperties(dto, musicVideo);
  1002. }
  1003. var book = item as Book;
  1004. if (book != null)
  1005. {
  1006. SetBookProperties(dto, book);
  1007. }
  1008. var photo = item as Photo;
  1009. if (photo != null)
  1010. {
  1011. SetPhotoProperties(dto, photo);
  1012. }
  1013. var tvChannel = item as LiveTvChannel;
  1014. if (tvChannel != null)
  1015. {
  1016. dto.MediaSources = tvChannel.GetMediaSources(true).ToList();
  1017. }
  1018. var channelItem = item as IChannelItem;
  1019. if (channelItem != null)
  1020. {
  1021. dto.ChannelId = channelItem.ChannelId;
  1022. dto.ChannelName = _channelManagerFactory().GetChannel(channelItem.ChannelId).Name;
  1023. }
  1024. }
  1025. private void AttachLinkedChildImages(BaseItemDto dto, Folder folder, User user)
  1026. {
  1027. List<BaseItem> linkedChildren = null;
  1028. if (dto.BackdropImageTags.Count == 0)
  1029. {
  1030. if (linkedChildren == null)
  1031. {
  1032. linkedChildren = user == null
  1033. ? folder.GetRecursiveChildren().ToList()
  1034. : folder.GetRecursiveChildren(user, true).ToList();
  1035. }
  1036. var parentWithBackdrop = linkedChildren.FirstOrDefault(i => i.GetImages(ImageType.Backdrop).Any());
  1037. if (parentWithBackdrop != null)
  1038. {
  1039. dto.ParentBackdropItemId = GetDtoId(parentWithBackdrop);
  1040. dto.ParentBackdropImageTags = GetBackdropImageTags(parentWithBackdrop);
  1041. }
  1042. }
  1043. if (!dto.ImageTags.ContainsKey(ImageType.Primary))
  1044. {
  1045. if (linkedChildren == null)
  1046. {
  1047. linkedChildren = user == null
  1048. ? folder.GetRecursiveChildren().ToList()
  1049. : folder.GetRecursiveChildren(user, true).ToList();
  1050. }
  1051. var parentWithImage = linkedChildren.FirstOrDefault(i => i.GetImages(ImageType.Primary).Any());
  1052. if (parentWithImage != null)
  1053. {
  1054. dto.ParentPrimaryImageItemId = GetDtoId(parentWithImage);
  1055. dto.ParentPrimaryImageTag = GetImageCacheTag(parentWithImage, ImageType.Primary);
  1056. }
  1057. }
  1058. }
  1059. private string GetMappedPath(IHasMetadata item)
  1060. {
  1061. var path = item.Path;
  1062. var locationType = item.LocationType;
  1063. if (locationType == LocationType.FileSystem || locationType == LocationType.Offline)
  1064. {
  1065. foreach (var map in _config.Configuration.PathSubstitutions)
  1066. {
  1067. path = _fileSystem.SubstitutePath(path, map.From, map.To);
  1068. }
  1069. }
  1070. return path;
  1071. }
  1072. private void SetProductionLocations(BaseItem item, BaseItemDto dto)
  1073. {
  1074. var hasProductionLocations = item as IHasProductionLocations;
  1075. if (hasProductionLocations != null)
  1076. {
  1077. dto.ProductionLocations = hasProductionLocations.ProductionLocations;
  1078. }
  1079. var person = item as Person;
  1080. if (person != null)
  1081. {
  1082. dto.ProductionLocations = new List<string>();
  1083. if (!string.IsNullOrEmpty(person.PlaceOfBirth))
  1084. {
  1085. dto.ProductionLocations.Add(person.PlaceOfBirth);
  1086. }
  1087. }
  1088. if (dto.ProductionLocations == null)
  1089. {
  1090. dto.ProductionLocations = new List<string>();
  1091. }
  1092. }
  1093. /// <summary>
  1094. /// Since it can be slow to make all of these calculations independently, this method will provide a way to do them all at once
  1095. /// </summary>
  1096. /// <param name="folder">The folder.</param>
  1097. /// <param name="user">The user.</param>
  1098. /// <param name="dto">The dto.</param>
  1099. /// <param name="fields">The fields.</param>
  1100. /// <returns>Task.</returns>
  1101. private void SetSpecialCounts(Folder folder, User user, BaseItemDto dto, List<ItemFields> fields)
  1102. {
  1103. var recursiveItemCount = 0;
  1104. var unplayed = 0;
  1105. long runtime = 0;
  1106. DateTime? dateLastMediaAdded = null;
  1107. double totalPercentPlayed = 0;
  1108. IEnumerable<BaseItem> children;
  1109. var season = folder as Season;
  1110. if (season != null)
  1111. {
  1112. children = season.GetEpisodes(user).Where(i => i.LocationType != LocationType.Virtual);
  1113. }
  1114. else
  1115. {
  1116. children = folder.GetRecursiveChildren(user)
  1117. .Where(i => !i.IsFolder && i.LocationType != LocationType.Virtual);
  1118. }
  1119. // Loop through each recursive child
  1120. foreach (var child in children)
  1121. {
  1122. if (!dateLastMediaAdded.HasValue)
  1123. {
  1124. dateLastMediaAdded = child.DateCreated;
  1125. }
  1126. else
  1127. {
  1128. dateLastMediaAdded = new[] { dateLastMediaAdded.Value, child.DateCreated }.Max();
  1129. }
  1130. var userdata = _userDataRepository.GetUserData(user.Id, child.GetUserDataKey());
  1131. recursiveItemCount++;
  1132. var isUnplayed = true;
  1133. // Incrememt totalPercentPlayed
  1134. if (userdata != null)
  1135. {
  1136. if (userdata.Played)
  1137. {
  1138. totalPercentPlayed += 100;
  1139. isUnplayed = false;
  1140. }
  1141. else if (userdata.PlaybackPositionTicks > 0 && child.RunTimeTicks.HasValue && child.RunTimeTicks.Value > 0)
  1142. {
  1143. double itemPercent = userdata.PlaybackPositionTicks;
  1144. itemPercent /= child.RunTimeTicks.Value;
  1145. totalPercentPlayed += itemPercent;
  1146. }
  1147. }
  1148. if (isUnplayed)
  1149. {
  1150. unplayed++;
  1151. }
  1152. runtime += child.RunTimeTicks ?? 0;
  1153. }
  1154. dto.RecursiveItemCount = recursiveItemCount;
  1155. dto.UserData.UnplayedItemCount = unplayed;
  1156. dto.RecursiveUnplayedItemCount = unplayed;
  1157. if (recursiveItemCount > 0)
  1158. {
  1159. dto.UserData.PlayedPercentage = totalPercentPlayed / recursiveItemCount;
  1160. }
  1161. if (runtime > 0 && fields.Contains(ItemFields.CumulativeRunTimeTicks))
  1162. {
  1163. dto.CumulativeRunTimeTicks = runtime;
  1164. }
  1165. if (fields.Contains(ItemFields.DateLastMediaAdded))
  1166. {
  1167. dto.DateLastMediaAdded = dateLastMediaAdded;
  1168. }
  1169. }
  1170. /// <summary>
  1171. /// Attaches the primary image aspect ratio.
  1172. /// </summary>
  1173. /// <param name="dto">The dto.</param>
  1174. /// <param name="item">The item.</param>
  1175. /// <returns>Task.</returns>
  1176. public void AttachPrimaryImageAspectRatio(IItemDto dto, IHasImages item)
  1177. {
  1178. var imageInfo = item.GetImageInfo(ImageType.Primary, 0);
  1179. if (imageInfo == null)
  1180. {
  1181. return;
  1182. }
  1183. var path = imageInfo.Path;
  1184. // See if we can avoid a file system lookup by looking for the file in ResolveArgs
  1185. var dateModified = imageInfo.DateModified;
  1186. ImageSize size;
  1187. try
  1188. {
  1189. size = _imageProcessor.GetImageSize(path, dateModified);
  1190. }
  1191. catch (FileNotFoundException)
  1192. {
  1193. _logger.Error("Image file does not exist: {0}", path);
  1194. return;
  1195. }
  1196. catch (Exception ex)
  1197. {
  1198. _logger.ErrorException("Failed to determine primary image aspect ratio for {0}", ex, path);
  1199. return;
  1200. }
  1201. dto.OriginalPrimaryImageAspectRatio = size.Width / size.Height;
  1202. var supportedEnhancers = _imageProcessor.GetSupportedEnhancers(item, ImageType.Primary).ToList();
  1203. foreach (var enhancer in supportedEnhancers)
  1204. {
  1205. try
  1206. {
  1207. size = enhancer.GetEnhancedImageSize(item, ImageType.Primary, 0, size);
  1208. }
  1209. catch (Exception ex)
  1210. {
  1211. _logger.ErrorException("Error in image enhancer: {0}", ex, enhancer.GetType().Name);
  1212. }
  1213. }
  1214. dto.PrimaryImageAspectRatio = size.Width / size.Height;
  1215. }
  1216. }
  1217. }