DtoService.cs 54 KB

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