DtoService.cs 54 KB

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