DtoService.cs 57 KB

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