DtoService.cs 49 KB

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