DtoService.cs 58 KB

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