DtoService.cs 56 KB

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