DtoService.cs 50 KB

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