DtoService.cs 58 KB

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