DtoService.cs 50 KB

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