DtoService.cs 58 KB

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