DtoService.cs 54 KB

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