DtoService.cs 57 KB

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