DtoService.cs 58 KB

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