DtoService.cs 54 KB

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