DtoService.cs 57 KB

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