DtoService.cs 54 KB

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