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