DtoService.cs 49 KB

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