DtoService.cs 50 KB

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