DtoService.cs 58 KB

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