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