DtoService.cs 54 KB

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