DtoService.cs 50 KB

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