DtoService.cs 56 KB

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