DtoService.cs 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381
  1. using System.Threading;
  2. using MediaBrowser.Common.Extensions;
  3. using MediaBrowser.Common.IO;
  4. using MediaBrowser.Controller.Channels;
  5. using MediaBrowser.Controller.Configuration;
  6. using MediaBrowser.Controller.Drawing;
  7. using MediaBrowser.Controller.Dto;
  8. using MediaBrowser.Controller.Entities;
  9. using MediaBrowser.Controller.Entities.Audio;
  10. using MediaBrowser.Controller.Entities.Movies;
  11. using MediaBrowser.Controller.Entities.TV;
  12. using MediaBrowser.Controller.Library;
  13. using MediaBrowser.Controller.LiveTv;
  14. using MediaBrowser.Controller.Persistence;
  15. using MediaBrowser.Controller.Providers;
  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 MoreLinq;
  22. using System;
  23. using System.Collections.Generic;
  24. using System.IO;
  25. using System.Linq;
  26. namespace MediaBrowser.Server.Implementations.Dto
  27. {
  28. public class DtoService : IDtoService
  29. {
  30. private readonly ILogger _logger;
  31. private readonly ILibraryManager _libraryManager;
  32. private readonly IUserManager _userManager;
  33. private readonly IUserDataManager _userDataRepository;
  34. private readonly IItemRepository _itemRepo;
  35. private readonly IImageProcessor _imageProcessor;
  36. private readonly IServerConfigurationManager _config;
  37. private readonly IFileSystem _fileSystem;
  38. private readonly IProviderManager _providerManager;
  39. private readonly Func<IChannelManager> _channelManagerFactory;
  40. public DtoService(ILogger logger, ILibraryManager libraryManager, IUserManager userManager, IUserDataManager userDataRepository, IItemRepository itemRepo, IImageProcessor imageProcessor, IServerConfigurationManager config, IFileSystem fileSystem, IProviderManager providerManager, Func<IChannelManager> channelManagerFactory)
  41. {
  42. _logger = logger;
  43. _libraryManager = libraryManager;
  44. _userManager = userManager;
  45. _userDataRepository = userDataRepository;
  46. _itemRepo = itemRepo;
  47. _imageProcessor = imageProcessor;
  48. _config = config;
  49. _fileSystem = fileSystem;
  50. _providerManager = providerManager;
  51. _channelManagerFactory = channelManagerFactory;
  52. }
  53. /// <summary>
  54. /// Converts a BaseItem to a DTOBaseItem
  55. /// </summary>
  56. /// <param name="item">The item.</param>
  57. /// <param name="fields">The fields.</param>
  58. /// <param name="user">The user.</param>
  59. /// <param name="owner">The owner.</param>
  60. /// <returns>Task{DtoBaseItem}.</returns>
  61. /// <exception cref="System.ArgumentNullException">item</exception>
  62. public BaseItemDto GetBaseItemDto(BaseItem item, List<ItemFields> fields, User user = null, BaseItem owner = null)
  63. {
  64. if (item == null)
  65. {
  66. throw new ArgumentNullException("item");
  67. }
  68. if (fields == null)
  69. {
  70. throw new ArgumentNullException("fields");
  71. }
  72. var dto = new BaseItemDto();
  73. if (fields.Contains(ItemFields.People))
  74. {
  75. AttachPeople(dto, item);
  76. }
  77. if (fields.Contains(ItemFields.PrimaryImageAspectRatio))
  78. {
  79. try
  80. {
  81. AttachPrimaryImageAspectRatio(dto, item);
  82. }
  83. catch (Exception ex)
  84. {
  85. // Have to use a catch-all unfortunately because some .net image methods throw plain Exceptions
  86. _logger.ErrorException("Error generating PrimaryImageAspectRatio for {0}", ex, item.Name);
  87. }
  88. }
  89. if (fields.Contains(ItemFields.DisplayPreferencesId))
  90. {
  91. dto.DisplayPreferencesId = item.DisplayPreferencesId.ToString("N");
  92. }
  93. if (user != null)
  94. {
  95. AttachUserSpecificInfo(dto, item, user, fields);
  96. }
  97. if (fields.Contains(ItemFields.Studios))
  98. {
  99. AttachStudios(dto, item);
  100. }
  101. AttachBasicFields(dto, item, owner, fields);
  102. if (user != null && dto.MediaSources != null && item is Video)
  103. {
  104. var preferredAudio = string.IsNullOrEmpty(user.Configuration.AudioLanguagePreference)
  105. ? new string[] { }
  106. : new[] { user.Configuration.AudioLanguagePreference };
  107. var preferredSubs = string.IsNullOrEmpty(user.Configuration.SubtitleLanguagePreference)
  108. ? new string[] { }
  109. : new[] { user.Configuration.SubtitleLanguagePreference };
  110. foreach (var source in dto.MediaSources)
  111. {
  112. source.DefaultAudioStreamIndex = MediaStreamSelector.GetDefaultAudioStreamIndex(
  113. source.MediaStreams, preferredAudio, user.Configuration.PlayDefaultAudioTrack);
  114. var defaultAudioIndex = source.DefaultAudioStreamIndex;
  115. var audioLangage = defaultAudioIndex == null
  116. ? null
  117. : source.MediaStreams.Where(i => i.Type == MediaStreamType.Audio && i.Index == defaultAudioIndex).Select(i => i.Language).FirstOrDefault();
  118. source.DefaultSubtitleStreamIndex = MediaStreamSelector.GetDefaultSubtitleStreamIndex(source.MediaStreams,
  119. preferredSubs,
  120. user.Configuration.SubtitleMode,
  121. audioLangage);
  122. }
  123. }
  124. if (fields.Contains(ItemFields.SoundtrackIds))
  125. {
  126. var hasSoundtracks = item as IHasSoundtracks;
  127. if (hasSoundtracks != null)
  128. {
  129. dto.SoundtrackIds = hasSoundtracks.SoundtrackIds
  130. .Select(i => i.ToString("N"))
  131. .ToArray();
  132. }
  133. }
  134. return dto;
  135. }
  136. public BaseItemDto GetItemByNameDto<T>(T item, List<ItemFields> fields, User user = null)
  137. where T : BaseItem, IItemByName
  138. {
  139. var libraryItems = user != null ? user.RootFolder.GetRecursiveChildren(user) :
  140. _libraryManager.RootFolder.RecursiveChildren;
  141. return GetItemByNameDto(item, fields, item.GetTaggedItems(libraryItems).ToList(), user);
  142. }
  143. public BaseItemDto GetItemByNameDto<T>(T item, List<ItemFields> fields, List<BaseItem> taggedItems, User user = null)
  144. where T : BaseItem, IItemByName
  145. {
  146. var dto = GetBaseItemDto(item, fields, user);
  147. if (item is MusicArtist || item is MusicGenre)
  148. {
  149. dto.AlbumCount = taggedItems.Count(i => i is MusicAlbum);
  150. dto.MusicVideoCount = taggedItems.Count(i => i is MusicVideo);
  151. dto.SongCount = taggedItems.Count(i => i is Audio);
  152. }
  153. else if (item is GameGenre)
  154. {
  155. dto.GameCount = taggedItems.Count(i => i is Game);
  156. }
  157. else
  158. {
  159. // This populates them all and covers Genre, Person, Studio, Year
  160. dto.AdultVideoCount = taggedItems.Count(i => i is AdultVideo);
  161. dto.AlbumCount = taggedItems.Count(i => i is MusicAlbum);
  162. dto.EpisodeCount = taggedItems.Count(i => i is Episode);
  163. dto.GameCount = taggedItems.Count(i => i is Game);
  164. dto.MovieCount = taggedItems.Count(i => i is Movie);
  165. dto.MusicVideoCount = taggedItems.Count(i => i is MusicVideo);
  166. dto.SeriesCount = taggedItems.Count(i => i is Series);
  167. dto.SongCount = taggedItems.Count(i => i is Audio);
  168. dto.TrailerCount = taggedItems.Count(i => i is Trailer);
  169. }
  170. dto.ChildCount = taggedItems.Count;
  171. return dto;
  172. }
  173. /// <summary>
  174. /// Attaches the user specific info.
  175. /// </summary>
  176. /// <param name="dto">The dto.</param>
  177. /// <param name="item">The item.</param>
  178. /// <param name="user">The user.</param>
  179. /// <param name="fields">The fields.</param>
  180. private void AttachUserSpecificInfo(BaseItemDto dto, BaseItem item, User user, List<ItemFields> fields)
  181. {
  182. if (item.IsFolder)
  183. {
  184. var folder = (Folder)item;
  185. dto.ChildCount = GetChildCount(folder, user);
  186. if (!(folder is UserRootFolder))
  187. {
  188. SetSpecialCounts(folder, user, dto, fields);
  189. }
  190. }
  191. var userData = _userDataRepository.GetUserData(user.Id, item.GetUserDataKey());
  192. dto.UserData = GetUserItemDataDto(userData);
  193. if (item.IsFolder)
  194. {
  195. dto.UserData.Played = dto.PlayedPercentage.HasValue && dto.PlayedPercentage.Value >= 100;
  196. }
  197. dto.PlayAccess = item.GetPlayAccess(user);
  198. }
  199. private int GetChildCount(Folder folder, User user)
  200. {
  201. return folder.GetChildren(user, true)
  202. .Count();
  203. }
  204. public UserDto GetUserDto(User user)
  205. {
  206. if (user == null)
  207. {
  208. throw new ArgumentNullException("user");
  209. }
  210. var dto = new UserDto
  211. {
  212. Id = user.Id.ToString("N"),
  213. Name = user.Name,
  214. HasPassword = !String.IsNullOrEmpty(user.Password),
  215. LastActivityDate = user.LastActivityDate,
  216. LastLoginDate = user.LastLoginDate,
  217. Configuration = user.Configuration
  218. };
  219. var image = user.GetImageInfo(ImageType.Primary, 0);
  220. if (image != null)
  221. {
  222. dto.PrimaryImageTag = GetImageCacheTag(user, image);
  223. try
  224. {
  225. AttachPrimaryImageAspectRatio(dto, user);
  226. }
  227. catch (Exception ex)
  228. {
  229. // Have to use a catch-all unfortunately because some .net image methods throw plain Exceptions
  230. _logger.ErrorException("Error generating PrimaryImageAspectRatio for {0}", ex, user.Name);
  231. }
  232. }
  233. return dto;
  234. }
  235. /// <summary>
  236. /// Gets client-side Id of a server-side BaseItem
  237. /// </summary>
  238. /// <param name="item">The item.</param>
  239. /// <returns>System.String.</returns>
  240. /// <exception cref="System.ArgumentNullException">item</exception>
  241. public string GetDtoId(BaseItem item)
  242. {
  243. if (item == null)
  244. {
  245. throw new ArgumentNullException("item");
  246. }
  247. return item.Id.ToString("N");
  248. }
  249. /// <summary>
  250. /// Converts a UserItemData to a DTOUserItemData
  251. /// </summary>
  252. /// <param name="data">The data.</param>
  253. /// <returns>DtoUserItemData.</returns>
  254. /// <exception cref="System.ArgumentNullException"></exception>
  255. public UserItemDataDto GetUserItemDataDto(UserItemData data)
  256. {
  257. if (data == null)
  258. {
  259. throw new ArgumentNullException("data");
  260. }
  261. return new UserItemDataDto
  262. {
  263. IsFavorite = data.IsFavorite,
  264. Likes = data.Likes,
  265. PlaybackPositionTicks = data.PlaybackPositionTicks,
  266. PlayCount = data.PlayCount,
  267. Rating = data.Rating,
  268. Played = data.Played,
  269. LastPlayedDate = data.LastPlayedDate,
  270. Key = data.Key
  271. };
  272. }
  273. private void SetBookProperties(BaseItemDto dto, Book item)
  274. {
  275. dto.SeriesName = item.SeriesName;
  276. }
  277. private void SetMusicVideoProperties(BaseItemDto dto, MusicVideo item)
  278. {
  279. if (!string.IsNullOrEmpty(item.Album))
  280. {
  281. var parentAlbum = _libraryManager.RootFolder
  282. .GetRecursiveChildren(i => i is MusicAlbum)
  283. .FirstOrDefault(i => string.Equals(i.Name, item.Album, StringComparison.OrdinalIgnoreCase));
  284. if (parentAlbum != null)
  285. {
  286. dto.AlbumId = GetDtoId(parentAlbum);
  287. }
  288. }
  289. dto.Album = item.Album;
  290. dto.Artists = string.IsNullOrEmpty(item.Artist) ? new List<string>() : new List<string> { item.Artist };
  291. }
  292. private void SetGameProperties(BaseItemDto dto, Game item)
  293. {
  294. dto.Players = item.PlayersSupported;
  295. dto.GameSystem = item.GameSystem;
  296. dto.MultiPartGameFiles = item.MultiPartGameFiles;
  297. }
  298. private void SetGameSystemProperties(BaseItemDto dto, GameSystem item)
  299. {
  300. dto.GameSystem = item.GameSystemName;
  301. }
  302. /// <summary>
  303. /// Gets the backdrop image tags.
  304. /// </summary>
  305. /// <param name="item">The item.</param>
  306. /// <returns>List{System.String}.</returns>
  307. private List<string> GetBackdropImageTags(BaseItem item)
  308. {
  309. return GetCacheTags(item, ImageType.Backdrop).ToList();
  310. }
  311. /// <summary>
  312. /// Gets the screenshot image tags.
  313. /// </summary>
  314. /// <param name="item">The item.</param>
  315. /// <returns>List{Guid}.</returns>
  316. private List<string> GetScreenshotImageTags(BaseItem item)
  317. {
  318. var hasScreenshots = item as IHasScreenshots;
  319. if (hasScreenshots == null)
  320. {
  321. return new List<string>();
  322. }
  323. return GetCacheTags(item, ImageType.Screenshot).ToList();
  324. }
  325. private IEnumerable<string> GetCacheTags(BaseItem item, ImageType type)
  326. {
  327. return item.GetImages(type)
  328. .Select(p => GetImageCacheTag(item, p))
  329. .Where(i => i != null)
  330. .ToList();
  331. }
  332. private string GetImageCacheTag(BaseItem item, ImageType type)
  333. {
  334. try
  335. {
  336. return _imageProcessor.GetImageCacheTag(item, type);
  337. }
  338. catch (Exception ex)
  339. {
  340. _logger.ErrorException("Error getting {0} image info", ex, type);
  341. return null;
  342. }
  343. }
  344. private string GetImageCacheTag(BaseItem item, ItemImageInfo image)
  345. {
  346. try
  347. {
  348. return _imageProcessor.GetImageCacheTag(item, image);
  349. }
  350. catch (Exception ex)
  351. {
  352. _logger.ErrorException("Error getting {0} image info for {1}", ex, image.Type, image.Path);
  353. return null;
  354. }
  355. }
  356. /// <summary>
  357. /// Attaches People DTO's to a DTOBaseItem
  358. /// </summary>
  359. /// <param name="dto">The dto.</param>
  360. /// <param name="item">The item.</param>
  361. /// <returns>Task.</returns>
  362. private void AttachPeople(BaseItemDto dto, BaseItem item)
  363. {
  364. // Ordering by person type to ensure actors and artists are at the front.
  365. // This is taking advantage of the fact that they both begin with A
  366. // This should be improved in the future
  367. var people = item.People.OrderBy(i => i.SortOrder ?? int.MaxValue).ThenBy(i => i.Type).ToList();
  368. // Attach People by transforming them into BaseItemPerson (DTO)
  369. dto.People = new BaseItemPerson[people.Count];
  370. var dictionary = people.Select(p => p.Name)
  371. .Distinct(StringComparer.OrdinalIgnoreCase).Select(c =>
  372. {
  373. try
  374. {
  375. return _libraryManager.GetPerson(c);
  376. }
  377. catch (IOException ex)
  378. {
  379. _logger.ErrorException("Error getting person {0}", ex, c);
  380. return null;
  381. }
  382. }).Where(i => i != null)
  383. .DistinctBy(i => i.Name)
  384. .ToDictionary(i => i.Name, StringComparer.OrdinalIgnoreCase);
  385. for (var i = 0; i < people.Count; i++)
  386. {
  387. var person = people[i];
  388. var baseItemPerson = new BaseItemPerson
  389. {
  390. Name = person.Name,
  391. Role = person.Role,
  392. Type = person.Type
  393. };
  394. Person entity;
  395. if (dictionary.TryGetValue(person.Name, out entity))
  396. {
  397. baseItemPerson.PrimaryImageTag = GetImageCacheTag(entity, ImageType.Primary);
  398. baseItemPerson.Id = entity.Id.ToString("N");
  399. }
  400. dto.People[i] = baseItemPerson;
  401. }
  402. }
  403. /// <summary>
  404. /// Attaches the studios.
  405. /// </summary>
  406. /// <param name="dto">The dto.</param>
  407. /// <param name="item">The item.</param>
  408. /// <returns>Task.</returns>
  409. private void AttachStudios(BaseItemDto dto, BaseItem item)
  410. {
  411. var studios = item.Studios.ToList();
  412. dto.Studios = new StudioDto[studios.Count];
  413. var dictionary = studios.Distinct(StringComparer.OrdinalIgnoreCase).Select(name =>
  414. {
  415. try
  416. {
  417. return _libraryManager.GetStudio(name);
  418. }
  419. catch (IOException ex)
  420. {
  421. _logger.ErrorException("Error getting studio {0}", ex, name);
  422. return null;
  423. }
  424. })
  425. .Where(i => i != null)
  426. .ToDictionary(i => i.Name, StringComparer.OrdinalIgnoreCase);
  427. for (var i = 0; i < studios.Count; i++)
  428. {
  429. var studio = studios[i];
  430. var studioDto = new StudioDto
  431. {
  432. Name = studio
  433. };
  434. Studio entity;
  435. if (dictionary.TryGetValue(studio, out entity))
  436. {
  437. studioDto.PrimaryImageTag = GetImageCacheTag(entity, ImageType.Primary);
  438. }
  439. dto.Studios[i] = studioDto;
  440. }
  441. }
  442. /// <summary>
  443. /// If an item does not any backdrops, this can be used to find the first parent that does have one
  444. /// </summary>
  445. /// <param name="item">The item.</param>
  446. /// <param name="owner">The owner.</param>
  447. /// <returns>BaseItem.</returns>
  448. private BaseItem GetParentBackdropItem(BaseItem item, BaseItem owner)
  449. {
  450. var parent = item.Parent ?? owner;
  451. while (parent != null)
  452. {
  453. if (parent.GetImages(ImageType.Backdrop).Any())
  454. {
  455. return parent;
  456. }
  457. parent = parent.Parent;
  458. }
  459. return null;
  460. }
  461. /// <summary>
  462. /// If an item does not have a logo, this can be used to find the first parent that does have one
  463. /// </summary>
  464. /// <param name="item">The item.</param>
  465. /// <param name="type">The type.</param>
  466. /// <param name="owner">The owner.</param>
  467. /// <returns>BaseItem.</returns>
  468. private BaseItem GetParentImageItem(BaseItem item, ImageType type, BaseItem owner)
  469. {
  470. var parent = item.Parent ?? owner;
  471. while (parent != null)
  472. {
  473. if (parent.HasImage(type))
  474. {
  475. return parent;
  476. }
  477. parent = parent.Parent;
  478. }
  479. return null;
  480. }
  481. /// <summary>
  482. /// Gets the chapter info dto.
  483. /// </summary>
  484. /// <param name="chapterInfo">The chapter info.</param>
  485. /// <param name="item">The item.</param>
  486. /// <returns>ChapterInfoDto.</returns>
  487. public ChapterInfoDto GetChapterInfoDto(ChapterInfo chapterInfo, BaseItem item)
  488. {
  489. var dto = new ChapterInfoDto
  490. {
  491. Name = chapterInfo.Name,
  492. StartPositionTicks = chapterInfo.StartPositionTicks
  493. };
  494. if (!string.IsNullOrEmpty(chapterInfo.ImagePath))
  495. {
  496. dto.ImageTag = GetImageCacheTag(item, new ItemImageInfo
  497. {
  498. Path = chapterInfo.ImagePath,
  499. Type = ImageType.Chapter,
  500. DateModified = _fileSystem.GetLastWriteTimeUtc(chapterInfo.ImagePath)
  501. });
  502. }
  503. return dto;
  504. }
  505. /// <summary>
  506. /// Sets simple property values on a DTOBaseItem
  507. /// </summary>
  508. /// <param name="dto">The dto.</param>
  509. /// <param name="item">The item.</param>
  510. /// <param name="owner">The owner.</param>
  511. /// <param name="fields">The fields.</param>
  512. private void AttachBasicFields(BaseItemDto dto, BaseItem item, BaseItem owner, List<ItemFields> fields)
  513. {
  514. if (fields.Contains(ItemFields.DateCreated))
  515. {
  516. dto.DateCreated = item.DateCreated;
  517. }
  518. if (fields.Contains(ItemFields.DisplayMediaType))
  519. {
  520. dto.DisplayMediaType = item.DisplayMediaType;
  521. }
  522. dto.IsUnidentified = item.IsUnidentified;
  523. if (fields.Contains(ItemFields.Settings))
  524. {
  525. dto.LockedFields = item.LockedFields;
  526. dto.LockData = item.IsLocked;
  527. dto.ForcedSortName = item.ForcedSortName;
  528. }
  529. var hasBudget = item as IHasBudget;
  530. if (hasBudget != null)
  531. {
  532. if (fields.Contains(ItemFields.Budget))
  533. {
  534. dto.Budget = hasBudget.Budget;
  535. }
  536. if (fields.Contains(ItemFields.Revenue))
  537. {
  538. dto.Revenue = hasBudget.Revenue;
  539. }
  540. }
  541. dto.EndDate = item.EndDate;
  542. if (fields.Contains(ItemFields.HomePageUrl))
  543. {
  544. dto.HomePageUrl = item.HomePageUrl;
  545. }
  546. if (fields.Contains(ItemFields.ExternalUrls))
  547. {
  548. dto.ExternalUrls = _providerManager.GetExternalUrls(item).ToArray();
  549. }
  550. if (fields.Contains(ItemFields.Tags))
  551. {
  552. var hasTags = item as IHasTags;
  553. if (hasTags != null)
  554. {
  555. dto.Tags = hasTags.Tags;
  556. }
  557. if (dto.Tags == null)
  558. {
  559. dto.Tags = new List<string>();
  560. }
  561. }
  562. if (fields.Contains(ItemFields.Keywords))
  563. {
  564. var hasTags = item as IHasKeywords;
  565. if (hasTags != null)
  566. {
  567. dto.Keywords = hasTags.Keywords;
  568. }
  569. if (dto.Keywords == null)
  570. {
  571. dto.Keywords = new List<string>();
  572. }
  573. }
  574. if (fields.Contains(ItemFields.ProductionLocations))
  575. {
  576. SetProductionLocations(item, dto);
  577. }
  578. var hasAspectRatio = item as IHasAspectRatio;
  579. if (hasAspectRatio != null)
  580. {
  581. dto.AspectRatio = hasAspectRatio.AspectRatio;
  582. }
  583. var hasMetascore = item as IHasMetascore;
  584. if (hasMetascore != null)
  585. {
  586. dto.Metascore = hasMetascore.Metascore;
  587. }
  588. if (fields.Contains(ItemFields.AwardSummary))
  589. {
  590. var hasAwards = item as IHasAwards;
  591. if (hasAwards != null)
  592. {
  593. dto.AwardSummary = hasAwards.AwardSummary;
  594. }
  595. }
  596. dto.BackdropImageTags = GetBackdropImageTags(item);
  597. if (fields.Contains(ItemFields.ScreenshotImageTags))
  598. {
  599. dto.ScreenshotImageTags = GetScreenshotImageTags(item);
  600. }
  601. if (fields.Contains(ItemFields.Genres))
  602. {
  603. dto.Genres = item.Genres;
  604. }
  605. dto.ImageTags = new Dictionary<ImageType, string>();
  606. // Prevent implicitly captured closure
  607. var currentItem = item;
  608. foreach (var image in currentItem.ImageInfos.Where(i => !currentItem.AllowsMultipleImages(i.Type)))
  609. {
  610. var tag = GetImageCacheTag(item, image);
  611. if (tag != null)
  612. {
  613. dto.ImageTags[image.Type] = tag;
  614. }
  615. }
  616. dto.Id = GetDtoId(item);
  617. dto.IndexNumber = item.IndexNumber;
  618. dto.IsFolder = item.IsFolder;
  619. dto.MediaType = item.MediaType;
  620. dto.LocationType = item.LocationType;
  621. var hasLang = item as IHasPreferredMetadataLanguage;
  622. if (hasLang != null)
  623. {
  624. dto.PreferredMetadataCountryCode = hasLang.PreferredMetadataCountryCode;
  625. dto.PreferredMetadataLanguage = hasLang.PreferredMetadataLanguage;
  626. }
  627. var hasCriticRating = item as IHasCriticRating;
  628. if (hasCriticRating != null)
  629. {
  630. dto.CriticRating = hasCriticRating.CriticRating;
  631. if (fields.Contains(ItemFields.CriticRatingSummary))
  632. {
  633. dto.CriticRatingSummary = hasCriticRating.CriticRatingSummary;
  634. }
  635. }
  636. var hasTrailers = item as IHasTrailers;
  637. if (hasTrailers != null)
  638. {
  639. dto.LocalTrailerCount = hasTrailers.LocalTrailerIds.Count;
  640. }
  641. var hasDisplayOrder = item as IHasDisplayOrder;
  642. if (hasDisplayOrder != null)
  643. {
  644. dto.DisplayOrder = hasDisplayOrder.DisplayOrder;
  645. }
  646. var collectionFolder = item as CollectionFolder;
  647. if (collectionFolder != null)
  648. {
  649. dto.CollectionType = collectionFolder.CollectionType;
  650. }
  651. var userView = item as UserView;
  652. if (userView != null)
  653. {
  654. dto.CollectionType = userView.ViewType;
  655. }
  656. if (fields.Contains(ItemFields.RemoteTrailers))
  657. {
  658. dto.RemoteTrailers = hasTrailers != null ?
  659. hasTrailers.RemoteTrailers :
  660. new List<MediaUrl>();
  661. }
  662. dto.Name = item.Name;
  663. dto.OfficialRating = item.OfficialRating;
  664. if (fields.Contains(ItemFields.Overview))
  665. {
  666. // TODO: Remove this after a while, since it's been moved to the providers
  667. if (item is MusicArtist)
  668. {
  669. var strippedOverview = string.IsNullOrEmpty(item.Overview) ? item.Overview : item.Overview.StripHtml();
  670. dto.Overview = strippedOverview;
  671. }
  672. else
  673. {
  674. dto.Overview = item.Overview;
  675. }
  676. }
  677. // If there are no backdrops, indicate what parent has them in case the Ui wants to allow inheritance
  678. if (dto.BackdropImageTags.Count == 0)
  679. {
  680. var parentWithBackdrop = GetParentBackdropItem(item, owner);
  681. if (parentWithBackdrop != null)
  682. {
  683. dto.ParentBackdropItemId = GetDtoId(parentWithBackdrop);
  684. dto.ParentBackdropImageTags = GetBackdropImageTags(parentWithBackdrop);
  685. }
  686. }
  687. if (item.Parent != null && fields.Contains(ItemFields.ParentId))
  688. {
  689. dto.ParentId = GetDtoId(item.Parent);
  690. }
  691. dto.ParentIndexNumber = item.ParentIndexNumber;
  692. // If there is no logo, indicate what parent has one in case the Ui wants to allow inheritance
  693. if (!dto.HasLogo)
  694. {
  695. var parentWithLogo = GetParentImageItem(item, ImageType.Logo, owner);
  696. if (parentWithLogo != null)
  697. {
  698. dto.ParentLogoItemId = GetDtoId(parentWithLogo);
  699. dto.ParentLogoImageTag = GetImageCacheTag(parentWithLogo, ImageType.Logo);
  700. }
  701. }
  702. // If there is no art, indicate what parent has one in case the Ui wants to allow inheritance
  703. if (!dto.HasArtImage)
  704. {
  705. var parentWithImage = GetParentImageItem(item, ImageType.Art, owner);
  706. if (parentWithImage != null)
  707. {
  708. dto.ParentArtItemId = GetDtoId(parentWithImage);
  709. dto.ParentArtImageTag = GetImageCacheTag(parentWithImage, ImageType.Art);
  710. }
  711. }
  712. // If there is no thumb, indicate what parent has one in case the Ui wants to allow inheritance
  713. if (!dto.HasThumb)
  714. {
  715. var parentWithImage = GetParentImageItem(item, ImageType.Thumb, owner);
  716. if (parentWithImage != null)
  717. {
  718. dto.ParentThumbItemId = GetDtoId(parentWithImage);
  719. dto.ParentThumbImageTag = GetImageCacheTag(parentWithImage, ImageType.Thumb);
  720. }
  721. }
  722. if (fields.Contains(ItemFields.Path))
  723. {
  724. dto.Path = GetMappedPath(item);
  725. }
  726. dto.PremiereDate = item.PremiereDate;
  727. dto.ProductionYear = item.ProductionYear;
  728. if (fields.Contains(ItemFields.ProviderIds))
  729. {
  730. dto.ProviderIds = item.ProviderIds;
  731. }
  732. dto.RunTimeTicks = item.RunTimeTicks;
  733. if (fields.Contains(ItemFields.SortName))
  734. {
  735. dto.SortName = item.SortName;
  736. }
  737. if (fields.Contains(ItemFields.CustomRating))
  738. {
  739. dto.CustomRating = item.CustomRating;
  740. }
  741. if (fields.Contains(ItemFields.Taglines))
  742. {
  743. var hasTagline = item as IHasTaglines;
  744. if (hasTagline != null)
  745. {
  746. dto.Taglines = hasTagline.Taglines;
  747. }
  748. if (dto.Taglines == null)
  749. {
  750. dto.Taglines = new List<string>();
  751. }
  752. }
  753. dto.Type = item.GetClientTypeName();
  754. dto.CommunityRating = item.CommunityRating;
  755. dto.VoteCount = item.VoteCount;
  756. if (item.IsFolder)
  757. {
  758. var folder = (Folder)item;
  759. if (fields.Contains(ItemFields.IndexOptions))
  760. {
  761. dto.IndexOptions = folder.IndexByOptionStrings.ToArray();
  762. }
  763. }
  764. var supportsPlaceHolders = item as ISupportsPlaceHolders;
  765. if (supportsPlaceHolders != null)
  766. {
  767. dto.IsPlaceHolder = supportsPlaceHolders.IsPlaceHolder;
  768. }
  769. // Add audio info
  770. var audio = item as Audio;
  771. if (audio != null)
  772. {
  773. dto.Album = audio.Album;
  774. dto.Artists = audio.Artists;
  775. var albumParent = audio.FindParent<MusicAlbum>();
  776. if (albumParent != null)
  777. {
  778. dto.AlbumId = GetDtoId(albumParent);
  779. dto.AlbumPrimaryImageTag = GetImageCacheTag(albumParent, ImageType.Primary);
  780. }
  781. dto.MediaSourceCount = 1;
  782. if (fields.Contains(ItemFields.MediaSources))
  783. {
  784. dto.MediaSources = GetMediaSources(audio);
  785. }
  786. }
  787. var album = item as MusicAlbum;
  788. if (album != null)
  789. {
  790. dto.Artists = album.Artists;
  791. dto.SoundtrackIds = album.SoundtrackIds
  792. .Select(i => i.ToString("N"))
  793. .ToArray();
  794. }
  795. var hasAlbumArtist = item as IHasAlbumArtist;
  796. if (hasAlbumArtist != null)
  797. {
  798. dto.AlbumArtist = hasAlbumArtist.AlbumArtist;
  799. }
  800. // Add video info
  801. var video = item as Video;
  802. if (video != null)
  803. {
  804. dto.VideoType = video.VideoType;
  805. dto.Video3DFormat = video.Video3DFormat;
  806. dto.IsoType = video.IsoType;
  807. dto.IsHD = video.IsHD;
  808. dto.PartCount = video.AdditionalPartIds.Count + 1;
  809. dto.MediaSourceCount = video.MediaSourceCount;
  810. if (fields.Contains(ItemFields.MediaSources))
  811. {
  812. dto.MediaSources = GetMediaSources(video);
  813. }
  814. if (fields.Contains(ItemFields.Chapters))
  815. {
  816. List<ChapterInfoDto> chapters;
  817. if (dto.MediaSources != null && dto.MediaSources.Count > 0)
  818. {
  819. chapters = _itemRepo.GetChapters(item.Id).Select(c => GetChapterInfoDto(c, item)).ToList();
  820. }
  821. else
  822. {
  823. chapters = _itemRepo.GetChapters(video.Id)
  824. .Select(c => GetChapterInfoDto(c, item))
  825. .ToList();
  826. }
  827. dto.Chapters = chapters;
  828. }
  829. }
  830. if (fields.Contains(ItemFields.MediaStreams))
  831. {
  832. // Add VideoInfo
  833. var iHasMediaStreams = item as IHasMediaStreams;
  834. if (iHasMediaStreams != null)
  835. {
  836. List<MediaStream> mediaStreams;
  837. if (dto.MediaSources != null && dto.MediaSources.Count > 0)
  838. {
  839. mediaStreams = dto.MediaSources.Where(i => new Guid(i.Id) == item.Id)
  840. .SelectMany(i => i.MediaStreams)
  841. .ToList();
  842. }
  843. else
  844. {
  845. mediaStreams = _itemRepo.GetMediaStreams(new MediaStreamQuery
  846. {
  847. ItemId = item.Id
  848. }).ToList();
  849. }
  850. dto.MediaStreams = mediaStreams;
  851. }
  852. }
  853. // Add MovieInfo
  854. var movie = item as Movie;
  855. if (movie != null)
  856. {
  857. var specialFeatureCount = movie.SpecialFeatureIds.Count;
  858. if (specialFeatureCount > 0)
  859. {
  860. dto.SpecialFeatureCount = specialFeatureCount;
  861. }
  862. if (fields.Contains(ItemFields.TmdbCollectionName))
  863. {
  864. dto.TmdbCollectionName = movie.TmdbCollectionName;
  865. }
  866. }
  867. // Add EpisodeInfo
  868. var episode = item as Episode;
  869. if (episode != null)
  870. {
  871. dto.IndexNumberEnd = episode.IndexNumberEnd;
  872. dto.DvdSeasonNumber = episode.DvdSeasonNumber;
  873. dto.DvdEpisodeNumber = episode.DvdEpisodeNumber;
  874. dto.AirsAfterSeasonNumber = episode.AirsAfterSeasonNumber;
  875. dto.AirsBeforeEpisodeNumber = episode.AirsBeforeEpisodeNumber;
  876. dto.AirsBeforeSeasonNumber = episode.AirsBeforeSeasonNumber;
  877. dto.AbsoluteEpisodeNumber = episode.AbsoluteEpisodeNumber;
  878. var seasonId = episode.SeasonId;
  879. if (seasonId.HasValue)
  880. {
  881. dto.SeasonId = seasonId.Value.ToString("N");
  882. }
  883. }
  884. // Add SeriesInfo
  885. var series = item as Series;
  886. if (series != null)
  887. {
  888. dto.AirDays = series.AirDays;
  889. dto.AirTime = series.AirTime;
  890. dto.Status = series.Status;
  891. dto.SpecialFeatureCount = series.SpecialFeatureIds.Count;
  892. dto.SeasonCount = series.SeasonCount;
  893. if (fields.Contains(ItemFields.Settings))
  894. {
  895. dto.DisplaySpecialsWithSeasons = series.DisplaySpecialsWithSeasons;
  896. }
  897. dto.AnimeSeriesIndex = series.AnimeSeriesIndex;
  898. }
  899. if (episode != null)
  900. {
  901. series = item.FindParent<Series>();
  902. dto.SeriesId = GetDtoId(series);
  903. dto.SeriesName = series.Name;
  904. dto.AirTime = series.AirTime;
  905. dto.SeriesStudio = series.Studios.FirstOrDefault();
  906. dto.SeriesThumbImageTag = GetImageCacheTag(series, ImageType.Thumb);
  907. dto.SeriesPrimaryImageTag = GetImageCacheTag(series, ImageType.Primary);
  908. }
  909. // Add SeasonInfo
  910. var season = item as Season;
  911. if (season != null)
  912. {
  913. series = item.FindParent<Series>();
  914. dto.SeriesId = GetDtoId(series);
  915. dto.SeriesName = series.Name;
  916. dto.AirTime = series.AirTime;
  917. dto.SeriesStudio = series.Studios.FirstOrDefault();
  918. dto.SeriesPrimaryImageTag = GetImageCacheTag(series, ImageType.Primary);
  919. }
  920. var game = item as Game;
  921. if (game != null)
  922. {
  923. SetGameProperties(dto, game);
  924. }
  925. var gameSystem = item as GameSystem;
  926. if (gameSystem != null)
  927. {
  928. SetGameSystemProperties(dto, gameSystem);
  929. }
  930. var musicVideo = item as MusicVideo;
  931. if (musicVideo != null)
  932. {
  933. SetMusicVideoProperties(dto, musicVideo);
  934. }
  935. var book = item as Book;
  936. if (book != null)
  937. {
  938. SetBookProperties(dto, book);
  939. }
  940. var tvChannel = item as LiveTvChannel;
  941. if (tvChannel != null)
  942. {
  943. dto.MediaSources = GetMediaSources(tvChannel);
  944. }
  945. var channelItem = item as IChannelItem;
  946. if (channelItem != null)
  947. {
  948. dto.ChannelId = channelItem.ChannelId;
  949. dto.ChannelName = _channelManagerFactory().GetChannel(channelItem.ChannelId).Name;
  950. }
  951. }
  952. public List<MediaSourceInfo> GetMediaSources(BaseItem item)
  953. {
  954. var video = item as Video;
  955. if (video != null)
  956. {
  957. return video.GetMediaSources(true).ToList();
  958. }
  959. var audio = item as Audio;
  960. if (audio != null)
  961. {
  962. return audio.GetMediaSources(true).ToList();
  963. }
  964. var result = new List<MediaSourceInfo>
  965. {
  966. new MediaSourceInfo
  967. {
  968. Id = item.Id.ToString("N"),
  969. LocationType = item.LocationType,
  970. Name = item.Name,
  971. Path = GetMappedPath(item),
  972. MediaStreams = _itemRepo.GetMediaStreams(new MediaStreamQuery
  973. {
  974. ItemId = item.Id
  975. }).ToList(),
  976. RunTimeTicks = item.RunTimeTicks
  977. }
  978. };
  979. return result;
  980. }
  981. private string GetMappedPath(IHasMetadata item)
  982. {
  983. var path = item.Path;
  984. var locationType = item.LocationType;
  985. if (locationType == LocationType.FileSystem || locationType == LocationType.Offline)
  986. {
  987. foreach (var map in _config.Configuration.PathSubstitutions)
  988. {
  989. path = _fileSystem.SubstitutePath(path, map.From, map.To);
  990. }
  991. }
  992. return path;
  993. }
  994. private void SetProductionLocations(BaseItem item, BaseItemDto dto)
  995. {
  996. var hasProductionLocations = item as IHasProductionLocations;
  997. if (hasProductionLocations != null)
  998. {
  999. dto.ProductionLocations = hasProductionLocations.ProductionLocations;
  1000. }
  1001. var person = item as Person;
  1002. if (person != null)
  1003. {
  1004. dto.ProductionLocations = new List<string>();
  1005. if (!string.IsNullOrEmpty(person.PlaceOfBirth))
  1006. {
  1007. dto.ProductionLocations.Add(person.PlaceOfBirth);
  1008. }
  1009. }
  1010. if (dto.ProductionLocations == null)
  1011. {
  1012. dto.ProductionLocations = new List<string>();
  1013. }
  1014. }
  1015. /// <summary>
  1016. /// Since it can be slow to make all of these calculations independently, this method will provide a way to do them all at once
  1017. /// </summary>
  1018. /// <param name="folder">The folder.</param>
  1019. /// <param name="user">The user.</param>
  1020. /// <param name="dto">The dto.</param>
  1021. /// <param name="fields">The fields.</param>
  1022. /// <returns>Task.</returns>
  1023. private void SetSpecialCounts(Folder folder, User user, BaseItemDto dto, List<ItemFields> fields)
  1024. {
  1025. var recursiveItemCount = 0;
  1026. var unplayed = 0;
  1027. long runtime = 0;
  1028. DateTime? dateLastMediaAdded = null;
  1029. double totalPercentPlayed = 0;
  1030. IEnumerable<BaseItem> children;
  1031. var season = folder as Season;
  1032. if (season != null)
  1033. {
  1034. children = season.GetEpisodes(user).Where(i => i.LocationType != LocationType.Virtual);
  1035. }
  1036. else
  1037. {
  1038. children = folder.GetRecursiveChildren(user, i => !i.IsFolder && i.LocationType != LocationType.Virtual);
  1039. }
  1040. // Loop through each recursive child
  1041. foreach (var child in children)
  1042. {
  1043. if (!dateLastMediaAdded.HasValue)
  1044. {
  1045. dateLastMediaAdded = child.DateCreated;
  1046. }
  1047. else
  1048. {
  1049. dateLastMediaAdded = new[] { dateLastMediaAdded.Value, child.DateCreated }.Max();
  1050. }
  1051. var userdata = _userDataRepository.GetUserData(user.Id, child.GetUserDataKey());
  1052. recursiveItemCount++;
  1053. var isUnplayed = true;
  1054. // Incrememt totalPercentPlayed
  1055. if (userdata != null)
  1056. {
  1057. if (userdata.Played)
  1058. {
  1059. totalPercentPlayed += 100;
  1060. isUnplayed = false;
  1061. }
  1062. else if (userdata.PlaybackPositionTicks > 0 && child.RunTimeTicks.HasValue && child.RunTimeTicks.Value > 0)
  1063. {
  1064. double itemPercent = userdata.PlaybackPositionTicks;
  1065. itemPercent /= child.RunTimeTicks.Value;
  1066. totalPercentPlayed += itemPercent;
  1067. }
  1068. }
  1069. if (isUnplayed)
  1070. {
  1071. unplayed++;
  1072. }
  1073. runtime += child.RunTimeTicks ?? 0;
  1074. }
  1075. dto.RecursiveItemCount = recursiveItemCount;
  1076. dto.RecursiveUnplayedItemCount = unplayed;
  1077. if (recursiveItemCount > 0)
  1078. {
  1079. dto.PlayedPercentage = totalPercentPlayed / recursiveItemCount;
  1080. }
  1081. if (runtime > 0 && fields.Contains(ItemFields.CumulativeRunTimeTicks))
  1082. {
  1083. dto.CumulativeRunTimeTicks = runtime;
  1084. }
  1085. if (fields.Contains(ItemFields.DateLastMediaAdded))
  1086. {
  1087. dto.DateLastMediaAdded = dateLastMediaAdded;
  1088. }
  1089. }
  1090. /// <summary>
  1091. /// Attaches the primary image aspect ratio.
  1092. /// </summary>
  1093. /// <param name="dto">The dto.</param>
  1094. /// <param name="item">The item.</param>
  1095. /// <returns>Task.</returns>
  1096. public void AttachPrimaryImageAspectRatio(IItemDto dto, IHasImages item)
  1097. {
  1098. var imageInfo = item.GetImageInfo(ImageType.Primary, 0);
  1099. if (imageInfo == null)
  1100. {
  1101. return;
  1102. }
  1103. var path = imageInfo.Path;
  1104. // See if we can avoid a file system lookup by looking for the file in ResolveArgs
  1105. var dateModified = imageInfo.DateModified;
  1106. ImageSize size;
  1107. try
  1108. {
  1109. size = _imageProcessor.GetImageSize(path, dateModified);
  1110. }
  1111. catch (FileNotFoundException)
  1112. {
  1113. _logger.Error("Image file does not exist: {0}", path);
  1114. return;
  1115. }
  1116. catch (Exception ex)
  1117. {
  1118. _logger.ErrorException("Failed to determine primary image aspect ratio for {0}", ex, path);
  1119. return;
  1120. }
  1121. dto.OriginalPrimaryImageAspectRatio = size.Width / size.Height;
  1122. var supportedEnhancers = _imageProcessor.GetSupportedEnhancers(item, ImageType.Primary).ToList();
  1123. foreach (var enhancer in supportedEnhancers)
  1124. {
  1125. try
  1126. {
  1127. size = enhancer.GetEnhancedImageSize(item, ImageType.Primary, 0, size);
  1128. }
  1129. catch (Exception ex)
  1130. {
  1131. _logger.ErrorException("Error in image enhancer: {0}", ex, enhancer.GetType().Name);
  1132. }
  1133. }
  1134. dto.PrimaryImageAspectRatio = size.Width / size.Height;
  1135. }
  1136. }
  1137. }