DtoService.cs 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472
  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 episodeSeason = episode.Season;
  950. if (episodeSeason != null)
  951. {
  952. dto.SeasonId = episodeSeason.Id.ToString("N");
  953. dto.SeasonName = episodeSeason.Name;
  954. }
  955. }
  956. // Add SeriesInfo
  957. var series = item as Series;
  958. if (series != null)
  959. {
  960. dto.AirDays = series.AirDays;
  961. dto.AirTime = series.AirTime;
  962. dto.Status = series.Status;
  963. dto.SpecialFeatureCount = series.SpecialFeatureIds.Count;
  964. dto.SeasonCount = series.SeasonCount;
  965. if (fields.Contains(ItemFields.Settings))
  966. {
  967. dto.DisplaySpecialsWithSeasons = series.DisplaySpecialsWithSeasons;
  968. }
  969. dto.AnimeSeriesIndex = series.AnimeSeriesIndex;
  970. }
  971. if (episode != null)
  972. {
  973. series = episode.Series;
  974. if (series != null)
  975. {
  976. dto.SeriesId = GetDtoId(series);
  977. dto.SeriesName = series.Name;
  978. dto.AirTime = series.AirTime;
  979. dto.SeriesStudio = series.Studios.FirstOrDefault();
  980. dto.SeriesThumbImageTag = GetImageCacheTag(series, ImageType.Thumb);
  981. dto.SeriesPrimaryImageTag = GetImageCacheTag(series, ImageType.Primary);
  982. }
  983. }
  984. // Add SeasonInfo
  985. var season = item as Season;
  986. if (season != null)
  987. {
  988. series = season.Series;
  989. if (series != null)
  990. {
  991. dto.SeriesId = GetDtoId(series);
  992. dto.SeriesName = series.Name;
  993. dto.AirTime = series.AirTime;
  994. dto.SeriesStudio = series.Studios.FirstOrDefault();
  995. dto.SeriesPrimaryImageTag = GetImageCacheTag(series, ImageType.Primary);
  996. }
  997. }
  998. var game = item as Game;
  999. if (game != null)
  1000. {
  1001. SetGameProperties(dto, game);
  1002. }
  1003. var gameSystem = item as GameSystem;
  1004. if (gameSystem != null)
  1005. {
  1006. SetGameSystemProperties(dto, gameSystem);
  1007. }
  1008. var musicVideo = item as MusicVideo;
  1009. if (musicVideo != null)
  1010. {
  1011. SetMusicVideoProperties(dto, musicVideo);
  1012. }
  1013. var book = item as Book;
  1014. if (book != null)
  1015. {
  1016. SetBookProperties(dto, book);
  1017. }
  1018. var photo = item as Photo;
  1019. if (photo != null)
  1020. {
  1021. SetPhotoProperties(dto, photo);
  1022. }
  1023. var tvChannel = item as LiveTvChannel;
  1024. if (tvChannel != null)
  1025. {
  1026. dto.MediaSources = tvChannel.GetMediaSources(true).ToList();
  1027. }
  1028. var channelItem = item as IChannelItem;
  1029. if (channelItem != null)
  1030. {
  1031. dto.ChannelId = channelItem.ChannelId;
  1032. dto.ChannelName = _channelManagerFactory().GetChannel(channelItem.ChannelId).Name;
  1033. }
  1034. }
  1035. private void AttachLinkedChildImages(BaseItemDto dto, Folder folder, User user)
  1036. {
  1037. List<BaseItem> linkedChildren = null;
  1038. if (dto.BackdropImageTags.Count == 0)
  1039. {
  1040. if (linkedChildren == null)
  1041. {
  1042. linkedChildren = user == null
  1043. ? folder.GetRecursiveChildren().ToList()
  1044. : folder.GetRecursiveChildren(user, true).ToList();
  1045. }
  1046. var parentWithBackdrop = linkedChildren.FirstOrDefault(i => i.GetImages(ImageType.Backdrop).Any());
  1047. if (parentWithBackdrop != null)
  1048. {
  1049. dto.ParentBackdropItemId = GetDtoId(parentWithBackdrop);
  1050. dto.ParentBackdropImageTags = GetBackdropImageTags(parentWithBackdrop);
  1051. }
  1052. }
  1053. if (!dto.ImageTags.ContainsKey(ImageType.Primary))
  1054. {
  1055. if (linkedChildren == null)
  1056. {
  1057. linkedChildren = user == null
  1058. ? folder.GetRecursiveChildren().ToList()
  1059. : folder.GetRecursiveChildren(user, true).ToList();
  1060. }
  1061. var parentWithImage = linkedChildren.FirstOrDefault(i => i.GetImages(ImageType.Primary).Any());
  1062. if (parentWithImage != null)
  1063. {
  1064. dto.ParentPrimaryImageItemId = GetDtoId(parentWithImage);
  1065. dto.ParentPrimaryImageTag = GetImageCacheTag(parentWithImage, ImageType.Primary);
  1066. }
  1067. }
  1068. }
  1069. private string GetMappedPath(IHasMetadata item)
  1070. {
  1071. var path = item.Path;
  1072. var locationType = item.LocationType;
  1073. if (locationType == LocationType.FileSystem || locationType == LocationType.Offline)
  1074. {
  1075. foreach (var map in _config.Configuration.PathSubstitutions)
  1076. {
  1077. path = _fileSystem.SubstitutePath(path, map.From, map.To);
  1078. }
  1079. }
  1080. return path;
  1081. }
  1082. private void SetProductionLocations(BaseItem item, BaseItemDto dto)
  1083. {
  1084. var hasProductionLocations = item as IHasProductionLocations;
  1085. if (hasProductionLocations != null)
  1086. {
  1087. dto.ProductionLocations = hasProductionLocations.ProductionLocations;
  1088. }
  1089. var person = item as Person;
  1090. if (person != null)
  1091. {
  1092. dto.ProductionLocations = new List<string>();
  1093. if (!string.IsNullOrEmpty(person.PlaceOfBirth))
  1094. {
  1095. dto.ProductionLocations.Add(person.PlaceOfBirth);
  1096. }
  1097. }
  1098. if (dto.ProductionLocations == null)
  1099. {
  1100. dto.ProductionLocations = new List<string>();
  1101. }
  1102. }
  1103. /// <summary>
  1104. /// Since it can be slow to make all of these calculations independently, this method will provide a way to do them all at once
  1105. /// </summary>
  1106. /// <param name="folder">The folder.</param>
  1107. /// <param name="user">The user.</param>
  1108. /// <param name="dto">The dto.</param>
  1109. /// <param name="fields">The fields.</param>
  1110. /// <returns>Task.</returns>
  1111. private void SetSpecialCounts(Folder folder, User user, BaseItemDto dto, List<ItemFields> fields)
  1112. {
  1113. var recursiveItemCount = 0;
  1114. var unplayed = 0;
  1115. long runtime = 0;
  1116. DateTime? dateLastMediaAdded = null;
  1117. double totalPercentPlayed = 0;
  1118. IEnumerable<BaseItem> children;
  1119. var season = folder as Season;
  1120. if (season != null)
  1121. {
  1122. children = season.GetEpisodes(user).Where(i => i.LocationType != LocationType.Virtual);
  1123. }
  1124. else
  1125. {
  1126. children = folder.GetRecursiveChildren(user)
  1127. .Where(i => !i.IsFolder && i.LocationType != LocationType.Virtual);
  1128. }
  1129. // Loop through each recursive child
  1130. foreach (var child in children)
  1131. {
  1132. if (!dateLastMediaAdded.HasValue)
  1133. {
  1134. dateLastMediaAdded = child.DateCreated;
  1135. }
  1136. else
  1137. {
  1138. dateLastMediaAdded = new[] { dateLastMediaAdded.Value, child.DateCreated }.Max();
  1139. }
  1140. var userdata = _userDataRepository.GetUserData(user.Id, child.GetUserDataKey());
  1141. recursiveItemCount++;
  1142. var isUnplayed = true;
  1143. // Incrememt totalPercentPlayed
  1144. if (userdata != null)
  1145. {
  1146. if (userdata.Played)
  1147. {
  1148. totalPercentPlayed += 100;
  1149. isUnplayed = false;
  1150. }
  1151. else if (userdata.PlaybackPositionTicks > 0 && child.RunTimeTicks.HasValue && child.RunTimeTicks.Value > 0)
  1152. {
  1153. double itemPercent = userdata.PlaybackPositionTicks;
  1154. itemPercent /= child.RunTimeTicks.Value;
  1155. totalPercentPlayed += itemPercent;
  1156. }
  1157. }
  1158. if (isUnplayed)
  1159. {
  1160. unplayed++;
  1161. }
  1162. runtime += child.RunTimeTicks ?? 0;
  1163. }
  1164. dto.RecursiveItemCount = recursiveItemCount;
  1165. dto.UserData.UnplayedItemCount = unplayed;
  1166. dto.RecursiveUnplayedItemCount = unplayed;
  1167. if (recursiveItemCount > 0)
  1168. {
  1169. dto.UserData.PlayedPercentage = totalPercentPlayed / recursiveItemCount;
  1170. }
  1171. if (runtime > 0 && fields.Contains(ItemFields.CumulativeRunTimeTicks))
  1172. {
  1173. dto.CumulativeRunTimeTicks = runtime;
  1174. }
  1175. if (fields.Contains(ItemFields.DateLastMediaAdded))
  1176. {
  1177. dto.DateLastMediaAdded = dateLastMediaAdded;
  1178. }
  1179. }
  1180. /// <summary>
  1181. /// Attaches the primary image aspect ratio.
  1182. /// </summary>
  1183. /// <param name="dto">The dto.</param>
  1184. /// <param name="item">The item.</param>
  1185. /// <returns>Task.</returns>
  1186. public void AttachPrimaryImageAspectRatio(IItemDto dto, IHasImages item)
  1187. {
  1188. var imageInfo = item.GetImageInfo(ImageType.Primary, 0);
  1189. if (imageInfo == null)
  1190. {
  1191. return;
  1192. }
  1193. var path = imageInfo.Path;
  1194. // See if we can avoid a file system lookup by looking for the file in ResolveArgs
  1195. var dateModified = imageInfo.DateModified;
  1196. ImageSize size;
  1197. try
  1198. {
  1199. size = _imageProcessor.GetImageSize(path, dateModified);
  1200. }
  1201. catch (FileNotFoundException)
  1202. {
  1203. _logger.Error("Image file does not exist: {0}", path);
  1204. return;
  1205. }
  1206. catch (Exception ex)
  1207. {
  1208. _logger.ErrorException("Failed to determine primary image aspect ratio for {0}", ex, path);
  1209. return;
  1210. }
  1211. dto.OriginalPrimaryImageAspectRatio = size.Width / size.Height;
  1212. var supportedEnhancers = _imageProcessor.GetSupportedEnhancers(item, ImageType.Primary).ToList();
  1213. foreach (var enhancer in supportedEnhancers)
  1214. {
  1215. try
  1216. {
  1217. size = enhancer.GetEnhancedImageSize(item, ImageType.Primary, 0, size);
  1218. }
  1219. catch (Exception ex)
  1220. {
  1221. _logger.ErrorException("Error in image enhancer: {0}", ex, enhancer.GetType().Name);
  1222. }
  1223. }
  1224. dto.PrimaryImageAspectRatio = size.Width / size.Height;
  1225. }
  1226. }
  1227. }