DtoService.cs 56 KB

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